diff options
author | niliara-edu <nil.jimeno@estudiant.fjaverianas.com> | 2025-01-23 23:28:01 +0100 |
---|---|---|
committer | niliara-edu <nil.jimeno@estudiant.fjaverianas.com> | 2025-01-23 23:28:01 +0100 |
commit | 8c4de2ddac066a072f376e9f30409b114aa9978c (patch) | |
tree | c1dc334904206f1b796d753293cb0b5c838f35d8 | |
parent | 6a7a49fb3804d0d27bbaee08b6feb26b4973b4bc (diff) |
-rw-r--r-- | .ignore | 2 | ||||
-rw-r--r-- | src/auth.rs | 68 | ||||
-rw-r--r-- | src/extractors/auth_token.rs | 43 | ||||
-rw-r--r-- | src/extractors/mod.rs | 1 | ||||
-rw-r--r-- | src/main.rs | 2 | ||||
-rw-r--r-- | src/structs.rs | 35 |
6 files changed, 97 insertions, 54 deletions
@@ -1,2 +1,2 @@ scripts/populate/ -asdscripts/ +scripts/ diff --git a/src/auth.rs b/src/auth.rs index 8bf29f7..e0c8ae9 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -1,9 +1,13 @@ -use actix_web::{web, Scope, HttpResponse}; -use serde::{Serialize, Deserialize}; -use chrono::{Utc, Duration}; -use jsonwebtoken::{encode, EncodingKey, Header}; - +use actix_web::{web, HttpResponse, Scope}; +use chrono::{Duration, Utc}; +use jsonwebtoken::{ + decode, encode, errors::Error as JwtError, Algorithm, DecodingKey, EncodingKey, Header, + TokenData, Validation, +}; +use serde::{Deserialize, Serialize}; use crate::AppState; +use crate::extractors::auth_token::AuthenticationToken; + pub fn auth_scope() -> Scope { web::scope("/auth") @@ -13,41 +17,71 @@ pub fn auth_scope() -> Scope { } #[derive(Serialize, Deserialize)] -struct Claims{ - id: usize, - exp: usize, +pub struct Claims { + pub id: usize, + pub exp: usize, +} + +#[derive(Serialize, Deserialize)] +struct Response { + message: String, } #[derive(Serialize, Deserialize)] -struct Response{ +struct EncodeResponse { message: String, + token: String, } #[derive(Serialize, Deserialize)] -struct EncodeResponse{ +struct DecodeResponse { message: String, + id: usize, +} + +#[derive(Serialize, Deserialize)] +struct DecodeBody { token: String, } async fn encode_token(path: web::Path<usize>, data: web::Data<AppState>) -> HttpResponse { let id: usize = path.into_inner(); let exp: usize = (Utc::now() + Duration::days(365)).timestamp() as usize; - let claims: Claims = Claims {id, exp}; - let token: String = encode( + let claims: Claims = Claims { id, exp }; + let token: String = match encode( &Header::default(), &claims, &EncodingKey::from_secret(data.secret.as_str().as_ref()), - ).unwrap(); + ) { + Ok(res) => res, + Err(_) => return 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() -> HttpResponse { - HttpResponse::Ok().body("decode_token\n".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), + ); + + 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(), + }), + } } -async fn protected() -> HttpResponse { - HttpResponse::Ok().body("protected\n".to_owned()) +async fn protected(auth_token: AuthenticationToken) -> HttpResponse { + println!("{:#?}", auth_token); + HttpResponse::Ok().json(Response { message: "Authorized".to_owned() }) } diff --git a/src/extractors/auth_token.rs b/src/extractors/auth_token.rs new file mode 100644 index 0000000..c505fdf --- /dev/null +++ b/src/extractors/auth_token.rs @@ -0,0 +1,43 @@ +use std::future::{ Ready, ready }; +use actix_web::{web, FromRequest, Error as ActixWebError, HttpRequest, dev::Payload, http, http::header::HeaderValue, error::ErrorUnauthorized}; +use serde::{Serialize, Deserialize}; +use jsonwebtoken:: {decode, DecodingKey, errors::Error as JwtError, Algorithm, Validation, TokenData}; +use crate::auth::Claims; +use crate::AppState; + +#[derive(Serialize, Deserialize, Debug)] +pub struct AuthenticationToken { + pub id: usize, +} + +impl FromRequest for AuthenticationToken { + type Error = ActixWebError; + type Future = Ready<Result<Self, Self::Error>>; + + fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { + // get auth token from the authorization header + let auth_header: Option<&HeaderValue> = req.headers().get(http::header::AUTHORIZATION); + let auth_token: String = auth_header.unwrap().to_str().unwrap_or("").to_string(); // check errors later + // stop empty and weird (ascii, chinese...) auth_token strings: + if auth_token.is_empty() { return ready(Err(ErrorUnauthorized("Invalid auth token!")))} + let secret: String = req.app_data::<web::Data<AppState>>().unwrap().secret.to_string(); + + // decode token with secret + let decode: Result<TokenData<Claims>, JwtError> = decode::<Claims>( + &auth_token, + &DecodingKey::from_secret(secret.as_str().as_ref()), + &Validation::new(Algorithm::HS256), + ); + + println!("{}", auth_token); + // return authenticationtoken + match decode { + Ok(token) => ready(Ok(AuthenticationToken { id: token.claims.id })), + Err(_) => ready(Err(ErrorUnauthorized("Unauthorized!"))), + } + } +} + +/* Example execution in curl: +curl localhost:8000/auth/protected -H "Accept: application/json" -H "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNzY5MjAyNjU1fQ.QbWkgjmbmMwLJnia6vd67EfRkf6y-4nw572g-Nk0BOE" +*/ diff --git a/src/extractors/mod.rs b/src/extractors/mod.rs new file mode 100644 index 0000000..403a6a8 --- /dev/null +++ b/src/extractors/mod.rs @@ -0,0 +1 @@ +pub mod auth_token; diff --git a/src/main.rs b/src/main.rs index 8a64e0d..9c96c4b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ mod api; mod auth; mod database; -mod structs; +mod extractors; use actix_web::{web, App, HttpServer}; use dotenv::dotenv; diff --git a/src/structs.rs b/src/structs.rs deleted file mode 100644 index 7535bb4..0000000 --- a/src/structs.rs +++ /dev/null @@ -1,35 +0,0 @@ -#[allow(dead_code)] -struct Song { - //song variables - id: i32, - title: String, - lyrics: String, - - //album variables - album_id: i32, - genres: Vec<String>, - album_cover: String, - - //artist variables - artist_id: i32, - artist_name: String, -} - -#[allow(dead_code)] -struct Album { - id: i32, - title: String, - genres: Vec<String>, - cover: String, - songs: Vec<i32>, -} - -#[allow(dead_code)] -struct Artist { - id: i32, - name: String, - genres: Vec<String>, - albums: Vec<i32>, -} - -// lepht anonym |