ffplayout/src/api/routes.rs

66 lines
2.1 KiB
Rust
Raw Normal View History

2022-06-08 18:16:58 +02:00
use actix_web::{get, http::StatusCode, post, web, Responder};
2022-06-07 22:05:35 +02:00
use argon2::{password_hash::PasswordHash, Argon2, PasswordVerifier};
2022-06-08 18:06:40 +02:00
use serde::Serialize;
2022-06-07 22:05:35 +02:00
use simplelog::*;
2022-06-06 23:07:11 +02:00
2022-06-08 18:06:40 +02:00
use crate::api::{handles::get_login, models::User};
2022-06-06 23:07:11 +02:00
#[get("/hello/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {
format!("Hello {name}!")
}
2022-06-08 18:06:40 +02:00
#[derive(Serialize)]
struct ResponseObj<T> {
message: String,
status: i32,
data: Option<T>,
2022-06-07 18:11:46 +02:00
}
2022-06-08 18:06:40 +02:00
2022-06-07 22:05:35 +02:00
/// curl -X POST -H "Content-Type: application/json" -d '{"username": "USER", "password": "abc123" }' http://127.0.0.1:8080/auth/login/
2022-06-07 18:11:46 +02:00
#[post("/auth/login/")]
pub async fn login(credentials: web::Json<User>) -> impl Responder {
2022-06-08 18:06:40 +02:00
match get_login(&credentials.username).await {
Ok(mut user) => {
let pass = user.password.clone();
user.password = "".into();
user.salt = None;
2022-06-07 22:05:35 +02:00
2022-06-08 18:06:40 +02:00
let hash = PasswordHash::new(&pass).unwrap();
2022-06-07 22:05:35 +02:00
if Argon2::default()
.verify_password(credentials.password.as_bytes(), &hash)
.is_ok()
{
info!("user {} login", credentials.username);
2022-06-07 18:11:46 +02:00
2022-06-08 18:06:40 +02:00
web::Json(ResponseObj {
message: "login correct!".into(),
status: 200,
data: Some(user),
})
2022-06-08 18:16:58 +02:00
.customize()
.with_status(StatusCode::OK)
2022-06-08 18:06:40 +02:00
} else {
error!("Wrong password for {}!", credentials.username);
web::Json(ResponseObj {
message: "Wrong password!".into(),
status: 401,
data: None,
})
2022-06-08 18:16:58 +02:00
.customize()
.with_status(StatusCode::FORBIDDEN)
2022-06-08 18:06:40 +02:00
}
}
Err(e) => {
error!("Login {} failed! {e}", credentials.username);
return web::Json(ResponseObj {
message: format!("Login {} failed!", credentials.username),
2022-06-08 18:16:58 +02:00
status: 400,
2022-06-08 18:06:40 +02:00
data: None,
2022-06-08 18:16:58 +02:00
})
.customize()
.with_status(StatusCode::BAD_REQUEST);
2022-06-08 18:06:40 +02:00
}
}
2022-06-07 18:11:46 +02:00
}