Switched to binary-only project

develop
Jef Roosens 2021-08-29 20:30:33 +02:00
parent c64eaf2ff5
commit 87d8d8ff0c
Signed by untrusted user: Jef Roosens
GPG Key ID: B580B976584B5F30
12 changed files with 152 additions and 158 deletions

View File

@ -4,10 +4,6 @@ version = "0.1.0"
authors = ["Jef Roosens <roosensjef@gmail.com>"]
edition = "2018"
[lib]
name = "rb"
path = "src/lib.rs"
[[bin]]
name = "rbd"
path = "src/main.rs"

View File

@ -11,7 +11,7 @@ use crate::{
tokens::{NewRefreshToken, RefreshToken},
users::User,
},
errors::RbError,
errors::{RbError, RbResult},
schema::{refresh_tokens::dsl as refresh_tokens, users::dsl as users},
};
@ -32,7 +32,7 @@ pub struct Claims
pub exp: i64,
}
pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> crate::Result<JWTResponse>
pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> RbResult<JWTResponse>
{
let secret = std::env::var("JWT_KEY").map_err(|_| RbError::Custom("Missing JWT key."))?;
let key: Hmac<Sha256> = Hmac::new_from_slice(secret.as_bytes())
@ -76,7 +76,7 @@ pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> crate::Result<JWT
})
}
pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> crate::Result<JWTResponse>
pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> RbResult<JWTResponse>
{
let token_bytes =
base64::decode(refresh_token).map_err(|_| RbError::AuthInvalidRefreshToken)?;

View File

@ -1,63 +1,58 @@
use argon2::verify_encoded;
use diesel::{insert_into, prelude::*, PgConnection};
use rand::{thread_rng, Rng};
use rocket::serde::json::Json;
use serde::Deserialize;
use crate::{
db::users::{NewUser, User},
errors::RbError,
schema::users::dsl as users,
use self::{
jwt::{generate_jwt_token, JWTResponse},
pass::verify_user,
};
use crate::{guards::User, RbDbConn, RbResult};
pub mod jwt;
pub mod pass;
pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> crate::Result<User>
#[derive(Deserialize)]
pub struct Credentials
{
// TODO handle non-"NotFound" Diesel errors accordingely
let user = users::users
.filter(users::username.eq(username))
.first::<User>(conn)
.map_err(|_| RbError::AuthUnknownUser)?;
// Check if a user is blocked
if user.blocked {
return Err(RbError::AuthBlockedUser);
}
match verify_encoded(user.password.as_str(), password.as_bytes()) {
Ok(true) => Ok(user),
_ => Err(RbError::AuthInvalidPassword),
}
username: String,
password: String,
}
pub fn hash_password(password: &str) -> crate::Result<String>
#[post("/login")]
pub async fn already_logged_in(_user: User) -> String
{
// Generate a random salt
let mut salt = [0u8; 64];
thread_rng().fill(&mut salt[..]);
// Encode the actual password
let config = argon2::Config::default();
argon2::hash_encoded(password.as_bytes(), &salt, &config)
.map_err(|_| RbError::Custom("Couldn't hash password."))
String::from("You're already logged in!")
}
pub fn create_admin_user(conn: &PgConnection, username: &str, password: &str)
-> crate::Result<bool>
#[post("/login", data = "<credentials>", rank = 2)]
pub async fn login(conn: RbDbConn, credentials: Json<Credentials>) -> RbResult<Json<JWTResponse>>
{
let pass_hashed = hash_password(password)?;
let new_user = NewUser {
username: username.to_string(),
password: pass_hashed,
admin: true,
};
let credentials = credentials.into_inner();
insert_into(users::users)
.values(&new_user)
.on_conflict(users::username)
.do_update()
.set(&new_user)
.execute(conn)
.map_err(|_| RbError::Custom("Couldn't create admin."))?;
// Get the user, if credentials are valid
let user = conn
.run(move |c| verify_user(c, &credentials.username, &credentials.password))
.await?;
Ok(true)
Ok(Json(conn.run(move |c| generate_jwt_token(c, &user)).await?))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefreshTokenRequest
{
pub refresh_token: String,
}
#[post("/refresh", data = "<refresh_token_request>")]
pub async fn refresh_token(
conn: RbDbConn,
refresh_token_request: Json<RefreshTokenRequest>,
) -> RbResult<Json<JWTResponse>>
{
let refresh_token = refresh_token_request.into_inner().refresh_token;
Ok(Json(
conn.run(move |c| crate::auth::jwt::refresh_token(c, &refresh_token))
.await?,
))
}

61
src/auth/pass.rs 100644
View File

@ -0,0 +1,61 @@
use argon2::verify_encoded;
use diesel::{insert_into, prelude::*, PgConnection};
use rand::{thread_rng, Rng};
use crate::{
db::users::{NewUser, User},
errors::RbError,
schema::users::dsl as users,
RbResult,
};
pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> RbResult<User>
{
// TODO handle non-"NotFound" Diesel errors accordingely
let user = users::users
.filter(users::username.eq(username))
.first::<User>(conn)
.map_err(|_| RbError::AuthUnknownUser)?;
// Check if a user is blocked
if user.blocked {
return Err(RbError::AuthBlockedUser);
}
match verify_encoded(user.password.as_str(), password.as_bytes()) {
Ok(true) => Ok(user),
_ => Err(RbError::AuthInvalidPassword),
}
}
pub fn hash_password(password: &str) -> RbResult<String>
{
// Generate a random salt
let mut salt = [0u8; 64];
thread_rng().fill(&mut salt[..]);
// Encode the actual password
let config = argon2::Config::default();
argon2::hash_encoded(password.as_bytes(), &salt, &config)
.map_err(|_| RbError::Custom("Couldn't hash password."))
}
pub fn create_admin_user(conn: &PgConnection, username: &str, password: &str) -> RbResult<bool>
{
let pass_hashed = hash_password(password)?;
let new_user = NewUser {
username: username.to_string(),
password: pass_hashed,
admin: true,
};
insert_into(users::users)
.values(&new_user)
.on_conflict(users::username)
.do_update()
.set(&new_user)
.execute(conn)
.map_err(|_| RbError::Custom("Couldn't create admin."))?;
Ok(true)
}

View File

@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
errors::RbError,
errors::{RbError, RbResult},
schema::{users, users::dsl::*},
};
@ -28,7 +28,7 @@ pub struct NewUser
pub admin: bool,
}
pub fn all(conn: &PgConnection) -> crate::Result<Vec<User>>
pub fn all(conn: &PgConnection) -> RbResult<Vec<User>>
{
users
.load::<User>(conn)
@ -40,7 +40,7 @@ pub fn find(conn: &PgConnection, user_id: Uuid) -> Option<User>
users.find(user_id).first::<User>(conn).ok()
}
pub fn create(conn: &PgConnection, new_user: &NewUser) -> crate::Result<()>
pub fn create(conn: &PgConnection, new_user: &NewUser) -> RbResult<()>
{
let count = diesel::insert_into(users)
.values(new_user)
@ -54,7 +54,7 @@ pub fn create(conn: &PgConnection, new_user: &NewUser) -> crate::Result<()>
Ok(())
}
pub fn delete(conn: &PgConnection, user_id: Uuid) -> crate::Result<()>
pub fn delete(conn: &PgConnection, user_id: Uuid) -> RbResult<()>
{
diesel::delete(users.filter(id.eq(user_id)))
.execute(conn)

View File

@ -84,4 +84,4 @@ impl<'r> Responder<'r, 'static> for RbError
}
}
pub type Result<T> = std::result::Result<T, RbError>;
pub type RbResult<T> = std::result::Result<T, RbError>;

