Moved code & started split into binary & library
This commit is contained in:
parent
26e2f5f3b1
commit
2ab88c09db
15 changed files with 375 additions and 83 deletions
|
|
@ -3,15 +3,14 @@ use diesel::PgConnection;
|
|||
use hmac::{Hmac, NewMac};
|
||||
use jwt::SignWithKey;
|
||||
use rand::{thread_rng, Rng};
|
||||
use rb::{
|
||||
auth::JwtConf,
|
||||
errors::{RbError, RbResult},
|
||||
};
|
||||
use rb_gw::db;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::{
|
||||
db,
|
||||
errors::{RbError, RbResult},
|
||||
RbJwtConf,
|
||||
};
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JWTResponse
|
||||
|
|
@ -31,7 +30,7 @@ pub struct Claims
|
|||
|
||||
pub fn generate_jwt_token(
|
||||
conn: &PgConnection,
|
||||
jwt: &RbJwtConf,
|
||||
jwt: &JwtConf,
|
||||
user: &db::User,
|
||||
) -> RbResult<JWTResponse>
|
||||
{
|
||||
|
|
@ -78,7 +77,7 @@ pub fn generate_jwt_token(
|
|||
|
||||
pub fn refresh_token(
|
||||
conn: &PgConnection,
|
||||
jwt: &RbJwtConf,
|
||||
jwt: &JwtConf,
|
||||
refresh_token: &str,
|
||||
) -> RbResult<JWTResponse>
|
||||
{
|
||||
|
|
|
|||
8
src/db/mod.rs
Normal file
8
src/db/mod.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! The db module contains all Diesel-related logic. This is to prevent the various Diesel imports
|
||||
//! from poluting other modules' namespaces.
|
||||
|
||||
pub mod tokens;
|
||||
pub mod users;
|
||||
|
||||
pub use tokens::{NewRefreshToken, RefreshToken};
|
||||
pub use users::{NewUser, User};
|
||||
120
src/db/tokens.rs
Normal file
120
src/db/tokens.rs
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
//! Handles refresh token-related database operations.
|
||||
|
||||
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
|
||||
use rb::errors::{RbError, RbResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::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(())
|
||||
}
|
||||
129
src/db/users.rs
Normal file
129
src/db/users.rs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
use diesel::{prelude::*, AsChangeset, Insertable, Queryable};
|
||||
use rb::errors::{RbError, RbResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::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(())
|
||||
}
|
||||
5
src/lib.rs
Normal file
5
src/lib.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
#[macro_use]
|
||||
extern crate diesel;
|
||||
|
||||
pub mod db;
|
||||
pub(crate) mod schema;
|
||||
|
|
@ -1,13 +1,3 @@
|
|||
table! {
|
||||
posts (id) {
|
||||
id -> Uuid,
|
||||
section_id -> Uuid,
|
||||
title -> Nullable<Varchar>,
|
||||
publish_date -> Date,
|
||||
content -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
refresh_tokens (token) {
|
||||
token -> Bytea,
|
||||
|
|
@ -17,17 +7,6 @@ table! {
|
|||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
sections (id) {
|
||||
id -> Uuid,
|
||||
title -> Varchar,
|
||||
shortname -> Varchar,
|
||||
description -> Nullable<Text>,
|
||||
is_default -> Bool,
|
||||
has_titles -> Bool,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
users (id) {
|
||||
id -> Uuid,
|
||||
|
|
@ -38,12 +17,9 @@ table! {
|
|||
}
|
||||
}
|
||||
|
||||
joinable!(posts -> sections (section_id));
|
||||
joinable!(refresh_tokens -> users (user_id));
|
||||
|
||||
allow_tables_to_appear_in_same_query!(
|
||||
posts,
|
||||
refresh_tokens,
|
||||
sections,
|
||||
users,
|
||||
);
|
||||
|
|
|
|||
Reference in a new issue