From 0c656f0fe6b61c35bd40d43829a6a63fe353c589 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Mon, 22 Aug 2022 22:32:54 +0200 Subject: Create user --- server/src/models/user.rs | 29 ++++++++++++++++++++++++----- server/src/routes/user.rs | 16 +++++++++++++--- 2 files changed, 37 insertions(+), 8 deletions(-) (limited to 'server/src') diff --git a/server/src/models/user.rs b/server/src/models/user.rs index 08514a8..9545fac 100644 --- a/server/src/models/user.rs +++ b/server/src/models/user.rs @@ -8,22 +8,41 @@ pub struct User { id: i32, email: String, password: String, + is_staff: Option, } #[derive(Deserialize, Serialize)] pub struct UserList { id: i32, email: String, + is_staff: Option, +} + +#[derive(Deserialize)] +pub struct UserCreate { + pub email: String, + pub password: String, } impl User { - pub async fn create(user: User) -> Result { + pub fn new(email: String, password: String) -> Self { + let crypted_password = sha256::digest(password); + Self { + id: 0, + email, + password: crypted_password, + is_staff: Some(false), + } + } + + pub async fn create(user: User) -> Result { let pool = unsafe { get_client() }; - let rec = sqlx::query!( + let rec = sqlx::query_as!( + UserList, r#" INSERT INTO users (email, password) VALUES ( $1, $2 ) - RETURNING id + RETURNING id, email, is_staff "#, user.email, user.password @@ -31,12 +50,12 @@ impl User { .fetch_one(pool) .await?; - Ok(rec.id) + Ok(rec) } pub async fn list() -> Result, AppError> { let pool = unsafe { get_client() }; - let rows = sqlx::query_as!(UserList, r#"SELECT id, email FROM users"#) + let rows = sqlx::query_as!(UserList, r#"SELECT id, email, is_staff FROM users"#) .fetch_all(pool) .await?; diff --git a/server/src/routes/user.rs b/server/src/routes/user.rs index 1b43e01..7aecccb 100644 --- a/server/src/routes/user.rs +++ b/server/src/routes/user.rs @@ -1,9 +1,12 @@ use crate::errors::AppError; -use crate::models::user::{User, UserList}; -use axum::{routing::get, Json, Router}; +use crate::models::user::{User, UserCreate, UserList}; +use axum::{ + routing::{get}, + Json, Router, +}; pub fn create_route() -> Router { - Router::new().route("/", get(list_users)) + Router::new().route("/", get(list_users).post(create_user)) } async fn list_users() -> Result>, AppError> { @@ -11,3 +14,10 @@ async fn list_users() -> Result>, AppError> { Ok(Json(users)) } + +async fn create_user(Json(payload): Json) -> Result, AppError> { + let user = User::new(payload.email, payload.password); + let user_new = User::create(user).await?; + + Ok(Json(user_new)) +} -- cgit v1.2.3-18-g5258