rusty-bever/src/guards.rs

120 lines
3.4 KiB
Rust
Raw Permalink Normal View History

2021-08-21 22:41:38 +02:00
use hmac::{Hmac, NewMac};
use jwt::VerifyWithKey;
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},
State,
2021-08-21 21:42:36 +02:00
};
use sha2::Sha256;
use crate::{auth::jwt::Claims, errors::RbError, RbConfig};
2021-08-29 20:30:33 +02:00
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
{
2021-08-29 20:30:33 +02:00
type Error = crate::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") {
2021-09-01 17:29:39 +02:00
None => return Outcome::Failure((Status::BadRequest, Self::Error::AuthMissingHeader)),
2021-08-21 21:42:36 +02:00
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-09-01 17:29:39 +02:00
None => return Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized)),
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.
2021-08-29 19:07:36 +02:00
pub struct Jwt(Claims);
2021-08-21 22:21:42 +02:00
#[rocket::async_trait]
2021-08-29 19:07:36 +02:00
impl<'r> FromRequest<'r> for Jwt
2021-08-22 16:45:01 +02:00
{
type Error = 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;
let config = try_outcome!(req.guard::<&State<RbConfig>>().await.map_failure(|_| (
Status::InternalServerError,
RbError::Custom("Couldn't get config guard.")
)));
2021-08-21 22:21:42 +02:00
let key: Hmac<Sha256> = match Hmac::new_from_slice(&config.jwt.key.as_bytes()) {
2021-08-21 21:42:36 +02:00
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
{
2021-08-29 20:30:33 +02:00
type Error = crate::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-29 19:07:36 +02:00
let claims = try_outcome!(req.guard::<Jwt>().await).0;
2021-08-21 22:41:38 +02:00
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
{
2021-08-29 20:30:33 +02:00
type Error = crate::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 {
2021-09-01 17:29:39 +02:00
Outcome::Failure((Status::Unauthorized, RbError::AuthUnauthorized))
2021-08-21 21:42:36 +02:00
}
}
}