|
| 1 | +use crate::models::user::User; |
| 2 | +use diesel::prelude::*; |
| 3 | +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; |
| 4 | +use rocket::http::Status; |
| 5 | +use rocket::request::{FromRequest, Outcome}; |
| 6 | +use rocket::Request; |
| 7 | +use serde::{Deserialize, Serialize}; |
| 8 | + |
| 9 | +pub struct AuthenticatedUser(pub User); |
| 10 | + |
| 11 | +#[derive(Debug, Serialize, Deserialize)] |
| 12 | +pub(crate) struct Claims { |
| 13 | + pub(crate) sub: i32, |
| 14 | + pub(crate) role: String, |
| 15 | + pub(crate) exp: usize, |
| 16 | +} |
| 17 | + |
| 18 | +#[rocket::async_trait] |
| 19 | +impl<'r> FromRequest<'r> for AuthenticatedUser { |
| 20 | + type Error = (); |
| 21 | + |
| 22 | + async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> { |
| 23 | + let token = request.headers().get_one("Authorization"); |
| 24 | + |
| 25 | + match token { |
| 26 | + Some(token) if token.starts_with("Bearer ") => { |
| 27 | + let token = &token[7..]; |
| 28 | + let decoding_key = DecodingKey::from_secret("your_secret_key".as_ref()); |
| 29 | + match decode::<Claims>(token, &decoding_key, &Validation::new(Algorithm::HS256)) { |
| 30 | + Ok(token_data) => { |
| 31 | + let mut conn = crate::db::establish_connection(); |
| 32 | + match crate::schema::users::dsl::users |
| 33 | + .find(token_data.claims.sub) |
| 34 | + .first::<User>(&mut conn) |
| 35 | + { |
| 36 | + Ok(user) => Outcome::Success(AuthenticatedUser(user)), |
| 37 | + Err(_) => Outcome::Error((Status::Unauthorized, ())), |
| 38 | + } |
| 39 | + } |
| 40 | + Err(_) => Outcome::Error((Status::Unauthorized, ())), |
| 41 | + } |
| 42 | + } |
| 43 | + _ => Outcome::Error((Status::Unauthorized, ())), |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments