Skip to content

Commit

Permalink
Merge pull request #19 from 8shaws/redi
Browse files Browse the repository at this point in the history
fix: /login route
  • Loading branch information
shawakash authored Jul 27, 2024
2 parents 96f2b97 + d81ffd9 commit fe3b80e
Show file tree
Hide file tree
Showing 14 changed files with 165 additions and 23 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
DATABASE_URL=postgres://postgres:password@localhost:5432/your_db_name
JWT_SECRET= use openssl rand -base64 32 to generate a secret
REDIS_URL=redis://localhost:6379
105 changes: 105 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions crates/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ rand = "0.8.5"
base64 = "0.22.1"
password-hash = "0.5.0"
tokio = "1.39.1"
redis = "0.26.0"
deadpool-redis = "0.15.1"
3 changes: 0 additions & 3 deletions crates/api/migrations/2024-07-26-124549_hash_pass/down.sql

This file was deleted.

3 changes: 0 additions & 3 deletions crates/api/migrations/2024-07-26-124549_hash_pass/up.sql

This file was deleted.

4 changes: 4 additions & 0 deletions crates/api/migrations/2024-07-27-100150_hash_pass/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-- This file should undo anything in `up.sql`
ALTER TABLE "users" DROP COLUMN "hash_password";
ALTER TABLE "users" ADD COLUMN "password" VARCHAR(255) NOT NULL;

4 changes: 4 additions & 0 deletions crates/api/migrations/2024-07-27-100150_hash_pass/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-- Your SQL goes here
ALTER TABLE "users" DROP COLUMN "password";
ALTER TABLE "users" ADD COLUMN "hash_password" VARCHAR(255) NOT NULL;

16 changes: 8 additions & 8 deletions crates/api/src/db/user_db_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,29 +36,29 @@ pub fn insert_user(
pub fn get_user_by_email(
con: &mut PgConnection,
form_email: &str,
) -> Result<Option<Vec<models::User>>, DbError> {
) -> Result<Option<models::User>, DbError> {
use crate::schema::users::dsl::*;

let user = users
let user_result = users
.filter(email.eq(form_email))
.select(User::as_select())
.load::<User>(con)
.get_result::<User>(con)
.optional()?;

Ok(user)
Ok(user_result)
}

pub fn get_user_by_contact(
con: &mut PgConnection,
contact: &str,
) -> Result<Option<Vec<models::User>>, DbError> {
) -> Result<Option<models::User>, DbError> {
use crate::schema::users::dsl::*;

let user = users
let user_result = users
.filter(contact_number.eq(contact))
.select(User::as_select())
.load::<User>(con)
.get_result::<User>(con)
.optional()?;

Ok(user)
Ok(user_result)
}
11 changes: 9 additions & 2 deletions crates/api/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::time::SystemTime;
mod auth;
mod db;
mod models;
mod redis;
mod route;
mod schema;

Expand Down Expand Up @@ -40,13 +41,19 @@ async fn main() -> std::io::Result<()> {
.filter_level(log::LevelFilter::Info)
.init();

let pool = initialize_db_pool();
let dp_pool = initialize_db_pool();
let redis_pool = redis::initialize_redis_pool();

let app_state = models::AppState {
db_pool: dp_pool,
redis_pool: redis_pool,
};

println!("{:?}: Api Server is running on port: {}", *START_TIME, 8080);

HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
.app_data(web::Data::new(app_state.clone()))
.wrap(middleware::Logger::default())
.configure(user_config)
.route("/", web::get().to(root))
Expand Down
7 changes: 7 additions & 0 deletions crates/api/src/models.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use chrono::NaiveDateTime;
use deadpool_redis::Pool as RedisPool;
use diesel::{prelude::*, query_builder::QueryId};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
Expand Down Expand Up @@ -41,3 +42,9 @@ pub struct LoginUser {
pub login_field: String,
pub password: String,
}

#[derive(Debug, Clone)]
pub struct AppState {
pub db_pool: crate::db::DbPool,
pub redis_pool: RedisPool,
}
9 changes: 9 additions & 0 deletions crates/api/src/redis.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use deadpool_redis::{Config, Pool as RedisPool, Runtime};
use std::env;

pub fn initialize_redis_pool() -> RedisPool {
let redis_url = env::var("REDIS_URL").expect("REDIS_URL must be set");
let cfg = Config::from_url(redis_url);
let pool = cfg.create_pool(Some(Runtime::Tokio1));
pool.expect("Failed to create Redis Pool")
}
14 changes: 7 additions & 7 deletions crates/api/src/route/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ use serde_json::json;

use crate::auth;
use crate::auth::middleware::ExtractClientId;
use crate::db::{self, DbPool};
use crate::db::{self};
use crate::models::*;

#[post("/login")]
async fn login(pool: web::Data<DbPool>, form: web::Json<LoginUser>) -> Result<impl Responder> {
async fn login(state: web::Data<AppState>, form: web::Json<LoginUser>) -> Result<impl Responder> {
let form = form.into_inner();
let user = web::block(move || {
let mut con = pool.get()?;
let mut con = state.db_pool.get()?;

let db_user = if form.login_field.contains("@") {
db::user_db_fn::get_user_by_email(&mut con, &form.login_field)
Expand All @@ -25,8 +25,8 @@ async fn login(pool: web::Data<DbPool>, form: web::Json<LoginUser>) -> Result<im
Ok(match user {
Some(user) => {
// Check if password is correct
if auth::utils::verify_password(&form.password, &user[0].hash_password) {
let token = match auth::utils::generate_token(&user[0].id.to_string()) {
if auth::utils::verify_password(&form.password, &user.hash_password) {
let token = match auth::utils::generate_token(&user.id.to_string()) {
Ok(t) => t,
Err(_) => {
return Err(error::ErrorInternalServerError("Error generating token"))
Expand Down Expand Up @@ -56,11 +56,11 @@ async fn login(pool: web::Data<DbPool>, form: web::Json<LoginUser>) -> Result<im

#[post("/register")]
async fn register(
pool: web::Data<DbPool>,
state: web::Data<AppState>,
form: web::Json<RegisterUser>,
) -> Result<impl Responder> {
let created_user = web::block(move || {
let mut conn = pool.get()?;
let mut conn = state.db_pool.get()?;
db::user_db_fn::insert_user(&mut conn, form.into_inner())
})
.await?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ services:
interval: 15s
timeout: 5s

redis:
image: redis:latest
container_name: redis
networks:
- app-network
restart: always
ports:
- 6379:6379

networks:
app-network:
driver: bridge
Expand Down
File renamed without changes.

0 comments on commit fe3b80e

Please sign in to comment.