use crate::{DB, KeyStore}; use rocket::request::{self, Request, FromRequest}; use rocket::http::Status; use rocket::Outcome; use serde::{Serialize, Deserialize}; #[derive(Clone, Serialize, Deserialize)] pub struct ApiKey { // Owner of the key pub name: String, // The secret value of the key itself pub key: String, } #[derive(Debug)] pub enum ApiKeyError { BadCount, Missing, Invalid } fn verify_api_key(key: &str, name: &str) -> request::Outcome { // yolo unwrap because i cba to deal w/ edge cases and shit match DB::get_entry(name.to_string()).unwrap() { Some(db_key) => { if db_key == key { Outcome::Success( ApiKey { name: name.to_string(), key: key.to_string()} ) } else{ Outcome::Failure((Status::Unauthorized, ApiKeyError::Invalid)) } }, None => Outcome::Failure((Status::Unauthorized, ApiKeyError::Invalid)) } } impl<'a, 'r> FromRequest<'a, 'r> for ApiKey { type Error = ApiKeyError; fn from_request(request: &'a Request<'r>) -> request::Outcome { let key = request.headers().get_one("x-api-key"); let name = request.headers().get_one("x-api-name"); match (key, name) { (Some(key), Some(name)) => verify_api_key(key, name), _ => Outcome::Failure((Status::BadRequest, ApiKeyError::Missing)) } } }