🔒 Adds authentication

This commit is contained in:
Daniel Svitan
2025-05-11 09:29:47 +02:00
parent d5bb5089da
commit 1413ed58b9
6 changed files with 98 additions and 3 deletions

56
backend/src/auth.rs Normal file
View File

@@ -0,0 +1,56 @@
use rocket::Response;
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome, Request};
use serde::Serialize;
use serde_json::json;
use std::io::Cursor;
pub struct ApiKey {}
#[derive(Serialize)]
pub struct GenericResponse {
pub message: String,
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for ApiKey {
type Error = Response<'r>;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Response<'r>> {
fn is_valid(key: &str) -> bool {
key == dotenv::var("API_KEY").unwrap()
}
match req.headers().get_one("Authorization") {
None => {
let body = json!(GenericResponse {
message: "auth token not found".to_string()
})
.to_string();
Outcome::Error((
Status::Unauthorized,
Response::build()
.status(Status::Unauthorized)
.sized_body(body.len(), Cursor::new(body))
.finalize(),
))
}
Some(key) if is_valid(key) => Outcome::Success(ApiKey {}),
Some(_) => {
let body = json!(GenericResponse {
message: "invalid auth token".to_string()
})
.to_string();
Outcome::Error((
Status::Unauthorized,
Response::build()
.status(Status::Unauthorized)
.sized_body(body.len(), Cursor::new(body))
.finalize(),
))
}
}
}
}

View File

@@ -1,6 +1,8 @@
mod db;
mod auth;
use dotenv;
use auth::ApiKey;
#[macro_use]
extern crate rocket;
@@ -10,11 +12,17 @@ async fn index() -> &'static str {
"Hello World!"
}
#[get("/hi")]
async fn hello(api_key: ApiKey) -> &'static str {
"Hi!"
}
#[launch]
fn rocket() -> _ {
dotenv::dotenv().ok();
let db_path = dotenv::var("DB_PATH").expect("DB_PATH is not set");
dotenv::var("API_KEY").expect("API_KEY is not set");
let db = db::Conn::new(&db_path);
rocket::build().mount("/", routes![index])
rocket::build().mount("/", routes![index, hello])
}