This repository has been archived on 2021-10-25. You can view files and clone it, but cannot push or open issues/pull-requests.
rusty-bever/src/guards.rs

115 lines
3.1 KiB
Rust
Raw Normal View History

2021-08-21 22:41:38 +02:00
use hmac::{Hmac, NewMac};
use jwt::VerifyWithKey;
use rb::auth::Claims;
2021-08-21 21:42:36 +02:00
use rocket::{
http::Status,
outcome::try_outcome,
2021-08-21 22:41:38 +02:00
request::{FromRequest, Outcome, Request},
2021-08-21 21:42:36 +02:00
};
use sha2::Sha256;
2021-08-21 22:41:38 +02:00
/// Extracts a "Authorization: Bearer" string from the headers.
pub struct Bearer(String);
2021-08-21 21:42:36 +02:00
#[rocket::async_trait]
2021-08-22 16:45:01 +02:00
impl<'r> FromRequest<'r> for Bearer
{
2021-08-21 21:42:36 +02:00
type Error = rb::errors::RBError;
2021-08-22 16:45:01 +02:00
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{
2021-08-21 21:42:36 +02:00
// If the header isn't present, just forward to the next route
let header = match req.headers().get_one("Authorization") {
None => return Outcome::Forward(()),
Some(val) => val,
};
if !header.starts_with("Bearer ") {
return Outcome::Forward(());
}
// Extract the jwt token from the header
2021-08-21 22:41:38 +02:00
let auth_string = match header.get(7..) {
Some(s) => s,
2021-08-21 22:21:42 +02:00
None => return Outcome::Forward(()),
2021-08-21 21:42:36 +02:00
};
2021-08-21 22:41:38 +02:00
Outcome::Success(Self(auth_string.to_string()))
2021-08-21 22:21:42 +02:00
}
}
2021-08-21 22:41:38 +02:00
/// Verifies the provided JWT is valid.
pub struct JWT(Claims);
2021-08-21 22:21:42 +02:00
#[rocket::async_trait]
2021-08-22 16:45:01 +02:00
impl<'r> FromRequest<'r> for JWT
{
2021-08-21 22:21:42 +02:00
type Error = rb::errors::RBError;
2021-08-22 16:45:01 +02:00
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{
2021-08-21 22:41:38 +02:00
let bearer = try_outcome!(req.guard::<Bearer>().await).0;
2021-08-21 22:21:42 +02:00
2021-08-21 21:42:36 +02:00
// Get secret & key
let secret = match std::env::var("JWT_KEY") {
Ok(key) => key,
Err(_) => {
return Outcome::Failure((Status::InternalServerError, Self::Error::MissingJWTKey))
}
};
let key: Hmac<Sha256> = match Hmac::new_from_slice(secret.as_bytes()) {
Ok(key) => key,
Err(_) => {
return Outcome::Failure((Status::InternalServerError, Self::Error::JWTError))
}
};
// Verify token using key
2021-08-21 22:41:38 +02:00
let claims: Claims = match bearer.verify_with_key(&key) {
2021-08-21 21:42:36 +02:00
Ok(claims) => claims,
Err(_) => return Outcome::Failure((Status::Unauthorized, Self::Error::Unauthorized)),
};
2021-08-21 22:41:38 +02:00
Outcome::Success(Self(claims))
}
}
/// Verifies the JWT has not expired.
pub struct User(Claims);
#[rocket::async_trait]
2021-08-22 16:45:01 +02:00
impl<'r> FromRequest<'r> for User
{
2021-08-21 22:41:38 +02:00
type Error = rb::errors::RBError;
2021-08-22 16:45:01 +02:00
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{
2021-08-21 22:41:38 +02:00
let claims = try_outcome!(req.guard::<JWT>().await).0;
2021-08-21 21:42:36 +02:00
// Verify key hasn't yet expired
if chrono::Utc::now().timestamp() > claims.exp {
2021-08-21 22:41:38 +02:00
return Outcome::Failure((Status::Forbidden, Self::Error::TokenExpired));
2021-08-21 21:42:36 +02:00
}
Outcome::Success(Self(claims))
}
}
2021-08-21 22:41:38 +02:00
/// Verifies the JWT belongs to an admin.
2021-08-21 21:42:36 +02:00
pub struct Admin(Claims);
#[rocket::async_trait]
2021-08-22 16:45:01 +02:00
impl<'r> FromRequest<'r> for Admin
{
2021-08-21 21:42:36 +02:00
type Error = rb::errors::RBError;
2021-08-22 16:45:01 +02:00
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{
2021-08-21 21:42:36 +02:00
let user = try_outcome!(req.guard::<User>().await);
if user.0.admin {
Outcome::Success(Self(user.0))
} else {
Outcome::Forward(())
}
}
}