diff options
Diffstat (limited to 'src/auth.rs')
-rw-r--r-- | src/auth.rs | 129 |
1 files changed, 89 insertions, 40 deletions
diff --git a/src/auth.rs b/src/auth.rs index e0c8ae9..5fdf079 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -1,19 +1,15 @@ -use actix_web::{web, HttpResponse, Scope}; +use crate::database::user::{User, UserForm}; +use crate::AppState; +use actix_web::{delete, post, web, HttpResponse, Scope}; use chrono::{Duration, Utc}; -use jsonwebtoken::{ - decode, encode, errors::Error as JwtError, Algorithm, DecodingKey, EncodingKey, Header, - TokenData, Validation, -}; +use jsonwebtoken::{encode, EncodingKey, Header}; use serde::{Deserialize, Serialize}; -use crate::AppState; -use crate::extractors::auth_token::AuthenticationToken; - pub fn auth_scope() -> Scope { web::scope("/auth") - .route("/encode-token/{id}", web::get().to(encode_token)) - .route("/decode-token", web::post().to(decode_token)) - .route("/protected", web::get().to(protected)) + .service(register) + .service(login) + .service(delete_user) } #[derive(Serialize, Deserialize)] @@ -44,44 +40,97 @@ struct DecodeBody { token: String, } -async fn encode_token(path: web::Path<usize>, data: web::Data<AppState>) -> HttpResponse { - let id: usize = path.into_inner(); +#[post("/register")] +pub async fn register( + app_state: web::Data<AppState>, + request_data: web::Json<UserForm>, +) -> HttpResponse { + let query = app_state.database.register(request_data.into_inner()).await; + match query { + Ok(_) => HttpResponse::Ok().json(Response { + message: "Registration executed with no errors".to_owned(), + }), + Err(e) => HttpResponse::BadRequest().json(Response { + message: format!("There was an issue in the request: {}", e).to_owned(), + }), + } +} + +#[post("/login")] +pub async fn login( + app_state: web::Data<AppState>, + request_data: web::Json<UserForm>, +) -> HttpResponse { + let query = app_state.database.login(request_data.into_inner()).await; + + let result = match query { + Ok(res) => res, + Err(e) => { + return HttpResponse::BadRequest().json(Response { + message: format!("There was an issue in the request: {}", e).to_owned(), + }) + } + }; + + let user: User = match result { + Some(user) => user, + None => { + return HttpResponse::BadRequest().json(Response { + message: "Username/Password incorrect!".to_owned(), + }) + } + }; + + let id: usize = match user.id { + Some(res) => res as usize, + None => { + return HttpResponse::BadRequest().json(Response { + message: "Internal error: user id not found".to_owned(), + }) + } + }; + + return match encode_token(id, &app_state.secret).await { + Ok(token) => HttpResponse::Ok().json(EncodeResponse { + message: format!("Successfully logged in as {}", user.name.unwrap()).to_owned(), + token: token.to_owned(), + }), + Err(response) => response, + }; +} + +async fn encode_token(id: usize, secret: &String) -> Result<String, HttpResponse> { let exp: usize = (Utc::now() + Duration::days(365)).timestamp() as usize; let claims: Claims = Claims { id, exp }; - let token: String = match encode( + match encode( &Header::default(), &claims, - &EncodingKey::from_secret(data.secret.as_str().as_ref()), + &EncodingKey::from_secret(secret.as_str().as_ref()), ) { - Ok(res) => res, - Err(_) => return HttpResponse::Ok().body("Token encoding didn't work\n"), + Ok(token) => return Ok(token), + Err(_) => return Err(HttpResponse::Ok().body("Token encoding didn't work\n")), }; - - HttpResponse::Ok().json(EncodeResponse { - message: "success".to_owned(), - token: token.to_owned(), - }) } -async fn decode_token(body: web::Json<DecodeBody>, data: web::Data<AppState>) -> HttpResponse { - let decoded: Result<TokenData<Claims>, JwtError> = decode::<Claims>( - &body.token, - &DecodingKey::from_secret(data.secret.as_str().as_ref()), - &Validation::new(Algorithm::HS256), - ); +// todo! tell if the user has been deleted or not +#[delete("/user")] +pub async fn delete_user( + app_state: web::Data<AppState>, + request_data: web::Json<UserForm>, +) -> HttpResponse { + let query = app_state + .database + .delete_user(request_data.into_inner()) + .await; - match decoded { - Ok(token) => HttpResponse::Ok().json(DecodeResponse { - message: "Authorized".to_string(), - id: token.claims.id, - }), - Err(e) => HttpResponse::BadRequest().json(Response { - message: e.to_string(), + match query { + Ok(_) => HttpResponse::Ok().json(Response { + message: "Deletion executed with no errors".to_owned(), }), + Err(e) => { + return HttpResponse::BadRequest().json(Response { + message: format!("There was an issue in the request: {}", e).to_owned(), + }) + } } } - -async fn protected(auth_token: AuthenticationToken) -> HttpResponse { - println!("{:#?}", auth_token); - HttpResponse::Ok().json(Response { message: "Authorized".to_owned() }) -} |