Compare commits
2 Commits
dd51d107e3
...
27b904b3f5
| Author | SHA1 | Date |
|---|---|---|
|
|
27b904b3f5 | |
|
|
6858e9da62 |
|
|
@ -1,4 +1,3 @@
|
|||
use argon2::verify_encoded;
|
||||
use chrono::Utc;
|
||||
use diesel::{insert_into, prelude::*, PgConnection};
|
||||
use hmac::{Hmac, NewMac};
|
||||
|
|
@ -10,31 +9,12 @@ use sha2::Sha256;
|
|||
use crate::{
|
||||
db::{
|
||||
tokens::{NewRefreshToken, RefreshToken},
|
||||
users::{NewUser, User},
|
||||
users::User,
|
||||
},
|
||||
errors::RbError,
|
||||
schema::{refresh_tokens::dsl as refresh_tokens, users::dsl as users},
|
||||
};
|
||||
|
||||
pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> crate::Result<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),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JWTResponse
|
||||
|
|
@ -96,39 +76,6 @@ pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> crate::Result<JWT
|
|||
})
|
||||
}
|
||||
|
||||
pub fn hash_password(password: &str) -> crate::Result<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)
|
||||
-> crate::Result<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)
|
||||
}
|
||||
|
||||
pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> crate::Result<JWTResponse>
|
||||
{
|
||||
let token_bytes =
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
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,
|
||||
};
|
||||
|
||||
pub mod jwt;
|
||||
|
||||
pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> crate::Result<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) -> crate::Result<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)
|
||||
-> crate::Result<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)
|
||||
}
|
||||
|
|
@ -79,6 +79,7 @@ impl<'r> Responder<'r, 'static> for RbError
|
|||
"message": self.message(),
|
||||
});
|
||||
|
||||
// TODO add status to response
|
||||
content.respond_to(req)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use hmac::{Hmac, NewMac};
|
||||
use jwt::VerifyWithKey;
|
||||
use rb::auth::Claims;
|
||||
use rb::auth::jwt::Claims;
|
||||
use rocket::{
|
||||
http::Status,
|
||||
outcome::try_outcome,
|
||||
|
|
@ -39,10 +39,10 @@ impl<'r> FromRequest<'r> for Bearer<'r>
|
|||
}
|
||||
|
||||
/// Verifies the provided JWT is valid.
|
||||
pub struct JWT(Claims);
|
||||
pub struct Jwt(Claims);
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for JWT
|
||||
impl<'r> FromRequest<'r> for Jwt
|
||||
{
|
||||
type Error = rb::errors::RbError;
|
||||
|
||||
|
|
@ -91,7 +91,7 @@ impl<'r> FromRequest<'r> for User
|
|||
|
||||
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
|
||||
{
|
||||
let claims = try_outcome!(req.guard::<JWT>().await).0;
|
||||
let claims = try_outcome!(req.guard::<Jwt>().await).0;
|
||||
|
||||
// Verify key hasn't yet expired
|
||||
if chrono::Utc::now().timestamp() > claims.exp {
|
||||
|
|
|
|||
|
|
@ -10,13 +10,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) -> rb::Result<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>) -> rb::Result<()>
|
||||
{
|
||||
Ok(conn
|
||||
.run(move |c| db::users::create(c, &user.into_inner()))
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
use rb::auth::{generate_jwt_token, verify_user, JWTResponse};
|
||||
use rb::auth::{
|
||||
jwt::{generate_jwt_token, JWTResponse},
|
||||
verify_user,
|
||||
};
|
||||
use rocket::serde::json::Json;
|
||||
use serde::Deserialize;
|
||||
|
||||
|
|
@ -51,7 +54,7 @@ async fn refresh_token(
|
|||
let refresh_token = refresh_token_request.into_inner().refresh_token;
|
||||
|
||||
Ok(Json(
|
||||
conn.run(move |c| rb::auth::refresh_token(c, &refresh_token))
|
||||
conn.run(move |c| rb::auth::jwt::refresh_token(c, &refresh_token))
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
|
|
|
|||
Reference in New Issue