Add Auth
This commit is contained in:
+19
-16
@@ -1,9 +1,9 @@
|
||||
use crate::items;
|
||||
use crate::proto_utils::Proto;
|
||||
use rocket::State;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use uuid::Uuid;
|
||||
use crate::items;
|
||||
use crate::proto_utils::Proto;
|
||||
|
||||
pub struct AuthState {
|
||||
// Map token -> username
|
||||
@@ -21,26 +21,29 @@ impl AuthState {
|
||||
#[post("/login", data = "<request>")]
|
||||
pub fn login(
|
||||
state: &State<AuthState>,
|
||||
user_list: &State<Vec<crate::User>>,
|
||||
request: Proto<items::LoginRequest>,
|
||||
) -> items::LoginResponse {
|
||||
let req = request.into_inner();
|
||||
// Simple mock authentication: allow any non-empty username/password
|
||||
if !req.username.is_empty() && !req.password.is_empty() {
|
||||
|
||||
if let Some(user) = user_list.iter().find(|u| u.name == req.username)
|
||||
&& bcrypt::verify(&req.password, &user.password_hash).unwrap_or(false)
|
||||
{
|
||||
let token = Uuid::new_v4().to_string();
|
||||
let mut tokens = state.tokens.lock().unwrap();
|
||||
tokens.insert(token.clone(), req.username);
|
||||
|
||||
items::LoginResponse {
|
||||
|
||||
return items::LoginResponse {
|
||||
token,
|
||||
success: true,
|
||||
message: "Login successful".to_string(),
|
||||
}
|
||||
} else {
|
||||
items::LoginResponse {
|
||||
token: "".to_string(),
|
||||
success: false,
|
||||
message: "Invalid credentials".to_string(),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
items::LoginResponse {
|
||||
token: "".to_string(),
|
||||
success: false,
|
||||
message: "Invalid credentials".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +54,7 @@ pub fn logout(
|
||||
) -> items::LogoutResponse {
|
||||
let req = request.into_inner();
|
||||
let mut tokens = state.tokens.lock().unwrap();
|
||||
|
||||
|
||||
if tokens.remove(&req.token).is_some() {
|
||||
items::LogoutResponse {
|
||||
success: true,
|
||||
@@ -72,7 +75,7 @@ pub fn get_auth_status(
|
||||
) -> items::AuthStatusResponse {
|
||||
let req = request.into_inner();
|
||||
let tokens = state.tokens.lock().unwrap();
|
||||
|
||||
|
||||
if let Some(username) = tokens.get(&req.token) {
|
||||
items::AuthStatusResponse {
|
||||
authenticated: true,
|
||||
@@ -86,4 +89,4 @@ pub fn get_auth_status(
|
||||
message: "Not authenticated".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user