Switched to binary-only project
parent
c64eaf2ff5
commit
87d8d8ff0c
|
@ -4,10 +4,6 @@ version = "0.1.0"
|
||||||
authors = ["Jef Roosens <roosensjef@gmail.com>"]
|
authors = ["Jef Roosens <roosensjef@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "rb"
|
|
||||||
path = "src/lib.rs"
|
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "rbd"
|
name = "rbd"
|
||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|
|
@ -11,7 +11,7 @@ use crate::{
|
||||||
tokens::{NewRefreshToken, RefreshToken},
|
tokens::{NewRefreshToken, RefreshToken},
|
||||||
users::User,
|
users::User,
|
||||||
},
|
},
|
||||||
errors::RbError,
|
errors::{RbError, RbResult},
|
||||||
schema::{refresh_tokens::dsl as refresh_tokens, users::dsl as users},
|
schema::{refresh_tokens::dsl as refresh_tokens, users::dsl as users},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -32,7 +32,7 @@ pub struct Claims
|
||||||
pub exp: i64,
|
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 secret = std::env::var("JWT_KEY").map_err(|_| RbError::Custom("Missing JWT key."))?;
|
||||||
let key: Hmac<Sha256> = Hmac::new_from_slice(secret.as_bytes())
|
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 =
|
let token_bytes =
|
||||||
base64::decode(refresh_token).map_err(|_| RbError::AuthInvalidRefreshToken)?;
|
base64::decode(refresh_token).map_err(|_| RbError::AuthInvalidRefreshToken)?;
|
||||||
|
|
|
@ -1,63 +1,58 @@
|
||||||
use argon2::verify_encoded;
|
use rocket::serde::json::Json;
|
||||||
use diesel::{insert_into, prelude::*, PgConnection};
|
use serde::Deserialize;
|
||||||
use rand::{thread_rng, Rng};
|
|
||||||
|
|
||||||
use crate::{
|
use self::{
|
||||||
db::users::{NewUser, User},
|
jwt::{generate_jwt_token, JWTResponse},
|
||||||
errors::RbError,
|
pass::verify_user,
|
||||||
schema::users::dsl as users,
|
|
||||||
};
|
};
|
||||||
|
use crate::{guards::User, RbDbConn, RbResult};
|
||||||
|
|
||||||
pub mod jwt;
|
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
|
username: String,
|
||||||
let user = users::users
|
password: String,
|
||||||
.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()) {
|
#[post("/login")]
|
||||||
Ok(true) => Ok(user),
|
pub async fn already_logged_in(_user: User) -> String
|
||||||
_ => Err(RbError::AuthInvalidPassword),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn hash_password(password: &str) -> crate::Result<String>
|
|
||||||
{
|
{
|
||||||
// Generate a random salt
|
String::from("You're already logged in!")
|
||||||
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)
|
#[post("/login", data = "<credentials>", rank = 2)]
|
||||||
-> crate::Result<bool>
|
pub async fn login(conn: RbDbConn, credentials: Json<Credentials>) -> RbResult<Json<JWTResponse>>
|
||||||
{
|
{
|
||||||
let pass_hashed = hash_password(password)?;
|
let credentials = credentials.into_inner();
|
||||||
let new_user = NewUser {
|
|
||||||
username: username.to_string(),
|
|
||||||
password: pass_hashed,
|
|
||||||
admin: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
insert_into(users::users)
|
// Get the user, if credentials are valid
|
||||||
.values(&new_user)
|
let user = conn
|
||||||
.on_conflict(users::username)
|
.run(move |c| verify_user(c, &credentials.username, &credentials.password))
|
||||||
.do_update()
|
.await?;
|
||||||
.set(&new_user)
|
|
||||||
.execute(conn)
|
|
||||||
.map_err(|_| RbError::Custom("Couldn't create admin."))?;
|
|
||||||
|
|
||||||
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?,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
|
@ -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)
|
||||||
|
}
|
|
@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
errors::RbError,
|
errors::{RbError, RbResult},
|
||||||
schema::{users, users::dsl::*},
|
schema::{users, users::dsl::*},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -28,7 +28,7 @@ pub struct NewUser
|
||||||
pub admin: bool,
|
pub admin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn all(conn: &PgConnection) -> crate::Result<Vec<User>>
|
pub fn all(conn: &PgConnection) -> RbResult<Vec<User>>
|
||||||
{
|
{
|
||||||
users
|
users
|
||||||
.load::<User>(conn)
|
.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()
|
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)
|
let count = diesel::insert_into(users)
|
||||||
.values(new_user)
|
.values(new_user)
|
||||||
|
@ -54,7 +54,7 @@ pub fn create(conn: &PgConnection, new_user: &NewUser) -> crate::Result<()>
|
||||||
Ok(())
|
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)))
|
diesel::delete(users.filter(id.eq(user_id)))
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
|
|
|
@ -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>;
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
use hmac::{Hmac, NewMac};
|
use hmac::{Hmac, NewMac};
|
||||||
use jwt::VerifyWithKey;
|
use jwt::VerifyWithKey;
|
||||||
use rb::auth::jwt::Claims;
|
|
||||||
use rocket::{
|
use rocket::{
|
||||||
http::Status,
|
http::Status,
|
||||||
outcome::try_outcome,
|
outcome::try_outcome,
|
||||||
|
@ -8,13 +7,15 @@ use rocket::{
|
||||||
};
|
};
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
|
|
||||||
|
use crate::auth::jwt::Claims;
|
||||||
|
|
||||||
/// Extracts a "Authorization: Bearer" string from the headers.
|
/// Extracts a "Authorization: Bearer" string from the headers.
|
||||||
pub struct Bearer<'a>(&'a str);
|
pub struct Bearer<'a>(&'a str);
|
||||||
|
|
||||||
#[rocket::async_trait]
|
#[rocket::async_trait]
|
||||||
impl<'r> FromRequest<'r> for Bearer<'r>
|
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>
|
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
|
||||||
{
|
{
|
||||||
|
@ -44,7 +45,7 @@ pub struct Jwt(Claims);
|
||||||
#[rocket::async_trait]
|
#[rocket::async_trait]
|
||||||
impl<'r> FromRequest<'r> for Jwt
|
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>
|
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
|
||||||
{
|
{
|
||||||
|
@ -87,7 +88,7 @@ pub struct User(Claims);
|
||||||
#[rocket::async_trait]
|
#[rocket::async_trait]
|
||||||
impl<'r> FromRequest<'r> for User
|
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>
|
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
|
||||||
{
|
{
|
||||||
|
@ -108,7 +109,7 @@ pub struct Admin(Claims);
|
||||||
#[rocket::async_trait]
|
#[rocket::async_trait]
|
||||||
impl<'r> FromRequest<'r> for Admin
|
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>
|
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
|
||||||
{
|
{
|
||||||
|
|
17
src/lib.rs
17
src/lib.rs
|
@ -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;
|
|
30
src/main.rs
30
src/main.rs
|
@ -1,23 +1,38 @@
|
||||||
// This needs to be explicitely included before diesel is imported to make sure
|
// This needs to be explicitely included before diesel is imported to make sure
|
||||||
// compilation succeeds in the release Docker image.
|
// compilation succeeds in the release Docker image.
|
||||||
extern crate openssl;
|
extern crate openssl;
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket;
|
extern crate rocket;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate diesel_migrations;
|
extern crate diesel_migrations;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate diesel;
|
||||||
|
|
||||||
use rocket::{fairing::AdHoc, Build, Rocket};
|
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;
|
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")]
|
#[database("postgres_rb")]
|
||||||
pub struct RbDbConn(diesel::PgConnection);
|
pub struct RbDbConn(diesel::PgConnection);
|
||||||
|
|
||||||
|
embed_migrations!();
|
||||||
|
|
||||||
async fn run_db_migrations(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>>
|
async fn run_db_migrations(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>>
|
||||||
{
|
{
|
||||||
let conn = RbDbConn::get_one(&rocket)
|
let conn = RbDbConn::get_one(&rocket)
|
||||||
|
@ -39,7 +54,7 @@ async fn create_admin_user(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocke
|
||||||
.await
|
.await
|
||||||
.expect("database connection");
|
.expect("database connection");
|
||||||
conn.run(move |c| {
|
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")
|
.expect("failed to create admin user")
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
@ -57,6 +72,9 @@ fn rocket() -> _
|
||||||
run_db_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", routes::auth::routes())
|
.mount(
|
||||||
|
"/api/auth",
|
||||||
|
routes![auth::already_logged_in, auth::login, auth::refresh_token,],
|
||||||
|
)
|
||||||
.mount("/api/admin", routes::admin::routes())
|
.mount("/api/admin", routes::admin::routes())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,12 @@
|
||||||
use rb::{db, errors::RbError};
|
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{guards::Admin, RbDbConn};
|
use crate::{
|
||||||
|
db,
|
||||||
|
errors::{RbError, RbResult},
|
||||||
|
guards::Admin,
|
||||||
|
RbDbConn,
|
||||||
|
};
|
||||||
|
|
||||||
pub fn routes() -> Vec<rocket::Route>
|
pub fn routes() -> Vec<rocket::Route>
|
||||||
{
|
{
|
||||||
|
@ -10,13 +14,13 @@ pub fn routes() -> Vec<rocket::Route>
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/users")]
|
#[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?))
|
Ok(Json(conn.run(|c| db::users::all(c)).await?))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/users", data = "<user>")]
|
#[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
|
Ok(conn
|
||||||
.run(move |c| db::users::create(c, &user.into_inner()))
|
.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>")]
|
#[get("/users/<user_id_str>")]
|
||||||
async fn get_user_info(
|
async fn get_user_info(_admin: Admin, conn: RbDbConn, user_id_str: &str)
|
||||||
_admin: Admin,
|
-> RbResult<Json<db::User>>
|
||||||
conn: RbDbConn,
|
|
||||||
user_id_str: &str,
|
|
||||||
) -> rb::Result<Json<db::User>>
|
|
||||||
{
|
{
|
||||||
let user_id = Uuid::parse_str(user_id_str).map_err(|_| RbError::UMUnknownUser)?;
|
let user_id = Uuid::parse_str(user_id_str).map_err(|_| RbError::UMUnknownUser)?;
|
||||||
|
|
||||||
|
|
|
@ -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?,
|
|
||||||
))
|
|
||||||
}
|
|
|
@ -1,2 +1 @@
|
||||||
pub mod admin;
|
pub mod admin;
|
||||||
pub mod auth;
|
|
||||||
|
|
Reference in New Issue