Added Json Web Tokens

Also down migration for users
This commit is contained in:
2026-04-24 17:49:32 +02:00
parent 5e643503aa
commit b94a94a28e
6 changed files with 253 additions and 0 deletions

37
backend/src/cookie/jwt.rs Normal file
View File

@@ -0,0 +1,37 @@
use axum::{Json, http::StatusCode};
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use crate::models::Claims;
#[derive(Debug, Deserialize, Serialize)]
pub struct Error {
pub status: &'static str,
pub message: String,
}
pub fn encode_token(header: &Header, id: String, key: &EncodingKey) -> String {
let now = chrono::Utc::now();
let issued = now.timestamp() as usize;
let expires = (now + chrono::Duration::minutes(90)).timestamp() as usize;
let claims: Claims = Claims {
subject: id,
issued: issued,
expires: expires,
};
let token = encode(header, &claims, key);
return token.expect("token return failed");
}
pub fn decode_token(token: String, key: &DecodingKey) -> Result<Claims, (StatusCode, Json<Error>)> {
let claims = decode::<Claims>(&token, key, &Validation::default())
.map_err(|_| {
let error = Error {
status: "error",
message: "Invalid Token".to_string(),
};
(StatusCode::UNAUTHORIZED, Json(error))
})?
.claims;
return Ok(claims);
}

View File

@@ -0,0 +1 @@
mod jwt;

View File

@@ -1,4 +1,5 @@
#![allow(unused_imports)]
mod cookie;
mod handlers;
mod models;
mod router;