Spaces:
Runtime error
Runtime error
Download src/main.rs from arami21/auth-login: direct link, hf CLI and curl.
- Browser
- Download file 6.69 kB
-
https://huggingface.co/spaces/arami21/auth-login/resolve/main/src/main.rs
- Command line
-
hf download hf://spaces/arami21/auth-login/src/main.rs
-
curl -L -o main.rs https://huggingface.co/spaces/arami21/auth-login/resolve/main/src/main.rs
6.69 kB
| use actix_identity::{Identity, IdentityMiddleware}; | |
| use actix_session::{SessionMiddleware, config::PersistentSession, storage::RedisSessionStore}; | |
| use actix_web::{ | |
| App, Error, HttpMessage, HttpRequest, HttpResponse, HttpServer, Responder, | |
| body::BoxBody, | |
| cookie::{Key, time::Duration}, | |
| dev::{ServiceRequest, ServiceResponse}, | |
| get, | |
| middleware::{Next, from_fn}, | |
| post, | |
| web::{self, Data}, | |
| }; | |
| use argon2::{ | |
| Argon2, PasswordHash, PasswordHasher, PasswordVerifier, | |
| password_hash::{SaltString, rand_core::OsRng}, | |
| }; | |
| use serde::Deserialize; | |
| use sqlx::{PgPool, prelude::FromRow}; | |
| async fn main() -> std::io::Result<()> { | |
| println!("Start Program"); | |
| dotenvy::dotenv().ok(); | |
| println!("Load Env Ok"); | |
| let pool = match db().await { | |
| Ok(pool) => { | |
| println!("Database connected!"); | |
| pool | |
| } | |
| Err(err) => { | |
| eprintln!("Database error : {}", err); | |
| return Err(std::io::Error::new( | |
| std::io::ErrorKind::Other, | |
| "Failed Connect Database!", | |
| )); | |
| } | |
| }; | |
| println!("Database Connection!"); | |
| let secret_key = std::env::var("SECRET_KEY").expect("SECRET_KEY not found"); | |
| println!("secrect key ok!"); | |
| let key = Key::from(secret_key.as_bytes()); | |
| println!("redis url ok!"); | |
| let redis_url = std::env::var("REDIS_URL").expect("REDIS_URL not found"); | |
| let session_store = RedisSessionStore::new(redis_url).await.unwrap(); | |
| println!("session redis ok!"); | |
| println!("Start Server!"); | |
| HttpServer::new(move || { | |
| App::new() | |
| .app_data(Data::new(pool.clone())) | |
| .wrap(IdentityMiddleware::builder().build()) | |
| .wrap( | |
| SessionMiddleware::builder(session_store.clone(), key.clone()) | |
| .session_lifecycle( | |
| PersistentSession::default().session_ttl(Duration::minutes(15)), | |
| ) | |
| .build(), | |
| ) | |
| .service(index) | |
| .service(login) | |
| .service(register) | |
| .service(logout) | |
| .service(web::scope("api").wrap(from_fn(auth)).service(protected)) | |
| }) | |
| .bind(("0.0.0.0", 7860))? | |
| .run() | |
| .await | |
| } | |
| async fn db() -> Result<PgPool, sqlx::Error> { | |
| let database_url = std::env::var("DATABASE_URL").expect("Database url not found!"); | |
| let pool = sqlx::postgres::PgPoolOptions::new() | |
| .max_connections(15) | |
| .acquire_timeout(std::time::Duration::from_secs(10)) | |
| .connect(&database_url) | |
| .await?; | |
| Ok(pool) | |
| } | |
| fn hash_password(password: String) -> String { | |
| let salt = SaltString::generate(&mut OsRng); | |
| let argon2 = Argon2::default(); | |
| let hashed_password = argon2 | |
| .hash_password(&password.as_bytes(), &salt) | |
| .unwrap() | |
| .to_string(); | |
| hashed_password | |
| } | |
| fn verify_password( | |
| password: String, | |
| hashed_password: String, | |
| ) -> Result<(), argon2::password_hash::Error> { | |
| let argon2 = Argon2::default(); | |
| let hashed_password = PasswordHash::new(&hashed_password).unwrap(); | |
| argon2.verify_password(password.as_bytes(), &hashed_password) | |
| } | |
| async fn register(pool: web::Data<PgPool>, user_request: web::Json<UserRequest>) -> impl Responder { | |
| if user_request.username.trim() == "" || user_request.password == "" { | |
| HttpResponse::BadRequest().body("Username or Password must be not empty!") | |
| } else { | |
| let rows: Vec<UserSql> = sqlx::query_as("SELECT * FROM users WHERE username = $1") | |
| .persistent(false) | |
| .bind(&user_request.username) | |
| .fetch_all(pool.get_ref()) | |
| .await | |
| .unwrap(); | |
| if rows.len() == 0 { | |
| let hashed_password = hash_password(user_request.password.clone()); | |
| sqlx::query("INSERT INTO users (username, password) VALUES ($1, $2)") | |
| .persistent(false) | |
| .bind(&user_request.username) | |
| .bind(&hashed_password) | |
| .execute(pool.get_ref()) | |
| .await | |
| .unwrap(); | |
| HttpResponse::Ok().body("Register Successful!") | |
| } else { | |
| HttpResponse::BadRequest().body("Username is already taken!") | |
| } | |
| } | |
| } | |
| async fn login( | |
| pool: web::Data<PgPool>, | |
| user_request: web::Json<UserRequest>, | |
| req: HttpRequest, | |
| ) -> impl Responder { | |
| if user_request.username.trim() == "" || user_request.password == "" { | |
| HttpResponse::BadRequest().body("Username or Password must be not empty!") | |
| } else { | |
| let rows: Vec<UserSql> = sqlx::query_as("SELECT * FROM users WHERE username = $1") | |
| .persistent(false) | |
| .bind(&user_request.username) | |
| .fetch_all(pool.get_ref()) | |
| .await | |
| .unwrap(); | |
| if rows.len() == 0 { | |
| HttpResponse::NotFound().body("username is not Registered!") | |
| } else { | |
| match verify_password(user_request.password.clone(), rows[0].password.clone()) { | |
| Ok(_) => { | |
| Identity::login(&req.extensions(), user_request.username.clone().into()) | |
| .unwrap(); | |
| HttpResponse::Ok().body("Login Successful!") | |
| } | |
| Err(_) => HttpResponse::Unauthorized().body("Password is incorrect!"), | |
| } | |
| } | |
| } | |
| } | |
| async fn logout(id: Option<Identity>) -> impl Responder { | |
| if let Some(id) = id { | |
| id.logout(); | |
| HttpResponse::Ok().body("Logout Successful!") | |
| } else { | |
| HttpResponse::BadRequest().body("Logout Failed") | |
| } | |
| } | |
| async fn index() -> impl Responder { | |
| "Hello World!" | |
| } | |
| async fn protected(req: HttpRequest) -> impl Responder { | |
| match req.extensions().get::<String>().cloned() { | |
| Some(user) => { | |
| let msg = format!("Hello {}, welcome!", user); | |
| HttpResponse::Ok().body(msg) | |
| } | |
| None => HttpResponse::NotFound().body("No User!"), | |
| } | |
| } | |
| async fn auth( | |
| id: Option<Identity>, | |
| req: ServiceRequest, | |
| next: Next<BoxBody>, | |
| ) -> Result<ServiceResponse<BoxBody>, Error> { | |
| if let Some(id) = id { | |
| let user = id.id().unwrap(); | |
| req.extensions_mut().insert(user); | |
| next.call(req).await | |
| } else { | |
| Ok(req.into_response(HttpResponse::Unauthorized().body("You are Unauthorized"))) | |
| } | |
| } | |
| struct UserRequest { | |
| username: String, | |
| password: String, | |
| } | |
| struct UserSql { | |
| id: i32, | |
| username: String, | |
| password: String, | |
| } | |