diff --git a/src/auth.rs b/src/auth.rs index 613c210..efd991d 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -81,7 +81,6 @@ pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> crate::Result crate::Result> { users.load::(conn).map_err(|_| RBError::DBError) } + +pub fn find(conn: &PgConnection, user_id: Uuid) -> Option +{ + users.find(user_id).first::(conn).ok() +} + +pub fn create(conn: &PgConnection, new_user: &NewUser) -> crate::Result<()> +{ + let count = diesel::insert_into(users) + .values(new_user) + .execute(conn) + .map_err(|_| RBError::DBError)?; + + if count == 0 { + return Err(RBError::DuplicateUser); + } + + Ok(()) +} + +pub fn delete(conn: &PgConnection, user_id: Uuid) -> crate::Result<()> +{ + diesel::delete(users.filter(id.eq(user_id))) + .execute(conn) + .map_err(|_| RBError::DBError)?; + + Ok(()) +} diff --git a/src/errors.rs b/src/errors.rs index bc3243f..7072dab 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -28,6 +28,7 @@ pub enum RBError InvalidRefreshToken, DuplicateRefreshToken, DBError, + DuplicateUser, } impl<'r> Responder<'r, 'static> for RBError @@ -46,6 +47,7 @@ impl<'r> Responder<'r, 'static> for RBError RBError::InvalidRefreshToken | RBError::DuplicateRefreshToken => { (Status::Unauthorized, "Invalid refresh token.") } + RBError::DuplicateUser => (Status::Conflict, "User already exists"), _ => (Status::InternalServerError, "Internal server error"), }; diff --git a/src/routes/admin.rs b/src/routes/admin.rs index db3ecc2..b3db29b 100644 --- a/src/routes/admin.rs +++ b/src/routes/admin.rs @@ -1,11 +1,18 @@ -use rb::db::users::User; +use rb::{ + db::{ + users as db_users, + users::{NewUser, User}, + }, + errors::RBError, +}; use rocket::serde::json::Json; +use uuid::Uuid; use crate::{guards::Admin, RbDbConn}; pub fn routes() -> Vec { - routes![get_users] + routes![get_users, get_user_info] } #[get("/users")] @@ -13,3 +20,22 @@ async fn get_users(admin: Admin, conn: RbDbConn) -> rb::Result>> { Ok(Json(conn.run(|c| rb::db::users::all(c)).await?)) } + +#[post("/users", data = "")] +async fn create_user(admin: Admin, conn: RbDbConn, user: Json) -> rb::Result<()> +{ + Ok(conn + .run(move |c| db_users::create(c, &user.into_inner())) + .await?) +} + +#[get("/users/")] +async fn get_user_info(_admin: Admin, conn: RbDbConn, user_id_str: &str) -> rb::Result> +{ + let user_id = Uuid::parse_str(user_id_str).map_err(|_| RBError::UnknownUser)?; + + match conn.run(move |c| db_users::find(c, user_id)).await { + Some(user) => Ok(Json(user)), + None => Err(RBError::UnknownUser), + } +}