feat: add a function to check access token

lets me reuse something that will happen often instead of having to write it manually in every file
This commit is contained in:
Radical 2025-05-01 07:06:14 +02:00
parent 3c976d666d
commit 83872ed7a6

View file

@ -1,4 +1,8 @@
use actix_web::{Scope, web}; use std::{str::FromStr, time::{SystemTime, UNIX_EPOCH}};
use actix_web::{web, HttpResponse, Scope};
use sqlx::Postgres;
use uuid::Uuid;
mod register; mod register;
mod login; mod login;
@ -10,3 +14,28 @@ pub fn web() -> Scope {
.service(login::response) .service(login::response)
.service(refresh::res) .service(refresh::res)
} }
pub async fn check_access_token(access_token: String, pool: sqlx::Pool<Postgres>) -> Result<Uuid, HttpResponse> {
match sqlx::query_as("SELECT CAST(uuid as VARCHAR), created FROM access_tokens WHERE token = $1")
.bind(&access_token)
.fetch_one(&pool)
.await {
Ok(row) => {
let (uuid, created): (String, i64) = row;
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
let lifetime = current_time - created;
if lifetime > 3600 {
return Err(HttpResponse::Unauthorized().finish())
}
Ok(Uuid::from_str(&uuid).unwrap())
},
Err(error) => {
eprintln!("{}", error);
Err(HttpResponse::InternalServerError().finish())
}
}
}