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

124 lines
3.3 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.
2021-08-23 12:01:04 +02:00
pub struct Bearer<'a>(&'a str);
2021-08-21 21:42:36 +02:00
#[rocket::async_trait]
2021-08-23 12:01:04 +02:00
impl<'r> FromRequest<'r> for Bearer<'r>
2021-08-22 16:45:01 +02:00
{
type Error = rb::errors::RbError;
2021-08-21 21:42:36 +02:00
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-23 12:01:04 +02:00
Outcome::Success(Self(auth_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
{
type Error = rb::errors::RbError;
2021-08-21 22:21:42 +02:00
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::AuthUnauthorized,
))
2021-08-21 21:42:36 +02:00
}
};
let key: Hmac<Sha256> = match Hmac::new_from_slice(secret.as_bytes()) {
Ok(key) => key,
Err(_) => {
return Outcome::Failure((
Status::InternalServerError,
Self::Error::Custom("Failed to do Hmac thing."),
))
2021-08-21 21:42:36 +02:00
}
};
// 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::AuthUnauthorized))
}
2021-08-21 21:42:36 +02:00
};
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
{
type Error = rb::errors::RbError;
2021-08-21 22:41:38 +02:00
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 {
return Outcome::Failure((Status::Forbidden, Self::Error::AuthTokenExpired));
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
{
type Error = rb::errors::RbError;
2021-08-21 21:42:36 +02:00
2021-08-22 16:45:01 +02:00
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{
2021-08-23 12:01:04 +02:00
let user = try_outcome!(req.guard::<User>().await).0;
if user.admin {
Outcome::Success(Self(user))
2021-08-21 21:42:36 +02:00
} else {
Outcome::Forward(())
}
}
}