+ FromRequest on ApiKey

With this we should get some easy coupling with the web server
This commit is contained in:
shockrah 2021-09-27 14:46:46 -07:00
parent 0e895abc94
commit a50cce38e9
4 changed files with 63 additions and 7 deletions

View File

@ -8,3 +8,4 @@ edition = "2018"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0" }
rocket = "0.4"

View File

@ -6,6 +6,9 @@ use std::io::prelude::*;
use serde::{Serialize, Deserialize};
pub mod request;
use request::ApiKey;
fn dev_urandom() -> std::io::Result<String> {
let mut file = File::open("/dev/urandom")?;
let mut buf: [u8;48] = [0;48];
@ -21,13 +24,6 @@ fn dev_urandom() -> std::io::Result<String> {
}
#[derive(Clone, Serialize, Deserialize)]
pub struct ApiKey {
// Owner of the key
name: String,
// The secret value of the key itself
key: String,
}
#[derive(Serialize, Deserialize)]
pub struct DB {
keys: Vec<ApiKey>

56
dblib/src/request.rs Normal file
View File

@ -0,0 +1,56 @@
use std::env;
use crate::DB;
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<ApiKey, ApiKeyError> {
let storage_target = match env::var("CLIP_KEY_STORE") {
Ok(val) => val,
Err(_) => "store.json".to_string()
};
// yolo unwrap because i cba to deal w/ edge cases and shit
match DB::get_entry(storage_target, 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<Self, Self::Error> {
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))
}
}
}

View File

@ -0,0 +1,3 @@
Signature: 8a477f597d28d172789f06886806bc55
# This file is a cache directory tag created by cargo.
# For information about cache directory tags see https://bford.info/cachedir/