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()) }