Compare commits

...

10 Commits

Author SHA1 Message Date
Franklin bf0030b7f1 Updated user service to use u32 instead of i32 and updated the dev-dtos lib 2023-03-05 09:08:51 -04:00
Franklin df955adc7f Changed it back whoops 2023-01-07 19:40:39 -04:00
Franklin dccd0d78ca changed incorrect dep name 2023-01-07 19:39:23 -04:00
Franklin f65e218be5 Added token to repo deps 2023-01-07 19:38:17 -04:00
Franklin 62dd99402c Updated gitea repos to github 2023-01-07 19:35:07 -04:00
Franklin 18b94e9e19 Added logger 2022-08-30 13:32:22 -04:00
Franklin 54272767f5 Added simple todo 2022-08-26 14:21:20 -04:00
Franklin 2f8038f740 Fixed internal server error caused by database exploding 2022-08-26 14:18:45 -04:00
Franklin 2b9b0fe83e fixed user service flaws 2022-08-26 13:58:47 -04:00
franklinblanco 0574c59006 Removed unneccesary result from main func 2022-08-12 20:14:07 -04:00
26 changed files with 154 additions and 196 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@ -2,7 +2,6 @@
name = "user-svc-actix"
version = "0.1.0"
edition = "2021"
build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
@ -15,8 +14,7 @@ chrono = { version = "0.4", features = [ "serde" ] }
ring = "0.16.20"
data-encoding = "2.3.2"
futures-util = "0.3"
actix-web-utils = "0.2"
#log = { version = "0.4", features = ["serde"] }
[build-dependencies]
dotenv = "0.15.0"
sqlx = { version = "0.6.0", features = [ "runtime-tokio-rustls", "mysql", "chrono" ] }
tokio = { version = "1", features = ["full"] }
dev-dtos = { git = "https://git.franklinblanco.dev/franklinblanco/dev-dtos.git" }

View File

@ -44,7 +44,11 @@ To build for release on current platform
cargo build --release
```
To build for release on x86-64 linux
To build for release on x86-64 linux From m1 macs
``` bash
brew tap SergioBenitez/osxct
brew install x86_64-unknown-linux-gnu
```
```bash
cargo build --release --target x86_64-unknown-linux-gnu

View File

@ -1,28 +0,0 @@
extern crate dotenv;
use std::{env, collections::HashMap};
use sqlx::Connection;
use dotenv::dotenv;
#[tokio::main]
async fn main(){
println!("cargo:rerun-if-changed=migrations");
dotenv().ok();
let mut dotenv_vars: HashMap<String, String> = HashMap::new();
for (key, val) in env::vars() {
dotenv_vars.insert(key, val);
}
let db_url = match dotenv_vars.get("DATABASE_URL") {
Some(var) => {var},
None => {panic!("DATABASE_URL env var not found, set it!")}
};
let mut conn = match sqlx::MySqlConnection::connect(&db_url).await {
Ok(res) => {res},
Err(e) => {panic!("{}", e)}
};
match sqlx::migrate!("./migrations").run(&mut conn).await {
Ok(()) => {println!("{}", "Successfully ran migrations.")},
Err(error) => {panic!("{error}")}
};
}

View File

