Updated user service to use u32 instead of i32 and updated the dev-dtos lib

This commit is contained in:
Franklin 2023-03-05 09:08:51 -04:00
parent df955adc7f
commit bf0030b7f1
10 changed files with 22 additions and 23 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@ -15,6 +15,6 @@ ring = "0.16.20"
data-encoding = "2.3.2" data-encoding = "2.3.2"
futures-util = "0.3" futures-util = "0.3"
actix-web-utils = "0.2" actix-web-utils = "0.2"
log = { version = "0.4", features = ["serde"] } #log = { version = "0.4", features = ["serde"] }
dev-dtos = { git = "https://franklinblanco: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@github.com/franklinblanco/user-svc-dtos-rust.git" } dev-dtos = { git = "https://git.franklinblanco.dev/franklinblanco/dev-dtos.git" }

View File

@ -1,5 +1,5 @@
CREATE TABLE IF NOT EXISTS user ( CREATE TABLE IF NOT EXISTS user (
id INT AUTO_INCREMENT PRIMARY KEY, id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
time_created DATETIME, time_created DATETIME,
last_updated DATETIME, last_updated DATETIME,
app VARCHAR(255) NOT NULL, app VARCHAR(255) NOT NULL,

View File

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

View File

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

View File

@ -5,7 +5,7 @@ use sqlx::{mysql::MySqlQueryResult};
pub async fn insert_token(conn: &MySqlPool, token: &Token) -> Result<MySqlQueryResult, sqlx::Error> { 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 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 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> { pub async fn update_token_with_id(conn: &MySqlPool, token: &Token ) -> Result<MySqlQueryResult, sqlx::Error> {

View File

@ -9,6 +9,6 @@ pub async fn insert_user(conn: &MySqlPool, user_to_insert: &User) -> Result<MySq
pub async fn find_user_by_credential(conn: &MySqlPool, credential: &String, credential_type: &String, app: &String) -> Result<User, sqlx::Error>{ 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 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 sqlx::query_file_as!(User, "sql/schema/user/find_with_id.sql", id).fetch_one(conn).await
} }

View File

@ -4,7 +4,7 @@ mod routes; mod service;
mod util; mod dto; mod util; mod dto;
mod validation; mod resources; mod validation; mod resources;
use actix_web_utils::utils::logger_util::{self}; //use actix_web_utils::utils::logger_util::{self};
use r#do::shared_state::SharedStateObj; use r#do::shared_state::SharedStateObj;
use util::env_util; use util::env_util;
use routes::main_router::{start_all_routes, after_startup_fn}; use routes::main_router::{start_all_routes, after_startup_fn};
@ -14,7 +14,7 @@ use dao::{main_dao::{self, run_all_migrations}};
#[tokio::main] #[tokio::main]
async fn main(){ async fn main(){
logger_util::init_logger_custom(2).expect("LOGGER FAILED TO LOAD"); //logger_util::init_logger_custom(2).expect("LOGGER FAILED TO LOAD");
// Retrieve env variables and send to services that need them. // Retrieve env variables and send to services that need them.
let env_vars = env_util::get_dot_env_map(); let env_vars = env_util::get_dot_env_map();

View File

@ -1,13 +1,12 @@
use std::sync::{Mutex, Arc}; use std::sync::{Mutex, Arc};
use actix_web::{HttpServer, App, web, middleware::Logger}; use actix_web::{HttpServer, App, web, middleware::Logger};
use log::info;
use crate::{r#do::shared_state::SharedStateObj}; use crate::{r#do::shared_state::SharedStateObj};
use super::user_routes; use super::user_routes;
// This function is to be used in case code is meant to be run after server startup // This function is to be used in case code is meant to be run after server startup
pub fn after_startup_fn() { pub fn after_startup_fn() {
info!("Started server.") println!("Started server.")
} }
pub async fn start_all_routes(after_startup_fn_call: &dyn Fn(), state: SharedStateObj) pub async fn start_all_routes(after_startup_fn_call: &dyn Fn(), state: SharedStateObj)

View File

@ -42,7 +42,7 @@ pub async fn create_user(incoming_user: web::Json<UserForCreationDto>, db_conn:
// Insert user in DB // Insert user in DB
match insert_user(&db_conn, &user_to_insert).await{ match insert_user(&db_conn, &user_to_insert).await{
Ok(resultrs) => { Ok(resultrs) => {
user_to_insert.id = resultrs.last_insert_id() as i32; user_to_insert.id = resultrs.last_insert_id() as u32;
}, },
Err(error) => { Err(error) => {
println!("Error while inserting user in database from create_user method. Log: {}", error); println!("Error while inserting user in database from create_user method. Log: {}", error);
@ -59,7 +59,7 @@ pub async fn create_user(incoming_user: web::Json<UserForCreationDto>, db_conn:
// Insert token in DB // Insert token in DB
match insert_token(&db_conn, &token_to_insert).await{ 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()} Err(_e) => {return HttpResponse::InternalServerError().finish()}
} }
@ -113,7 +113,7 @@ pub async fn authenticate_user_with_password(incoming_user: web::Json<UserForLog
// Insert token in DB // Insert token in DB
match insert_token(&db_conn, &token_to_insert).await{ 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(_) => { Err(_) => {
message_resources.push(MessageResourceDto::new_from_error_message(ERROR_CREATING_TOKEN)); message_resources.push(MessageResourceDto::new_from_error_message(ERROR_CREATING_TOKEN));
return HttpResponse::InternalServerError().json(message_resources) return HttpResponse::InternalServerError().json(message_resources)
@ -126,7 +126,7 @@ pub async fn authenticate_user_with_password(incoming_user: web::Json<UserForLog
#[post("/user/auth/token/{user_id}")] #[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 mut message_resources: Vec<MessageResourceDto> = Vec::new();
let headers = request.headers(); let headers = request.headers();
let auth_token = match headers.get("auth-token") { let auth_token = match headers.get("auth-token") {
@ -181,7 +181,7 @@ pub async fn authenticate_user_with_auth_token(request: HttpRequest, user_id: we
#[patch("/user/refresh/{user_id}")] #[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 mut message_resources: Vec<MessageResourceDto> = Vec::new();
let headers = request.headers(); let headers = request.headers();
let refresh_token = match headers.get("refresh-token") { let refresh_token = match headers.get("refresh-token") {