Added Admin & User guards

This commit is contained in:
Jef Roosens 2021-08-21 21:42:36 +02:00
parent 210eeee7b6
commit 35fb38de9e
Signed by: Jef Roosens
GPG key ID: 955C0660072F691F
6 changed files with 141 additions and 31 deletions

View file

@ -2,11 +2,13 @@ use crate::RbDbConn;
use rb::auth::{generate_jwt_token, verify_user, JWTResponse};
use rocket::serde::json::Json;
use serde::Deserialize;
use crate::guards::User;
pub(crate) fn routes() -> Vec<rocket::Route> {
routes![login]
routes![login, me]
}
#[derive(Deserialize)]
struct Credentials {
username: String,
@ -27,5 +29,10 @@ async fn login(conn: RbDbConn, credentials: Json<Credentials>) -> rb::Result<Jso
Ok(Json(conn.run(move |c| generate_jwt_token(c, &user)).await?))
}
#[get("/me")]
async fn me(claims: User) -> String {
String::from("You are logged in!")
}
// /refresh
// /logout

77
src/rbs/guards.rs Normal file
View file

@ -0,0 +1,77 @@
use rocket::{
http::Status,
outcome::try_outcome,
request::{FromRequest, Outcome, Request}
};
use hmac::{Hmac, NewMac};
use jwt::VerifyWithKey;
use rb::auth::Claims;
use sha2::Sha256;
pub struct User(Claims);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for User {
type Error = rb::errors::RBError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
// 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
let jwt_token = match header.get(7..) {
Some(token) => token,
None => return Outcome::Failure((Status::Unauthorized, Self::Error::JWTError)),
};
// 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
let claims: Claims = match jwt_token.verify_with_key(&key) {
Ok(claims) => claims,
Err(_) => return Outcome::Failure((Status::Unauthorized, Self::Error::Unauthorized)),
};
// Verify key hasn't yet expired
if chrono::Utc::now().timestamp() > claims.exp {
return Outcome::Failure((Status::Unauthorized, Self::Error::Unauthorized));
}
Outcome::Success(Self(claims))
}
}
pub struct Admin(Claims);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Admin {
type Error = rb::errors::RBError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let user = try_outcome!(req.guard::<User>().await);
if user.0.admin {
Outcome::Success(Self(user.0))
} else {
Outcome::Forward(())
}
}
}

View file

@ -11,6 +11,7 @@ use rocket::{fairing::AdHoc, Build, Rocket};
use rocket_sync_db_pools::{database, diesel};
mod auth;
pub(crate) mod guards;
embed_migrations!();
@ -35,7 +36,11 @@ async fn create_admin_user(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocke
let conn = RbDbConn::get_one(&rocket)
.await
.expect("database connection");
conn.run(move |c| rb::auth::create_admin_user(c, &admin_user, &admin_password).expect("failed to create admin user")).await;
conn.run(move |c| {
rb::auth::create_admin_user(c, &admin_user, &admin_password)
.expect("failed to create admin user")
})
.await;
Ok(rocket)
}
@ -48,9 +53,6 @@ fn rocket() -> _ {
"Run database migrations",
run_db_migrations,
))
.attach(AdHoc::try_on_ignite(
"Create admin user",
create_admin_user
))
.attach(AdHoc::try_on_ignite("Create admin user", create_admin_user))
.mount("/api/auth", auth::routes())
}