37 lines
1.3 KiB
Rust
37 lines
1.3 KiB
Rust
use actix_web::{dev::Payload, http::header::AUTHORIZATION, web, Error, FromRequest, HttpRequest};
|
|
use futures::future::{ready, Ready};
|
|
use rusqlite::Connection;
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
pub struct Auth {
|
|
pub user_id: String,
|
|
}
|
|
|
|
impl FromRequest for Auth {
|
|
type Error = Error;
|
|
type Future = Ready<Result<Self, Self::Error>>;
|
|
|
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
|
let db = req
|
|
.app_data::<web::Data<Arc<Mutex<Connection>>>>()
|
|
.expect("Database connection missing");
|
|
|
|
if let Some(auth_header) = req.headers().get(AUTHORIZATION) {
|
|
if let Ok(auth_str) = auth_header.to_str() {
|
|
if auth_str.starts_with("Bearer ") {
|
|
let token = &auth_str[7..];
|
|
let conn = db.lock().unwrap();
|
|
|
|
match super::db::validate_token(&conn, token) {
|
|
Ok(Some(user_id)) => return ready(Ok(Auth { user_id })),
|
|
Ok(None) | Err(_) => {
|
|
return ready(Err(actix_web::error::ErrorUnauthorized("Invalid token")))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
ready(Err(actix_web::error::ErrorUnauthorized("Missing token")))
|
|
}
|
|
}
|