Implement extractor for checking authorization

This commit is contained in:
Reimar 2024-08-14 16:33:38 +02:00
parent c32477b307
commit 687d366f3d
Signed by: Reimar
GPG Key ID: 93549FA07F0AE268
4 changed files with 54 additions and 0 deletions

View File

@ -1101,6 +1101,7 @@ checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"
name = "skantravels"
version = "0.1.0"
dependencies = [
"actix-utils",
"actix-web",
"refinery",
"rusqlite",

View File

@ -5,6 +5,7 @@ edition = "2021"
[dependencies]
actix-web = "4"
actix-utils = "3.0.1"
refinery = { version = "0.8.14", features = ["rusqlite"] }
rusqlite = { version = "0.31", features = ["bundled"] }

41
rust-backend/src/auth.rs Normal file
View File

@ -0,0 +1,41 @@
use actix_web::{Error, FromRequest, HttpRequest};
use actix_web::dev::Payload;
use actix_web::error::ErrorUnauthorized;
use std::string::String;
use actix_utils::future::{Ready, ok, err};
pub struct AuthorizedUser {
user_id: String,
}
impl FromRequest for AuthorizedUser {
type Error = Error;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
if is_authorized(req) {
ok(Self {
user_id: "hi".to_string(),
})
} else {
err(ErrorUnauthorized("Unauthorized"))
}
}
}
fn is_authorized(req: &HttpRequest) -> bool {
let token = req.headers()
.get("Authorization")
.and_then(|value| value.to_str().ok())
.take_if(|value| value.starts_with("Bearer "))
.and_then(|value| Some(value.replace("Bearer ", "")));
if token.is_none() {
return false;
}
// TODO implement
true
}

View File

@ -1,5 +1,9 @@
mod auth;
use actix_web::{get, Responder, HttpResponse, HttpServer, App, web};
use actix_web::middleware;
use std::sync::{Mutex, Arc};
use crate::auth::AuthorizedUser;
mod embedded {
use refinery::embed_migrations;
@ -21,6 +25,11 @@ async fn healthcheck(data: web::Data<AppData>) -> impl Responder {
}
#[get("/authorized")]
async fn authorized(_: AuthorizedUser) -> impl Responder {
HttpResponse::Ok().body("Authorized")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let port = std::env::var("RUST_BACKEND_PORT")
@ -50,8 +59,10 @@ async fn main() -> std::io::Result<()> {
database: conn,
}))
.service(healthcheck)
.service(authorized)
})
.bind(("0.0.0.0", port))?
.run()
.await
}