From 6a7a49fb3804d0d27bbaee08b6feb26b4973b4bc Mon Sep 17 00:00:00 2001 From: niliara-edu Date: Wed, 22 Jan 2025 14:10:08 +0100 Subject: prepare for api --- src/auth.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/auth.rs (limited to 'src/auth.rs') diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..8bf29f7 --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,53 @@ +use actix_web::{web, Scope, HttpResponse}; +use serde::{Serialize, Deserialize}; +use chrono::{Utc, Duration}; +use jsonwebtoken::{encode, EncodingKey, Header}; + +use crate::AppState; + +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)) +} + +#[derive(Serialize, Deserialize)] +struct Claims{ + id: usize, + exp: usize, +} + +#[derive(Serialize, Deserialize)] +struct Response{ + message: String, +} + +#[derive(Serialize, Deserialize)] +struct EncodeResponse{ + message: String, + token: String, +} + +async fn encode_token(path: web::Path, data: web::Data) -> 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( + &Header::default(), + &claims, + &EncodingKey::from_secret(data.secret.as_str().as_ref()), + ).unwrap(); + 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 protected() -> HttpResponse { + HttpResponse::Ok().body("protected\n".to_owned()) +} -- cgit v1.2.3