Started working on user authentication
This commit is contained in:
25
src/main.rs
25
src/main.rs
@@ -1,3 +1,24 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
mod users;
|
||||
|
||||
use std::sync::Mutex;
|
||||
use users::*;
|
||||
|
||||
use actix_web::{App, HttpServer};
|
||||
use actix_web::web::Data;
|
||||
use sqlx::sqlite::SqlitePool;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
database: SqlitePool,
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let pool = SqlitePool::connect("sqlite:database.db").await.expect("Could not connect to db");
|
||||
let app_state = Data::new(AppState { database: pool });
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.service(login)
|
||||
.app_data(app_state.clone())
|
||||
}).bind(("127.0.0.1", 8000))?.run().await
|
||||
}
|
||||
|
||||
46
src/users.rs
Normal file
46
src/users.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use actix_web::web::Data;
|
||||
use actix_web::{post, HttpResponse, Responder};
|
||||
use argon2::password_hash::{SaltString, rand_core::OsRng, PasswordHash, PasswordVerifier, PasswordHasher};
|
||||
use argon2::Argon2;
|
||||
use sqlx::{query, query_as};
|
||||
use crate::AppState;
|
||||
|
||||
struct UserLogin {
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
struct User {
|
||||
id: i64,
|
||||
uuid: String,
|
||||
username: String,
|
||||
hash: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
#[post("/login")]
|
||||
async fn login(user_login: Data<UserLogin>, app_state: Data<AppState>) -> impl Responder {
|
||||
// Verify that the password is correct
|
||||
let argon2 = Argon2::default();
|
||||
let user = query_as!(User, "SELECT * FROM users WHERE username = $1", user_login.username).fetch_one(&app_state.database).await;
|
||||
if user.is_err() {
|
||||
return HttpResponse::BadRequest();
|
||||
}
|
||||
let user = user.unwrap();
|
||||
let hash = PasswordHash::new(&user.hash);
|
||||
if hash.is_err() {
|
||||
return HttpResponse::BadRequest();
|
||||
}
|
||||
if argon2.verify_password(user_login.password.as_bytes(), &hash.unwrap()).is_err() {
|
||||
return HttpResponse::BadRequest();
|
||||
}
|
||||
// Create the JWT
|
||||
|
||||
// Send the JWT as cookie
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[post("/logout")]
|
||||
async fn logout(_token: Data<String>) -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
Reference in New Issue
Block a user