mock auth
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
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
|
||||
tokens: Mutex<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
impl AuthState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tokens: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/login", data = "<request>")]
|
||||
pub fn login(
|
||||
state: &State<AuthState>,
|
||||
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() {
|
||||
let token = Uuid::new_v4().to_string();
|
||||
let mut tokens = state.tokens.lock().unwrap();
|
||||
tokens.insert(token.clone(), req.username);
|
||||
|
||||
items::LoginResponse {
|
||||
token,
|
||||
success: true,
|
||||
message: "Login successful".to_string(),
|
||||
}
|
||||
} else {
|
||||
items::LoginResponse {
|
||||
token: "".to_string(),
|
||||
success: false,
|
||||
message: "Invalid credentials".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/logout", data = "<request>")]
|
||||
pub fn logout(
|
||||
state: &State<AuthState>,
|
||||
request: Proto<items::LogoutRequest>,
|
||||
) -> 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,
|
||||
message: "Logged out successfully".to_string(),
|
||||
}
|
||||
} else {
|
||||
items::LogoutResponse {
|
||||
success: false,
|
||||
message: "Invalid token".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/get_auth_status", data = "<request>")]
|
||||
pub fn get_auth_status(
|
||||
state: &State<AuthState>,
|
||||
request: Proto<items::AuthStatusRequest>,
|
||||
) -> 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,
|
||||
username: username.clone(),
|
||||
message: "Authenticated".to_string(),
|
||||
}
|
||||
} else {
|
||||
items::AuthStatusResponse {
|
||||
authenticated: false,
|
||||
username: "".to_string(),
|
||||
message: "Not authenticated".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user