Skip to content

Commit

Permalink
Implement registration endpoint
Browse files Browse the repository at this point in the history
Currently only validates inputs and creates the user. Still needs
authentication and anonymous user merging before being complete.

To facilitate the implementation, multiple other crates were pulled in
and features were implemented, notably:
 - Struct validation was implemented via Validator, and Axum's flexible
   API was used to generate responses.
 - Error responses in the format expected by the client (generic /
   specific errors) were implemented.
 - rs-snowflake was used to generate snowflake IDs.
 - chrono was used for dates and times.
 - bcrypt was used for password hashing.
  • Loading branch information
Aleksbgbg committed Feb 7, 2024
1 parent eae8300 commit 253377c
Show file tree
Hide file tree
Showing 11 changed files with 438 additions and 7 deletions.
126 changes: 125 additions & 1 deletion backend-rs/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions backend-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@ edition = "2021"

[dependencies]
axum = "0.7.4"
bcrypt = "0.15.0"
chrono = "0.4.33"
convert_case = "0.6.0"
lazy_static = "1.4.0"
rs-snowflake = "0.6.0"
sea-orm = { version = "0.12.14", features = ["runtime-tokio-native-tls", "sqlx-postgres"] }
sea-orm-migration = "0.12.12"
serde = { version = "1.0.196", features = ["derive"] }
serde_json = "1.0.113"
thiserror = "1.0.56"
tokio = { version = "1.36.0", features = ["rt-multi-thread"] }
toml-env = "1.1.1"
tower-http = { version = "0.5.1", features = ["trace"] }
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
validator = { version = "0.16.1", features = ["derive"] }
8 changes: 8 additions & 0 deletions backend-rs/src/app_state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use sea_orm::DatabaseConnection;
use snowflake::SnowflakeIdBucket;

#[derive(Clone)]
pub struct AppState {
pub connection: DatabaseConnection,
pub user_snowflake: SnowflakeIdBucket,
}
3 changes: 3 additions & 0 deletions backend-rs/src/controllers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod errors;
pub mod user;
pub mod validate;
83 changes: 83 additions & 0 deletions backend-rs/src/controllers/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use crate::models::user;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use lazy_static::lazy_static;
use sea_orm::DbErr;
use serde::Serialize;
use serde_json::json;
use std::collections::HashMap;
use thiserror::Error;

lazy_static! {
pub static ref FAILED_VALIDATION: Errors =
Errors::generic("Some inputs failed validation.".to_string());
}

#[derive(Serialize, Default, Clone)]
pub struct Errors {
generic: Vec<String>,
specific: HashMap<String, Vec<String>>,
}

impl Errors {
pub fn generic(value: String) -> Self {
let mut errors = Self::default();
errors.add_generic(value);
errors
}

pub fn add_generic(&mut self, value: String) {
self.generic.push(value);
}

pub fn add_one_specific(&mut self, key: String, value: String) {
self.add_specific(key, vec![value]);
}

pub fn add_specific(&mut self, key: String, value: Vec<String>) {
self.specific.insert(key, value);
}
}

impl IntoResponse for Errors {
fn into_response(self) -> Response {
json!({"errors": &self}).to_string().into_response()
}
}

#[derive(Error, Debug)]
pub enum HandlerError {
#[error("Username must not be taken.")]
UsernameTaken,
#[error("Email Address must not be taken.")]
EmailTaken,

#[error("Database transaction failed.")]
Database(#[from] DbErr),
#[error("Could not create user.")]
CreateUser(#[from] user::CreateError),
}

impl HandlerError {
fn into_generic(self, code: StatusCode) -> (StatusCode, Errors) {
(code, Errors::generic(self.to_string()))
}

fn failed_validation(self, code: StatusCode, key: &str) -> (StatusCode, Errors) {
let mut errors = FAILED_VALIDATION.clone();
errors.add_one_specific(key.to_string(), self.to_string());
(code, errors)
}
}

impl IntoResponse for HandlerError {
fn into_response(self) -> Response {
match self {
HandlerError::UsernameTaken => self.failed_validation(StatusCode::BAD_REQUEST, "username"),
HandlerError::EmailTaken => self.failed_validation(StatusCode::BAD_REQUEST, "emailAddress"),
HandlerError::Database(_) => self.into_generic(StatusCode::INTERNAL_SERVER_ERROR),
HandlerError::CreateUser(_) => self.into_generic(StatusCode::INTERNAL_SERVER_ERROR),
}
.into_response()
}
}
45 changes: 45 additions & 0 deletions backend-rs/src/controllers/user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use crate::app_state::AppState;
use crate::controllers::errors::HandlerError;
use crate::controllers::validate::ValidatedJson;
use crate::models::user::{self, CreateUser};
use axum::extract::State;
use axum::http::StatusCode;
use serde::Deserialize;
use validator::Validate;

#[derive(Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
pub struct RegisterUser {
#[validate(length(min = 2, max = 32))]
username: String,
#[validate(email)]
email_address: String,
#[validate(length(min = 6, max = 72))]
password: String,
#[validate(must_match(other = "password", message = "Password"))]
repeat_password: String,
}

pub async fn register(
State(mut state): State<AppState>,
ValidatedJson(details): ValidatedJson<RegisterUser>,
) -> Result<StatusCode, HandlerError> {
if user::name_exists(&state, &details.username).await? {
return Err(HandlerError::UsernameTaken);
}
if user::email_exists(&state, &details.email_address).await? {
return Err(HandlerError::EmailTaken);
}

user::create(
&mut state,
CreateUser {
username: &details.username,
email_address: &details.email_address,
password: &details.password,
},
)
.await?;

Ok(StatusCode::CREATED)
}
Loading

0 comments on commit 253377c

Please sign in to comment.