Moved over initial code
This commit is contained in:
parent
01a605371e
commit
64e18e17d2
17 changed files with 750 additions and 0 deletions
102
src/auth/jwt.rs
Normal file
102
src/auth/jwt.rs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
use chrono::Utc;
|
||||
use diesel::PgConnection;
|
||||
use hmac::{Hmac, NewMac};
|
||||
use jwt::SignWithKey;
|
||||
use rand::{thread_rng, Rng};
|
||||
use rb::auth::{Claims, JwtConf, JwtResponse};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::{
|
||||
db,
|
||||
errors::{RbError, RbResult},
|
||||
RbJwtConf,
|
||||
};
|
||||
|
||||
pub fn generate_jwt_token(
|
||||
conn: &PgConnection,
|
||||
jwt: &RbJwtConf,
|
||||
user: &db::User,
|
||||
) -> RbResult<JWTResponse>
|
||||
{
|
||||
let key: Hmac<Sha256> = Hmac::new_from_slice(jwt.key.as_bytes())
|
||||
.map_err(|_| RbError::Custom("Couldn't create Hmac key."))?;
|
||||
|
||||
let current_time = Utc::now();
|
||||
|
||||
// Create the claims
|
||||
let claims = Claims {
|
||||
id: user.id,
|
||||
username: user.username.clone(),
|
||||
admin: user.admin,
|
||||
exp: current_time.timestamp() + jwt.refresh_token_expire,
|
||||
};
|
||||
|
||||
// Sign the claims into a new token
|
||||
let token = claims
|
||||
.sign_with_key(&key)
|
||||
.map_err(|_| RbError::Custom("Couldn't sign JWT."))?;
|
||||
|
||||
// Generate a random refresh token
|
||||
let mut refresh_token = vec![0u8; jwt.refresh_token_size];
|
||||
thread_rng().fill(&mut refresh_token[..]);
|
||||
|
||||
let refresh_expire =
|
||||
(current_time + chrono::Duration::seconds(jwt.refresh_token_expire)).naive_utc();
|
||||
|
||||
// Store refresh token in database
|
||||
db::tokens::create(
|
||||
conn,
|
||||
&db::NewRefreshToken {
|
||||
token: refresh_token.to_vec(),
|
||||
user_id: user.id,
|
||||
expires_at: refresh_expire,
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(JWTResponse {
|
||||
token,
|
||||
refresh_token: base64::encode(refresh_token),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn refresh_token(
|
||||
conn: &PgConnection,
|
||||
jwt: &RbJwtConf,
|
||||
refresh_token: &str,
|
||||
) -> RbResult<JWTResponse>
|
||||
{
|
||||
let token_bytes =
|
||||
base64::decode(refresh_token).map_err(|_| RbError::AuthInvalidRefreshToken)?;
|
||||
|
||||
// First, we request the token from the database to see if it's really a valid token
|
||||
let (token_entry, user) =
|
||||
db::tokens::find_with_user(conn, &token_bytes).ok_or(RbError::AuthInvalidRefreshToken)?;
|
||||
|
||||
// If we see that the token has already been used before, we block the user.
|
||||
if token_entry.last_used_at.is_some() {
|
||||
// If we fail to block the user, the end user must know
|
||||
if let Err(err) = db::users::block(conn, token_entry.user_id) {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
return Err(RbError::AuthDuplicateRefreshToken);
|
||||
}
|
||||
|
||||
// Then we check if the user is blocked
|
||||
if user.blocked {
|
||||
return Err(RbError::AuthBlockedUser);
|
||||
}
|
||||
|
||||
// Now we check if the token has already expired
|
||||
let cur_time = Utc::now().naive_utc();
|
||||
|
||||
if token_entry.expires_at < cur_time {
|
||||
return Err(RbError::AuthTokenExpired);
|
||||
}
|
||||
|
||||
// We update the last_used_at value for the refresh token
|
||||
db::tokens::update_last_used_at(conn, &token_entry.token, cur_time)?;
|
||||
|
||||
generate_jwt_token(conn, jwt, &user)
|
||||
}
|
||||
68
src/auth/mod.rs
Normal file
68
src/auth/mod.rs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
use rocket::{serde::json::Json, State};
|
||||
use serde::Deserialize;
|
||||
|
||||
use self::{
|
||||
jwt::{generate_jwt_token, JWTResponse},
|
||||
pass::verify_user,
|
||||
};
|
||||
use crate::{errors::RbResult, guards::User, RbConfig, RbDbConn};
|
||||
|
||||
pub mod jwt;
|
||||
pub mod pass;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Credentials
|
||||
{
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[post("/login")]
|
||||
pub async fn already_logged_in(_user: User) -> String
|
||||
{
|
||||
String::from("You're already logged in!")
|
||||
}
|
||||
|
||||
#[post("/login", data = "<credentials>", rank = 2)]
|
||||
pub async fn login(
|
||||
conn: RbDbConn,
|
||||
conf: &State<RbConfig>,
|
||||
credentials: Json<Credentials>,
|
||||
) -> RbResult<Json<JWTResponse>>
|
||||
{
|
||||
let credentials = credentials.into_inner();
|
||||
let jwt = conf.jwt.clone();
|
||||
|
||||
// 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, &jwt, &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,
|
||||
conf: &State<RbConfig>,
|
||||
refresh_token_request: Json<RefreshTokenRequest>,
|
||||
) -> RbResult<Json<JWTResponse>>
|
||||
{
|
||||
let refresh_token = refresh_token_request.into_inner().refresh_token;
|
||||
let jwt = conf.jwt.clone();
|
||||
|
||||
Ok(Json(
|
||||
conn.run(move |c| crate::auth::jwt::refresh_token(c, &jwt, &refresh_token))
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
36
src/auth/pass.rs
Normal file
36
src/auth/pass.rs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
use argon2::verify_encoded;
|
||||
use diesel::PgConnection;
|
||||
use rand::{thread_rng, Rng};
|
||||
|
||||
use crate::{
|
||||
db,
|
||||
errors::{RbError, RbResult},
|
||||
};
|
||||
|
||||
pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> RbResult<db::User>
|
||||
{
|
||||
// TODO handle non-"NotFound" Diesel errors accordingely
|
||||
let user = db::users::find_by_username(conn, username).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."))
|
||||
}
|
||||
2
src/db/mod.rs
Normal file
2
src/db/mod.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
mod tokens;
|
||||
mod users;
|
||||
122
src/db/tokens.rs
Normal file
122
src/db/tokens.rs
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
//! Handles refresh token-related database operations.
|
||||
|
||||
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
errors::{RbError, RbResult},
|
||||
schema::{refresh_tokens, refresh_tokens::dsl::*},
|
||||
};
|
||||
|
||||
/// A refresh token as stored in the database
|
||||
#[derive(Queryable, Serialize)]
|
||||
pub struct RefreshToken
|
||||
{
|
||||
pub token: Vec<u8>,
|
||||
pub user_id: Uuid,
|
||||
pub expires_at: chrono::NaiveDateTime,
|
||||
pub last_used_at: Option<chrono::NaiveDateTime>,
|
||||
}
|
||||
|
||||
/// A new refresh token to be added into the database
|
||||
#[derive(Deserialize, Insertable)]
|
||||
#[table_name = "refresh_tokens"]
|
||||
pub struct NewRefreshToken
|
||||
{
|
||||
pub token: Vec<u8>,
|
||||
pub user_id: Uuid,
|
||||
pub expires_at: chrono::NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, AsChangeset)]
|
||||
#[table_name = "refresh_tokens"]
|
||||
pub struct PatchRefreshToken
|
||||
{
|
||||
pub expires_at: Option<chrono::NaiveDateTime>,
|
||||
pub last_used_at: Option<chrono::NaiveDateTime>,
|
||||
}
|
||||
|
||||
pub fn get(conn: &PgConnection, offset_: u32, limit_: u32) -> RbResult<Vec<RefreshToken>>
|
||||
{
|
||||
Ok(refresh_tokens
|
||||
.offset(offset_.into())
|
||||
.limit(limit_.into())
|
||||
.load(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't query tokens."))?)
|
||||
}
|
||||
|
||||
pub fn create(conn: &PgConnection, new_token: &NewRefreshToken) -> RbResult<RefreshToken>
|
||||
{
|
||||
Ok(insert_into(refresh_tokens)
|
||||
.values(new_token)
|
||||
.get_result(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't insert refresh token."))?)
|
||||
|
||||
// TODO check for conflict?
|
||||
}
|
||||
|
||||
pub fn update(
|
||||
conn: &PgConnection,
|
||||
token_: &[u8],
|
||||
patch_token: &PatchRefreshToken,
|
||||
) -> RbResult<RefreshToken>
|
||||
{
|
||||
Ok(diesel::update(refresh_tokens.filter(token.eq(token_)))
|
||||
.set(patch_token)
|
||||
.get_result(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't update token."))?)
|
||||
}
|
||||
|
||||
pub fn delete(conn: &PgConnection, token_: &[u8]) -> RbResult<()>
|
||||
{
|
||||
diesel::delete(refresh_tokens.filter(token.eq(token_)))
|
||||
.execute(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't delete token."))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the token & user data associated with the given refresh token value.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `conn` - database connection to use
|
||||
/// * `token_val` - token value to search for
|
||||
pub fn find_with_user(
|
||||
conn: &PgConnection,
|
||||
token_: &[u8],
|
||||
) -> Option<(RefreshToken, super::users::User)>
|
||||
{
|
||||
// TODO actually check for errors here
|
||||
refresh_tokens
|
||||
.inner_join(crate::schema::users::dsl::users)
|
||||
.filter(token.eq(token_))
|
||||
.first::<(RefreshToken, super::users::User)>(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't get refresh token & user."))
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Updates a token's `last_used_at` column value.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `conn` - database connection to use
|
||||
/// * `token_` - value of the refresh token to update
|
||||
/// * `last_used_at_` - date value to update column with
|
||||
///
|
||||
/// **NOTE**: argument names use trailing underscores as to not conflict with Diesel's imported dsl
|
||||
/// names.
|
||||
pub fn update_last_used_at(
|
||||
conn: &PgConnection,
|
||||
token_: &[u8],
|
||||
last_used_at_: chrono::NaiveDateTime,
|
||||
) -> RbResult<()>
|
||||
{
|
||||
diesel::update(refresh_tokens.filter(token.eq(token_)))
|
||||
.set(last_used_at.eq(last_used_at_))
|
||||
.execute(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't update last_used_at."))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
131
src/db/users.rs
Normal file
131
src/db/users.rs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
use diesel::{prelude::*, AsChangeset, Insertable, Queryable};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
errors::{RbError, RbResult},
|
||||
schema::{users, users::dsl::*},
|
||||
};
|
||||
|
||||
#[derive(Queryable, Serialize)]
|
||||
pub struct User
|
||||
{
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
#[serde(skip_serializing)]
|
||||
pub password: String,
|
||||
pub blocked: bool,
|
||||
pub admin: bool,
|
||||
}
|
||||
|
||||
#[derive(Insertable, Deserialize)]
|
||||
#[table_name = "users"]
|
||||
pub struct NewUser
|
||||
{
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
pub admin: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, AsChangeset)]
|
||||
#[table_name = "users"]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PatchSection
|
||||
{
|
||||
username: Option<String>,
|
||||
admin: Option<bool>,
|
||||
}
|
||||
|
||||
pub fn get(conn: &PgConnection, offset_: u32, limit_: u32) -> RbResult<Vec<User>>
|
||||
{
|
||||
Ok(users
|
||||
.offset(offset_.into())
|
||||
.limit(limit_.into())
|
||||
.load(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't query users."))?)
|
||||
}
|
||||
|
||||
pub fn find(conn: &PgConnection, user_id: Uuid) -> Option<User>
|
||||
{
|
||||
users.find(user_id).first::<User>(conn).ok()
|
||||
}
|
||||
|
||||
pub fn find_by_username(conn: &PgConnection, username_: &str) -> RbResult<User>
|
||||
{
|
||||
Ok(users
|
||||
.filter(username.eq(username_))
|
||||
.first::<User>(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't find users by username."))?)
|
||||
}
|
||||
|
||||
/// Insert a new user into the database
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `conn` - database connection to use
|
||||
/// * `new_user` - user to insert
|
||||
pub fn create(conn: &PgConnection, new_user: &NewUser) -> RbResult<()>
|
||||
{
|
||||
let count = diesel::insert_into(users)
|
||||
.values(new_user)
|
||||
.execute(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't create user."))?;
|
||||
|
||||
if count == 0 {
|
||||
return Err(RbError::UMDuplicateUser);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Either create a new user or update an existing one on conflict.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `conn` - database connection to use
|
||||
/// * `new_user` - user to insert/update
|
||||
// pub fn create_or_update(conn: &PgConnection, new_user: &NewUser) -> RbResult<()>
|
||||
// {
|
||||
// diesel::insert_into(users)
|
||||
// .values(new_user)
|
||||
// .on_conflict(username)
|
||||
// .do_update()
|
||||
// .set(new_user)
|
||||
// .execute(conn)
|
||||
// .map_err(|_| RbError::DbError("Couldn't create or update user."))?;
|
||||
|
||||
// Ok(())
|
||||
// }
|
||||
|
||||
/// Delete the user with the given ID.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// `conn` - database connection to use
|
||||
/// `user_id` - ID of user to delete
|
||||
pub fn delete(conn: &PgConnection, user_id: Uuid) -> RbResult<()>
|
||||
{
|
||||
diesel::delete(users.filter(id.eq(user_id)))
|
||||
.execute(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't delete user."))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Block a user given an ID.
|
||||
/// In practice, this means updating the user's entry so that the `blocked` column is set to
|
||||
/// `true`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// `conn` - database connection to use
|
||||
/// `user_id` - ID of user to block
|
||||
pub fn block(conn: &PgConnection, user_id: Uuid) -> RbResult<()>
|
||||
{
|
||||
diesel::update(users.filter(id.eq(user_id)))
|
||||
.set(blocked.eq(true))
|
||||
.execute(conn)
|
||||
.map_err(|_| RbError::DbError("Couldn't block user."))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
6
src/lib.rs
Normal file
6
src/lib.rs
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
#[macro_use]
|
||||
extern crate diesel;
|
||||
|
||||
pub mod db;
|
||||
#[rustfmt::skip]
|
||||
pub(crate) mod schema;
|
||||
76
src/main.rs
Normal file
76
src/main.rs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
#[macro_use]
|
||||
extern crate rocket;
|
||||
#[macro_use]
|
||||
extern crate diesel_migrations;
|
||||
|
||||
use figment::{
|
||||
providers::{Env, Format, Yaml},
|
||||
Figment,
|
||||
};
|
||||
use rb::auth::JwtConf;
|
||||
use rocket::{
|
||||
fairing::AdHoc,
|
||||
http::Status,
|
||||
serde::json::{json, Value},
|
||||
Build, Request, Rocket,
|
||||
};
|
||||
use rocket_sync_db_pools::database;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod v1;
|
||||
|
||||
/// Used by Rocket to store database connections.
|
||||
#[database("postgres_rb")]
|
||||
pub struct RbDbConn(diesel::PgConnection);
|
||||
|
||||
/// Handles all error status codes.
|
||||
#[catch(default)]
|
||||
fn default_catcher(status: Status, _: &Request) -> Value
|
||||
{
|
||||
json!({"status": status.code, "message": ""})
|
||||
}
|
||||
|
||||
/// Rocket fairing that executes the necessary migrations in our database.
|
||||
async fn run_db_migrations(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>>
|
||||
{
|
||||
embed_migrations!();
|
||||
|
||||
let conn = RbDbConn::get_one(&rocket)
|
||||
.await
|
||||
.expect("database connection");
|
||||
conn.run(|c| match embedded_migrations::run(c) {
|
||||
Ok(()) => Ok(rocket),
|
||||
Err(_) => Err(rocket),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Struct to deserialize from the config file. It contains any custom configuration our
|
||||
/// application might need besides the default Rocket variables.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct RbConfig
|
||||
{
|
||||
jwt: JwtConf,
|
||||
}
|
||||
|
||||
/// The main entrypoint of our program. It launches the Rocket instance.
|
||||
#[launch]
|
||||
fn rocket() -> _
|
||||
{
|
||||
let figment = Figment::from(rocket::config::Config::default())
|
||||
.merge(Yaml::file("Rb.yaml").nested())
|
||||
.merge(Env::prefixed("RB_").global());
|
||||
|
||||
let rocket = rocket::custom(figment)
|
||||
.attach(RbDbConn::fairing())
|
||||
.attach(AdHoc::try_on_ignite(
|
||||
"Run database migrations",
|
||||
run_db_migrations,
|
||||
))
|
||||
.register("/", catchers![default_catcher]);
|
||||
|
||||
let new_figment = rocket.figment();
|
||||
let jwt_conf: JwtConf = new_figment.extract_inner("jwt").expect("jwt config");
|
||||
|
||||
rocket.manage(jwt_conf)
|
||||
}
|
||||
0
src/v1/mod.rs
Normal file
0
src/v1/mod.rs
Normal file
0
src/v1/users.rs
Normal file
0
src/v1/users.rs
Normal file
Reference in a new issue