View File

@ -1,6 +1,5 @@
use hmac::{Hmac, NewMac};
use jwt::VerifyWithKey;
use rb::auth::jwt::Claims;
use rocket::{
http::Status,
outcome::try_outcome,
@ -8,13 +7,15 @@ use rocket::{
};
use sha2::Sha256;
use crate::auth::jwt::Claims;
/// Extracts a "Authorization: Bearer" string from the headers.
pub struct Bearer<'a>(&'a str);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Bearer<'r>
{
type Error = rb::errors::RbError;
type Error = crate::errors::RbError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{
@ -44,7 +45,7 @@ pub struct Jwt(Claims);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Jwt
{
type Error = rb::errors::RbError;
type Error = crate::errors::RbError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{
@ -87,7 +88,7 @@ pub struct User(Claims);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for User
{
type Error = rb::errors::RbError;
type Error = crate::errors::RbError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{
@ -108,7 +109,7 @@ pub struct Admin(Claims);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Admin
{
type Error = rb::errors::RbError;
type Error = crate::errors::RbError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{

View File

@ -1,17 +0,0 @@
#[macro_use]
extern crate diesel;
pub mod auth;
pub mod db;
pub mod errors;
pub(crate) mod schema;
pub use errors::Result;
// Any import defaults are defined here
/// Expire time for the JWT tokens in seconds.
const JWT_EXP_SECONDS: i64 = 600;
/// Amount of bytes the refresh tokens should consist of
const REFRESH_TOKEN_N_BYTES: usize = 64;
/// Expire time for refresh tokens; here: one week
const REFRESH_TOKEN_EXP_SECONDS: i64 = 604800;

View File

@ -1,23 +1,38 @@
// This needs to be explicitely included before diesel is imported to make sure
// compilation succeeds in the release Docker image.
extern crate openssl;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate diesel;
use rocket::{fairing::AdHoc, Build, Rocket};
use rocket_sync_db_pools::{database, diesel};
use rocket_sync_db_pools::database;
pub(crate) mod guards;
pub use crate::errors::{RbError, RbResult};
pub mod auth;
pub mod db;
pub mod errors;
pub mod guards;
mod routes;
pub(crate) mod schema;
embed_migrations!();
// Any import defaults are defined here
/// Expire time for the JWT tokens in seconds.
const JWT_EXP_SECONDS: i64 = 600;
/// Amount of bytes the refresh tokens should consist of
const REFRESH_TOKEN_N_BYTES: usize = 64;
/// Expire time for refresh tokens; here: one week
const REFRESH_TOKEN_EXP_SECONDS: i64 = 604800;
#[database("postgres_rb")]
pub struct RbDbConn(diesel::PgConnection);
embed_migrations!();
async fn run_db_migrations(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>>
{
let conn = RbDbConn::get_one(&rocket)
@ -39,7 +54,7 @@ async fn create_admin_user(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocke
.await
.expect("database connection");
conn.run(move |c| {
rb::auth::create_admin_user(c, &admin_user, &admin_password)
auth::pass::create_admin_user(c, &admin_user, &admin_password)
.expect("failed to create admin user")
})
.await;
@ -57,6 +72,9 @@ fn rocket() -> _
run_db_migrations,
))
.attach(AdHoc::try_on_ignite("Create admin user", create_admin_user))
.mount("/api/auth", routes::auth::routes())
.mount(
"/api/auth",
routes![auth::already_logged_in, auth::login, auth::refresh_token,],
)
.mount("/api/admin", routes::admin::routes())
}

View File

@ -1,8 +1,12 @@
use rb::{db, errors::RbError};
use rocket::serde::json::Json;
use uuid::Uuid;
use crate::{guards::Admin, RbDbConn};
use crate::{
db,
errors::{RbError, RbResult},
guards::Admin,
RbDbConn,
};
pub fn routes() -> Vec<rocket::Route>
{
@ -10,13 +14,13 @@ pub fn routes() -> Vec<rocket::Route>
}
#[get("/users")]
async fn get_users(_admin: Admin, conn: RbDbConn) -> rb::Result<Json<Vec<db::User>>>
async fn get_users(_admin: Admin, conn: RbDbConn) -> RbResult<Json<Vec<db::User>>>
{
Ok(Json(conn.run(|c| db::users::all(c)).await?))
}
#[post("/users", data = "<user>")]
async fn create_user(_admin: Admin, conn: RbDbConn, user: Json<db::NewUser>) -> rb::Result<()>
async fn create_user(_admin: Admin, conn: RbDbConn, user: Json<db::NewUser>) -> RbResult<()>
{
Ok(conn
.run(move |c| db::users::create(c, &user.into_inner()))
@ -24,11 +28,8 @@ async fn create_user(_admin: Admin, conn: RbDbConn, user: Json<db::NewUser>) ->
}
#[get("/users/<user_id_str>")]
async fn get_user_info(
_admin: Admin,
conn: RbDbConn,
user_id_str: &str,
) -> rb::Result<Json<db::User>>
async fn get_user_info(_admin: Admin, conn: RbDbConn, user_id_str: &str)
-> RbResult<Json<db::User>>
{
let user_id = Uuid::parse_str(user_id_str).map_err(|_| RbError::UMUnknownUser)?;

View File

@ -1,60 +0,0 @@
use rb::auth::{
jwt::{generate_jwt_token, JWTResponse},
verify_user,
};
use rocket::serde::json::Json;
use serde::Deserialize;
use crate::{guards::User, RbDbConn};
pub(crate) fn routes() -> Vec<rocket::Route>
{
routes![login, already_logged_in, refresh_token]
}
#[derive(Deserialize)]
struct Credentials
{
username: String,
password: String,
}
#[post("/login")]
async fn already_logged_in(_user: User) -> String
{
String::from("You're already logged in!")
}
#[post("/login", data = "<credentials>", rank = 2)]
async fn login(conn: RbDbConn, credentials: Json<Credentials>) -> rb::Result<Json<JWTResponse>>
{
let credentials = credentials.into_inner();
// Get the user, if credentials are valid
let user = conn
.run(move |c| verify_user(c, &credentials.username, &credentials.password))
.await?;
Ok(Json(conn.run(move |c| generate_jwt_token(c, &user)).await?))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RefreshTokenRequest
{
pub refresh_token: String,
}
#[post("/refresh", data = "<refresh_token_request>")]
async fn refresh_token(
conn: RbDbConn,
refresh_token_request: Json<RefreshTokenRequest>,
) -> rb::Result<Json<JWTResponse>>
{
let refresh_token = refresh_token_request.into_inner().refresh_token;
Ok(Json(
conn.run(move |c| rb::auth::jwt::refresh_token(c, &refresh_token))
.await?,
))
}

View File

@ -1,2 +1 @@
pub mod admin;
pub mod auth;