@ -1,9 +1,10 @@
CREATE TABLE IF NOT EXISTS user (
id INT AUTO_INCREMENT PRIMARY KEY,
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
time_created DATETIME,
last_updated DATETIME,
app VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
credential VARCHAR(255) NOT NULL,
credential_type VARCHAR(20) NOT NULL,
name VARCHAR(255) NOT NULL,
password TEXT NOT NULL,
salt TEXT NOT NULL

View File

@ -1 +0,0 @@
-- Add migration script here

View File

@ -1,6 +1,6 @@
CREATE TABLE IF NOT EXISTS token (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED NOT NULL,
time_created DATETIME,
last_updated DATETIME,
auth_token TEXT NOT NULL,

View File

@ -1,8 +0,0 @@
CREATE TABLE IF NOT EXISTS token (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
time_created TIMESTAMP NOT NULL,
last_updated TIMESTAMP NOT NULL,
auth_token TEXT NOT NULL,
refresh_token TEXT NOT NULL
)

View File

@ -1,9 +0,0 @@
CREATE TABLE IF NOT EXISTS user (
id INT AUTO_INCREMENT PRIMARY KEY,
time_created TIMESTAMP NOT NULL,
last_updated TIMESTAMP NOT NULL,
email VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
password TEXT NOT NULL,
salt VARCHAR(255) NOT NULL
)

View File

@ -0,0 +1,5 @@
SELECT *
FROM user
WHERE user.credential = ? AND
user.credential_type = ? AND
user.app = ?

View File

@ -1,4 +0,0 @@
SELECT *
FROM user
WHERE user.email = ? AND
user.app = ?

View File

@ -1,3 +1,3 @@
INSERT INTO user
(id, time_created, last_updated, app, email, name, password, salt) values
(NULL, NOW(), NOW(), ?, ?, ?, ?, ?)
(id, time_created, last_updated, app, credential, credential_type, name, password, salt) values
(NULL, NOW(), NOW(), ?, ?, ?, ?, ?, ?)

View File

@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::{collections::HashMap, str::FromStr};
use sqlx::{MySqlPool};
//use log::{LevelFilter, info};
use sqlx::{MySqlPool, mysql::{MySqlConnectOptions, MySqlPoolOptions}};
pub async fn start_database_connection(env_vars: &HashMap<String, String>) -> Result<MySqlPool, sqlx::Error>{
let db_url = match env_vars.get("DATABASE_URL") {
@ -8,11 +9,14 @@ pub async fn start_database_connection(env_vars: &HashMap<String, String>) -> Re
None => panic!("DATABASE_URL env var not found")
};
let formatted_db_url = &db_url;
sqlx::MySqlPool::connect(&formatted_db_url).await
let options = MySqlConnectOptions::from_str(formatted_db_url)?;
//options.log_slow_statements(LevelFilter::Warn, Duration::from_secs(1))
//.log_statements(LevelFilter::Trace);
MySqlPoolOptions::new().connect_with(options).await
}
pub async fn run_all_migrations(conn: &MySqlPool){
match sqlx::migrate!("./migrations").run(conn).await {
Ok(()) => {println!("{}", "Successfully ran migrations.")},
Ok(()) => {println!("Successfully ran migrations.")},
Err(error) => {panic!("{error}")}
}
}

View File

@ -1,13 +1,11 @@
use dev_dtos::domain::user::token::{AUTH_TOKEN_EXPIRATION_TIME_IN_DAYS, Token, REFRESH_TOKEN_EXPIRATION_TIME_IN_DAYS};
use sqlx::MySqlPool;
use sqlx::{mysql::MySqlQueryResult};
use crate::r#do::token::Token;
use crate::r#do::token::{AUTH_TOKEN_EXPIRATION_TIME_IN_DAYS, REFRESH_TOKEN_EXPIRATION_TIME_IN_DAYS};
pub async fn insert_token(conn: &MySqlPool, token: &Token) -> Result<MySqlQueryResult, sqlx::Error> {
sqlx::query_file!("sql/schema/token/insert.sql", token.user_id, token.auth_token, token.refresh_token).execute(conn).await
}
pub async fn get_tokens_with_user_id(conn: &MySqlPool, user_id: &i32) -> Result<Vec<Token>, sqlx::Error> {
pub async fn get_tokens_with_user_id(conn: &MySqlPool, user_id: &u32) -> Result<Vec<Token>, sqlx::Error> {
sqlx::query_file_as!(Token, "sql/schema/token/find_with_user_id.sql", user_id).fetch_all(conn).await
}
pub async fn update_token_with_id(conn: &MySqlPool, token: &Token ) -> Result<MySqlQueryResult, sqlx::Error> {

View File

@ -1,15 +1,14 @@
use dev_dtos::domain::user::user::User;
use sqlx::{mysql::MySqlQueryResult, MySqlPool};
use crate::r#do::user::User;
pub async fn insert_user(conn: &MySqlPool, user_to_insert: &User) -> Result<MySqlQueryResult, sqlx::Error>{
sqlx::query_file!("sql/schema/user/insert.sql",
user_to_insert.app, user_to_insert.email, user_to_insert.name, user_to_insert.password, user_to_insert.salt)
user_to_insert.app, user_to_insert.credential, user_to_insert.credential_type, user_to_insert.name, user_to_insert.password, user_to_insert.salt)
.execute(conn).await
}
pub async fn find_user_by_email(conn: &MySqlPool, email: &String, app: &String) -> Result<User, sqlx::Error>{
sqlx::query_file_as!(User, "sql/schema/user/find_with_email.sql", email, app).fetch_one(conn).await
pub async fn find_user_by_credential(conn: &MySqlPool, credential: &String, credential_type: &String, app: &String) -> Result<User, sqlx::Error>{
sqlx::query_file_as!(User, "sql/schema/user/find_with_credential.sql", credential, credential_type, app).fetch_one(conn).await
}
pub async fn find_user_by_id(conn: &MySqlPool, id: &i32) -> Result<User, sqlx::Error> {
pub async fn find_user_by_id(conn: &MySqlPool, id: &u32) -> Result<User, sqlx::Error> {
sqlx::query_file_as!(User, "sql/schema/user/find_with_id.sql", id).fetch_one(conn).await
}

67
src/do/loggers.rs Normal file
View File

@ -0,0 +1,67 @@
use std::{future::{ready, Ready}, rc::Rc, io::Read};
use actix_web::{
dev::{self, Service, ServiceRequest, ServiceResponse, Transform},
Error, HttpMessage, web::BytesMut,
};
use futures_util::{future::LocalBoxFuture, StreamExt, Stream};
// There are two steps in middleware processing.
// 1. Middleware initialization, middleware factory gets called with
// next service in chain as parameter.
// 2. Middleware's call method gets called with normal request.
pub struct BodyLogger;
// Middleware factory is `Transform` trait from actix-service crate
// `S` - type of the next service
// `B` - type of response's body
impl<S: 'static, B> Transform<S, ServiceRequest> for BodyLogger
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type InitError = ();
type Transform = BodyLoggerMiddleware<S>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(BodyLoggerMiddleware { service: Rc::new(service) }))
}
}
pub struct BodyLoggerMiddleware<S> {
service: Rc<S>,
}
impl<S, B> Service<ServiceRequest> for BodyLoggerMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
dev::forward_ready!(service);
fn call(&self, mut req: ServiceRequest) -> Self::Future {
let svc = self.service.clone();
Box::pin(async move {
let mut body = BytesMut::new();
let mut stream = req.take_payload();
while let Some(chunk) = stream.next().await {
body.extend_from_slice(&chunk?);
}
println!("request body: {body:?}");
let res = svc.call(req).await?;
println!("response: {:?}", res.headers());
Ok(res)
})
}
}

View File

@ -1,3 +1,2 @@
pub mod shared_state;
pub mod user;
pub mod token;
//pub mod loggers;

View File

@ -1,31 +0,0 @@
use chrono::NaiveDateTime;
use serde::{Serialize, Deserialize};
pub const AUTH_TOKEN_EXPIRATION_TIME_IN_DAYS:i32 = 1;
pub const REFRESH_TOKEN_EXPIRATION_TIME_IN_DAYS: i32 = 20;
#[derive(Serialize, Deserialize)]
pub struct Token {
#[serde(skip_serializing)]
pub id: i32,
pub user_id: i32,
#[serde(skip_serializing)]
pub time_created: Option<NaiveDateTime>,
#[serde(skip_serializing)]
pub last_updated: Option<NaiveDateTime>,
pub auth_token: String,
pub refresh_token: String
}
impl Token{
pub fn new(user_id: i32, auth_token: String, refresh_token: String) -> Token{
Token {
id: 0,
user_id,
time_created: None,
last_updated: None,
auth_token,
refresh_token
}
}
}

View File

@ -1,42 +0,0 @@
use chrono::{NaiveDateTime};
use serde::{Serialize, Deserialize};
use crate::dto::user_dtos::UserForCreationDto;
#[derive(Serialize, Deserialize, Debug)]
pub struct User{
pub id: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub time_created: Option<NaiveDateTime>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_updated: Option<NaiveDateTime>,
pub app: String,
pub email: String,
pub name: String,
#[serde(skip_serializing)]
pub password: String,
#[serde(skip_serializing)]
pub salt: String
}
impl User {
pub fn _new() -> User {
User { id: 0,
time_created: None, // This will be automatically generated from the database
last_updated: None, // This will be automatically generated from the database
app: "".to_string(),
email: "".to_string(),
name:"".to_string(),
password:"".to_string(),
salt: "".to_string() }
}
pub fn new_for_creation(incoming_user: &UserForCreationDto) -> User{
User { id: 0,
time_created: None, // This will be automatically generated from the database
last_updated: None, // This will be automatically generated from the database
app: incoming_user.app.to_string(),
email: incoming_user.email.to_string(),
name: incoming_user.name.to_string(),
password: incoming_user.password.to_string(),
salt: "".to_string() }
}
}

View File

@ -1,3 +1,2 @@
pub mod user_dtos;
pub mod message_resources_dtos;
pub mod hash_dtos;

View File

@ -1,21 +0,0 @@
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct UserForCreationDto{
pub app: String,
pub email: String,
pub password: String,
pub name: String
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UserForLoginDto{
pub app: String,
pub email: String,
pub password: String
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UserForAuthenticationDto{
pub app: String,
pub email: String,
pub token: String
}

View File

@ -4,6 +4,7 @@ mod routes; mod service;
mod util; mod dto;
mod validation; mod resources;
//use actix_web_utils::utils::logger_util::{self};
use r#do::shared_state::SharedStateObj;
use util::env_util;
use routes::main_router::{start_all_routes, after_startup_fn};
@ -11,7 +12,9 @@ use dao::{main_dao::{self, run_all_migrations}};
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
async fn main(){
//logger_util::init_logger_custom(2).expect("LOGGER FAILED TO LOAD");
// Retrieve env variables and send to services that need them.
let env_vars = env_util::get_dot_env_map();
@ -29,6 +32,6 @@ async fn main() -> Result<(), std::io::Error> {
let shared_state_obj = SharedStateObj {db_conn, env_vars };
// Pass shared state to server and start it
start_all_routes(&after_startup_fn, shared_state_obj).await
start_all_routes(&after_startup_fn, shared_state_obj).await.unwrap();
}

View File

@ -3,6 +3,8 @@
pub const ERROR_INVALID_EMAIL: (&str, &str) = ("ERROR.INVALID_EMAIL", "Invalid email. Needs to be at least 4 characters, at most 254 and correctly formatted.");
pub const ERROR_INVALID_PHONE_NUMBER: (&str, &str) = ("ERROR.INVALID_PHONE_NUMBER", "Invalid Phone number. Needs to be 10 characters.");
pub const ERROR_INVALID_NAME: (&str, &str) = ("ERROR.INVALID_NAME", "Invalid name. Names should have at least 4 characters in length and at most 254.");
pub const ERROR_INVALID_PASSWORD: (&str, &str) = ("ERROR.INVALID_PASSWORD", "Invalid password. Password should have at least 8 characters and at most 128.");

View File

@ -1,11 +1,12 @@
use std::sync::{Mutex, Arc};
use actix_web::{HttpServer, App, web};
use crate::r#do::shared_state::SharedStateObj;
use actix_web::{HttpServer, App, web, middleware::Logger};
use crate::{r#do::shared_state::SharedStateObj};
use super::user_routes;
// This function is to be used in case code is meant to be run after server startup
pub fn after_startup_fn() {
println!("{}", "Started server.");
println!("Started server.")
}
pub async fn start_all_routes(after_startup_fn_call: &dyn Fn(), state: SharedStateObj)
@ -34,6 +35,8 @@ pub async fn start_all_routes(after_startup_fn_call: &dyn Fn(), state: SharedSta
let server_future = HttpServer::new( move || {
App::new()
// Define routes & pass in shared state
//.wrap(loggers::BodyLogger) This is how you add middleware
.wrap(Logger::default())
.app_data(db_conn_state.clone())
.app_data(env_vars_state.clone())
.service(user_routes::create_user)

View File

@ -2,11 +2,10 @@ use std::{sync::{Arc}};
use actix_web::{web::{self, Data}, HttpResponse, post, patch, HttpRequest};
use chrono::{Utc};
use dev_dtos::{dtos::user::user_dtos::{UserForLoginDto, UserForCreationDto}, domain::user::{user::User, token::{Token, AUTH_TOKEN_EXPIRATION_TIME_IN_DAYS, REFRESH_TOKEN_EXPIRATION_TIME_IN_DAYS}}};
use sqlx::{MySqlPool};
use crate::{r#do::user::User, dao::{user_dao::{insert_user, find_user_by_email, find_user_by_id}, token_dao::{insert_token, self, update_token_with_id}}, dto::{user_dtos::{UserForCreationDto, UserForLoginDto}, message_resources_dtos::MessageResourceDto}, validation::user_validator, util::hasher::{self, generate_multiple_random_token_with_rng}, r#do::token::Token, resources::error_messages::{ERROR_USER_ALREADY_EXISTS, ERROR_USER_DOES_NOT_EXIST, ERROR_PASSWORD_INCORRECT, ERROR_INVALID_TOKEN, ERROR_MISSING_TOKEN, ERROR_INCORRECT_TOKEN, ERROR_EXPIRED_TOKEN, ERROR_CREATING_TOKEN}, r#do::token::AUTH_TOKEN_EXPIRATION_TIME_IN_DAYS, r#do::token::REFRESH_TOKEN_EXPIRATION_TIME_IN_DAYS};
use crate::{dto::message_resources_dtos::MessageResourceDto, resources::error_messages::{ERROR_USER_ALREADY_EXISTS, ERROR_USER_DOES_NOT_EXIST, ERROR_INCORRECT_TOKEN, ERROR_INVALID_TOKEN, ERROR_MISSING_TOKEN, ERROR_EXPIRED_TOKEN, ERROR_CREATING_TOKEN, ERROR_PASSWORD_INCORRECT}, dao::{user_dao::{find_user_by_credential, insert_user, find_user_by_id}, token_dao::{insert_token, update_token_with_id, self}}, validation::user_validator, util::hasher::{self, generate_multiple_random_token_with_rng}};
#[post("/user")]
pub async fn create_user(incoming_user: web::Json<UserForCreationDto>, db_conn: Data<Arc<MySqlPool>>) -> HttpResponse {
@ -24,7 +23,7 @@ pub async fn create_user(incoming_user: web::Json<UserForCreationDto>, db_conn:
user_validator::validate_user_for_creation(incoming_user_obj, &mut message_resources);
// Find if user exists
match find_user_by_email(&db_conn, &user_to_insert.email, &user_to_insert.app).await{
match find_user_by_credential(&db_conn, &user_to_insert.credential, &user_to_insert.credential_type, &user_to_insert.app).await{
Ok(_usr) => {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_USER_ALREADY_EXISTS));
return HttpResponse::BadRequest().json(web::Json(message_resources));
@ -43,7 +42,7 @@ pub async fn create_user(incoming_user: web::Json<UserForCreationDto>, db_conn:
// Insert user in DB
match insert_user(&db_conn, &user_to_insert).await{
Ok(resultrs) => {
user_to_insert.id = resultrs.last_insert_id() as i32;
user_to_insert.id = resultrs.last_insert_id() as u32;
},
Err(error) => {
println!("Error while inserting user in database from create_user method. Log: {}", error);
@ -60,7 +59,7 @@ pub async fn create_user(incoming_user: web::Json<UserForCreationDto>, db_conn:
// Insert token in DB
match insert_token(&db_conn, &token_to_insert).await{
Ok(resultrs) => {token_to_insert.id = resultrs.last_insert_id() as i32},
Ok(resultrs) => {token_to_insert.id = resultrs.last_insert_id() as u32},
Err(_e) => {return HttpResponse::InternalServerError().finish()}
}
@ -82,7 +81,7 @@ pub async fn authenticate_user_with_password(incoming_user: web::Json<UserForLog
if message_resources.len() > 0 { return HttpResponse::BadRequest().json(web::Json(message_resources)); }
// If user exists get it, if it doesn't blow up to the client
let persisted_user = match find_user_by_email(&db_conn, &incoming_user_obj.email, &incoming_user_obj.app).await {
let persisted_user = match find_user_by_credential(&db_conn, &incoming_user_obj.credential, &incoming_user_obj.credential_type.to_string(), &incoming_user_obj.app).await {
Ok(rs) => {rs},
Err(_) => {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_USER_DOES_NOT_EXIST));
@ -114,7 +113,7 @@ pub async fn authenticate_user_with_password(incoming_user: web::Json<UserForLog
// Insert token in DB
match insert_token(&db_conn, &token_to_insert).await{
Ok(resultrs) => {token_to_insert.id = resultrs.last_insert_id() as i32},
Ok(resultrs) => {token_to_insert.id = resultrs.last_insert_id() as u32},
Err(_) => {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_CREATING_TOKEN));
return HttpResponse::InternalServerError().json(message_resources)
@ -127,7 +126,7 @@ pub async fn authenticate_user_with_password(incoming_user: web::Json<UserForLog
#[post("/user/auth/token/{user_id}")]
pub async fn authenticate_user_with_auth_token(request: HttpRequest, user_id: web::Path<i32>, db_conn: Data<Arc<MySqlPool>>) -> HttpResponse{
pub async fn authenticate_user_with_auth_token(request: HttpRequest, user_id: web::Path<u32>, db_conn: Data<Arc<MySqlPool>>) -> HttpResponse{
let mut message_resources: Vec<MessageResourceDto> = Vec::new();
let headers = request.headers();
let auth_token = match headers.get("auth-token") {
@ -182,7 +181,7 @@ pub async fn authenticate_user_with_auth_token(request: HttpRequest, user_id: we
#[patch("/user/refresh/{user_id}")]
pub async fn refresh_auth_token(request: HttpRequest, user_id: web::Path<i32>, db_conn: Data<Arc<MySqlPool>>) -> HttpResponse{
pub async fn refresh_auth_token(request: HttpRequest, user_id: web::Path<u32>, db_conn: Data<Arc<MySqlPool>>) -> HttpResponse{
let mut message_resources: Vec<MessageResourceDto> = Vec::new();
let headers = request.headers();
let refresh_token = match headers.get("refresh-token") {

View File

@ -1,14 +1,20 @@
use crate::{
dto::{ user_dtos::{UserForCreationDto, UserForLoginDto}, message_resources_dtos::MessageResourceDto },
resources::{ variable_lengths::*, error_messages::* }
};
use dev_dtos::{dtos::user::user_dtos::{UserForCreationDto, UserForLoginDto}, domain::user::credential_type::CredentialType};
use crate::{resources::{variable_lengths::{MAX_EMAIL_LENGTH, MIN_EMAIL_LENGTH, MIN_NAME_LENGTH, MAX_NAME_LENGTH, MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH}, error_messages::{ERROR_INVALID_NAME, ERROR_INVALID_EMAIL, ERROR_INVALID_PASSWORD, ERROR_INVALID_PHONE_NUMBER}}, dto::message_resources_dtos::MessageResourceDto};
//TODO: Regex validation for emails
fn validate_user_email(email: &String) -> bool {
email.len() >= MIN_EMAIL_LENGTH.into() &&
email.len() <= MAX_EMAIL_LENGTH.into() &&
email.contains('@') &&
email.contains('.')
}
//TODO: Regex validation for phone numbers
fn validate_user_phone_number(email: &String) -> bool {
email.len() >= CredentialType::get_max_length(&CredentialType::PhoneNumber) &&
email.len() <= MAX_EMAIL_LENGTH.into()
}
fn validate_user_name(name: &String) -> bool {
name.len() >= MIN_NAME_LENGTH.into() &&
name.len() <= MAX_NAME_LENGTH.into()
@ -19,9 +25,17 @@ fn validate_user_password(password: &String) -> bool {
}
// User dto SHOULD die here.
pub fn validate_user_for_creation(user: UserForCreationDto, message_resources: &mut Vec<MessageResourceDto>){
if !validate_user_email(&user.email) {
match user.credential_type {
CredentialType::Email =>
if !validate_user_email(&user.credential) {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_INVALID_EMAIL));
},
CredentialType::PhoneNumber =>
if !validate_user_phone_number(&user.credential) {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_INVALID_PHONE_NUMBER));
},
}
if !validate_user_name(&user.name) {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_INVALID_NAME));
}
@ -30,8 +44,15 @@ pub fn validate_user_for_creation(user: UserForCreationDto, message_resources: &
}
}
pub fn validate_user_for_password_authentication(user: &UserForLoginDto, message_resources: &mut Vec<MessageResourceDto>){
if !validate_user_email(&user.email) {
match user.credential_type {
CredentialType::Email =>
if !validate_user_email(&user.credential) {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_INVALID_EMAIL));
},
CredentialType::PhoneNumber =>
if !validate_user_phone_number(&user.credential) {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_INVALID_PHONE_NUMBER));
},
}
if !validate_user_password(&user.password) {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_INVALID_PASSWORD));