Compare commits
2 Commits
87d8d8ff0c
...
02011e04ce
| Author | SHA1 | Date |
|---|---|---|
|
|
02011e04ce | |
|
|
1378219fe5 |
|
|
@ -0,0 +1,61 @@
|
||||||
|
use diesel::{insert_into, prelude::*, PgConnection};
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
auth::pass::hash_password,
|
||||||
|
db,
|
||||||
|
errors::{RbError, RbResult},
|
||||||
|
guards::Admin,
|
||||||
|
schema::users::dsl as users,
|
||||||
|
RbDbConn,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[get("/users")]
|
||||||
|
pub 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>")]
|
||||||
|
pub 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()))
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/users/<user_id_str>")]
|
||||||
|
pub 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)?;
|
||||||
|
|
||||||
|
match conn.run(move |c| db::users::find(c, user_id)).await {
|
||||||
|
Some(user) => Ok(Json(user)),
|
||||||
|
None => Err(RbError::UMUnknownUser),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_admin_user(conn: &PgConnection, username: &str, password: &str) -> RbResult<bool>
|
||||||
|
{
|
||||||
|
let pass_hashed = hash_password(password)?;
|
||||||
|
let new_user = db::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)
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use diesel::{insert_into, prelude::*, PgConnection};
|
use diesel::{prelude::*, PgConnection};
|
||||||
use hmac::{Hmac, NewMac};
|
use hmac::{Hmac, NewMac};
|
||||||
use jwt::SignWithKey;
|
use jwt::SignWithKey;
|
||||||
use rand::{thread_rng, Rng};
|
use rand::{thread_rng, Rng};
|
||||||
|
|
@ -7,10 +7,8 @@ use serde::{Deserialize, Serialize};
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
db::{
|
db,
|
||||||
tokens::{NewRefreshToken, RefreshToken},
|
db::{tokens::NewRefreshToken, users::User},
|
||||||
users::User,
|
|
||||||
},
|
|
||||||
errors::{RbError, RbResult},
|
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},
|
||||||
};
|
};
|
||||||
|
|
@ -61,14 +59,14 @@ pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> RbResult<JWTRespo
|
||||||
(current_time + chrono::Duration::seconds(crate::REFRESH_TOKEN_EXP_SECONDS)).naive_utc();
|
(current_time + chrono::Duration::seconds(crate::REFRESH_TOKEN_EXP_SECONDS)).naive_utc();
|
||||||
|
|
||||||
// Store refresh token in database
|
// Store refresh token in database
|
||||||
insert_into(refresh_tokens::refresh_tokens)
|
db::tokens::create(
|
||||||
.values(NewRefreshToken {
|
conn,
|
||||||
|
&NewRefreshToken {
|
||||||
token: refresh_token.to_vec(),
|
token: refresh_token.to_vec(),
|
||||||
user_id: user.id,
|
user_id: user.id,
|
||||||
expires_at: refresh_expire,
|
expires_at: refresh_expire,
|
||||||
})
|
},
|
||||||
.execute(conn)
|
)?;
|
||||||
.map_err(|_| RbError::Custom("Couldn't insert refresh token."))?;
|
|
||||||
|
|
||||||
Ok(JWTResponse {
|
Ok(JWTResponse {
|
||||||
token,
|
token,
|
||||||
|
|
@ -82,11 +80,8 @@ pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> RbResult<JWTRe
|
||||||
base64::decode(refresh_token).map_err(|_| RbError::AuthInvalidRefreshToken)?;
|
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
|
// First, we request the token from the database to see if it's really a valid token
|
||||||
let (token_entry, user) = refresh_tokens::refresh_tokens
|
let (token_entry, user) =
|
||||||
.inner_join(users::users)
|
db::tokens::find_with_user(conn, &token_bytes).ok_or(RbError::AuthInvalidRefreshToken)?;
|
||||||
.filter(refresh_tokens::token.eq(token_bytes))
|
|
||||||
.first::<(RefreshToken, User)>(conn)
|
|
||||||
.map_err(|_| RbError::AuthInvalidRefreshToken)?;
|
|
||||||
|
|
||||||
// If we see that the token has already been used before, we block the user.
|
// If we see that the token has already been used before, we block the user.
|
||||||
if token_entry.last_used_at.is_some() {
|
if token_entry.last_used_at.is_some() {
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ use self::{
|
||||||
jwt::{generate_jwt_token, JWTResponse},
|
jwt::{generate_jwt_token, JWTResponse},
|
||||||
pass::verify_user,
|
pass::verify_user,
|
||||||
};
|
};
|
||||||
use crate::{guards::User, RbDbConn, RbResult};
|
use crate::{errors::RbResult, guards::User, RbDbConn};
|
||||||
|
|
||||||
pub mod jwt;
|
pub mod jwt;
|
||||||
pub mod pass;
|
pub mod pass;
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,11 @@
|
||||||
use argon2::verify_encoded;
|
use argon2::verify_encoded;
|
||||||
use diesel::{insert_into, prelude::*, PgConnection};
|
use diesel::{prelude::*, PgConnection};
|
||||||
use rand::{thread_rng, Rng};
|
use rand::{thread_rng, Rng};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
db::users::{NewUser, User},
|
db::users::User,
|
||||||
errors::RbError,
|
errors::{RbError, RbResult},
|
||||||
schema::users::dsl as users,
|
schema::users::dsl as users,
|
||||||
RbResult,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> RbResult<User>
|
pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> RbResult<User>
|
||||||
|
|
@ -39,23 +38,3 @@ pub fn hash_password(password: &str) -> RbResult<String>
|
||||||
argon2::hash_encoded(password.as_bytes(), &salt, &config)
|
argon2::hash_encoded(password.as_bytes(), &salt, &config)
|
||||||
.map_err(|_| RbError::Custom("Couldn't hash password."))
|
.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)
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,10 @@
|
||||||
use diesel::{Insertable, Queryable};
|
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::schema::refresh_tokens;
|
use crate::{
|
||||||
|
errors::{RbError, RbResult},
|
||||||
|
schema::{refresh_tokens, refresh_tokens::dsl::*},
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Queryable)]
|
#[derive(Queryable)]
|
||||||
pub struct RefreshToken
|
pub struct RefreshToken
|
||||||
|
|
@ -20,3 +23,36 @@ pub struct NewRefreshToken
|
||||||
pub user_id: Uuid,
|
pub user_id: Uuid,
|
||||||
pub expires_at: chrono::NaiveDateTime,
|
pub expires_at: chrono::NaiveDateTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn all(conn: &PgConnection) -> RbResult<Vec<RefreshToken>>
|
||||||
|
{
|
||||||
|
refresh_tokens
|
||||||
|
.load::<RefreshToken>(conn)
|
||||||
|
.map_err(|_| RbError::DbError("Couldn't get all refresh tokens."))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create(conn: &PgConnection, new_refresh_token: &NewRefreshToken) -> RbResult<()>
|
||||||
|
{
|
||||||
|
insert_into(refresh_tokens)
|
||||||
|
.values(new_refresh_token)
|
||||||
|
.execute(conn)
|
||||||
|
.map_err(|_| RbError::Custom("Couldn't insert refresh token."))?;
|
||||||
|
|
||||||
|
// TODO check for conflict?
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find_with_user(
|
||||||
|
conn: &PgConnection,
|
||||||
|
token_val: &[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_val))
|
||||||
|
.first::<(RefreshToken, super::users::User)>(conn)
|
||||||
|
.map_err(|_| RbError::Custom("Couldn't get refresh token & user."))
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
|
||||||
11
src/main.rs
11
src/main.rs
|
|
@ -11,13 +11,11 @@ extern crate diesel;
|
||||||
use rocket::{fairing::AdHoc, Build, Rocket};
|
use rocket::{fairing::AdHoc, Build, Rocket};
|
||||||
use rocket_sync_db_pools::database;
|
use rocket_sync_db_pools::database;
|
||||||
|
|
||||||
pub use crate::errors::{RbError, RbResult};
|
mod admin;
|
||||||
|
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod db;
|
pub mod db;
|
||||||
pub mod errors;
|
pub mod errors;
|
||||||
pub mod guards;
|
pub mod guards;
|
||||||
mod routes;
|
|
||||||
pub(crate) mod schema;
|
pub(crate) mod schema;
|
||||||
|
|
||||||
// Any import defaults are defined here
|
// Any import defaults are defined here
|
||||||
|
|
@ -54,7 +52,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| {
|
||||||
auth::pass::create_admin_user(c, &admin_user, &admin_password)
|
admin::create_admin_user(c, &admin_user, &admin_password)
|
||||||
.expect("failed to create admin user")
|
.expect("failed to create admin user")
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
|
@ -76,5 +74,8 @@ fn rocket() -> _
|
||||||
"/api/auth",
|
"/api/auth",
|
||||||
routes![auth::already_logged_in, auth::login, auth::refresh_token,],
|
routes![auth::already_logged_in, auth::login, auth::refresh_token,],
|
||||||
)
|
)
|
||||||
.mount("/api/admin", routes::admin::routes())
|
.mount(
|
||||||
|
"/api/admin",
|
||||||
|
routes![admin::get_users, admin::create_user, admin::get_user_info],
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
use rocket::serde::json::Json;
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
db,
|
|
||||||
errors::{RbError, RbResult},
|
|
||||||
guards::Admin,
|
|
||||||
RbDbConn,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub fn routes() -> Vec<rocket::Route>
|
|
||||||
{
|
|
||||||
routes![get_users, get_user_info, create_user]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/users")]
|
|
||||||
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>) -> RbResult<()>
|
|
||||||
{
|
|
||||||
Ok(conn
|
|
||||||
.run(move |c| db::users::create(c, &user.into_inner()))
|
|
||||||
.await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/users/<user_id_str>")]
|
|
||||||
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)?;
|
|
||||||
|
|
||||||
match conn.run(move |c| db::users::find(c, user_id)).await {
|
|
||||||
Some(user) => Ok(Json(user)),
|
|
||||||
None => Err(RbError::UMUnknownUser),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
pub mod admin;
|
|
||||||
Reference in New Issue