Skip to content

Commit

Permalink
backend/fix: Added user entity in auth response
Browse files Browse the repository at this point in the history
  • Loading branch information
Vignesh-772 committed Apr 30, 2024
1 parent e4a8552 commit a52504c
Show file tree
Hide file tree
Showing 23 changed files with 98 additions and 94 deletions.
7 changes: 2 additions & 5 deletions .github/workflows/backend.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
name: Rust

on:
pull_request:
paths:
- 'Backend/**'
on: [pull_request]

env:
CARGO_TERM_COLOR: always
Expand All @@ -13,7 +10,7 @@ permissions:

jobs:
build:
runs-on: self-hosted
runs-on: ubuntu-latest
defaults:
run:
working-directory: Backend/
Expand Down
2 changes: 1 addition & 1 deletion Backend/diesel.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ file = "src/db/schema.rs"
schema = "school_trips"

[migrations_directory]
dir = "../../migrations"
dir = "./migrations"
5 changes: 1 addition & 4 deletions Backend/src/db/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,5 @@ pub mod school_trips {
}
}

diesel::allow_tables_to_appear_in_same_query!(
auth,
users,
);
diesel::allow_tables_to_appear_in_same_query!(auth, users,);
}
25 changes: 12 additions & 13 deletions Backend/src/handlers/auth/auth_verify.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::storage::models;
use crate::storage::models::auth::{Auth, VerifyAuthResponse};
use crate::storage::models::geometry::ServiceabilityRequest;
use crate::storage::models::user::User;
use crate::storage::result::QueryResult;
use crate::tools::contants::ONEWEEK;
Expand All @@ -10,7 +9,6 @@ use crate::ServerState;
use actix_web::web::{self};
use actix_web::HttpResponse;


pub fn handle_verify_auth(
state: web::Data<ServerState>,
req: web::Json<models::auth::VerifyAuthRequest>,
Expand All @@ -36,7 +34,12 @@ pub fn handle_verify_auth(
..register_user
};
response = VerifyAuthResponse {
session_token : SessionToken::new(upadated_user.id.clone(), get_exipry_from_minutes(ONEWEEK).timestamp()).encode(state.config.jwt_secret.clone())
session_token: SessionToken::new(
upadated_user.id.clone(),
get_exipry_from_minutes(ONEWEEK).timestamp(),
)
.encode(state.config.jwt_secret.clone()),
user: upadated_user.to_owned()
};
upadated_user.update(&state.data.pool);
}
Expand All @@ -50,7 +53,12 @@ pub fn handle_verify_auth(
role: auth.role.to_owned(),
};
response = VerifyAuthResponse {
session_token : SessionToken::new(user.id.clone(), get_exipry_from_minutes(ONEWEEK).timestamp()).encode(state.config.jwt_secret.clone())
session_token: SessionToken::new(
user.id.clone(),
get_exipry_from_minutes(ONEWEEK).timestamp(),
)
.encode(state.config.jwt_secret.clone()),
user: user.to_owned()
};
user.insert(&state.data.pool);
}
Expand All @@ -70,12 +78,3 @@ pub fn handle_verify_auth(
_ => HttpResponse::InternalServerError().body("INTERNAL_ERROR"),
}
}


pub fn origin_serviceability(
state: web::Data<ServerState>,
req: web::Json<ServiceabilityRequest>,
) -> HttpResponse {
// geo::Polygon::
return HttpResponse::InternalServerError().body("INTERNAL_ERROR");
}
2 changes: 1 addition & 1 deletion Backend/src/handlers/auth/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub mod auth;
pub mod auth_verify;
pub mod auth_verify;
2 changes: 1 addition & 1 deletion Backend/src/handlers/geometry/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
pub mod serviceability;
pub mod serviceability;
20 changes: 11 additions & 9 deletions Backend/src/handlers/geometry/serviceability.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
use geo::Contains;

use crate::{storage::models::geometry::ServiceabilityRequest, tools::polygon_utils::geo_json::get_available_shape_files, web, HttpResponse, ServerState};
use crate::{
storage::models::geometry::ServiceabilityRequest,
tools::polygon_utils::geo_json::get_available_shape_files, web, HttpResponse, ServerState,
};
use geo::{coord, Intersects};

pub fn origin_serviceability(
state: web::Data<ServerState>,
_: web::Data<ServerState>,
req: web::Json<ServiceabilityRequest>,
) -> HttpResponse {
let areas = get_available_shape_files();
let mut result = false;
for area in areas {
if (area.get_polygon().contains(&req.point)) {
result = true;
}
return HttpResponse::Ok().json(
area.get_polygon()
.intersects(&coord! {x: req.point.lon, y: req.point.lat}),
);
}
return HttpResponse::Ok().json(result);
return HttpResponse::Ok().json(false);
}
2 changes: 1 addition & 1 deletion Backend/src/handlers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub mod auth;
pub mod error_handler;
pub mod geometry;
pub mod geometry;
2 changes: 1 addition & 1 deletion Backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ mod db;
mod handlers;
mod routes;
mod storage;
mod tools;
mod transformers;
mod types;
mod tools;

#[derive(serde::Deserialize, serde::Serialize)]
pub struct Response {
Expand Down
4 changes: 3 additions & 1 deletion Backend/src/routes/auth.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::{
handlers::auth::{auth::handle_auth, auth_verify::handle_verify_auth}, storage::models, ServerState
handlers::auth::{auth::handle_auth, auth_verify::handle_verify_auth},
storage::models,
ServerState,
};
use actix_web::{post, web, HttpResponse};

Expand Down
2 changes: 1 addition & 1 deletion Backend/src/routes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub mod auth;
pub mod routes;
pub mod serviceability;
pub mod session;
pub mod serviceability;
2 changes: 1 addition & 1 deletion Backend/src/routes/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ pub fn add_all_routes(cfg: &mut web::ServiceConfig) {
.service(super::auth::create_auth)
.service(super::auth::verify_auth)
.service(super::session::verify_session)
.service(super::serviceability::serviceability)
.service(super::serviceability::serviceability),
);
}
13 changes: 9 additions & 4 deletions Backend/src/routes/serviceability.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
use actix_web::{get, http::header::AUTHORIZATION, web, HttpRequest, HttpResponse};
use actix_web::{get, web, HttpResponse};

use crate::{
handlers::geometry::serviceability::origin_serviceability, storage::models, tools::{session_utils::SessionToken, utils::get_token_from_bearer}, types::ServerState
handlers::geometry::serviceability::origin_serviceability,
storage::models,
types::ServerState,
};

#[get("origin/serviceability")]
pub async fn serviceability(state: web::Data<ServerState>, req: web::Json<models::geometry::ServiceabilityRequest>,) -> HttpResponse {
return origin_serviceability(state,req);
pub async fn serviceability(
state: web::Data<ServerState>,
req: web::Json<models::geometry::ServiceabilityRequest>,
) -> HttpResponse {
return origin_serviceability(state, req);
}
3 changes: 2 additions & 1 deletion Backend/src/storage/models/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use chrono::NaiveDateTime;
use diesel::prelude::*;
use serde::{Deserialize, Serialize};

use super::user::Role;
use super::user::{Role, User};

/// Auth table sturct
#[derive(AsChangeset, Queryable, Insertable)]
Expand Down Expand Up @@ -41,6 +41,7 @@ pub struct VerifyAuthRequest {
#[derive(Deserialize, Serialize)]
pub struct VerifyAuthResponse {
pub session_token: String,
pub user: User,
}
// TODO Add User creation
#[derive(Deserialize, Serialize)]
Expand Down
14 changes: 8 additions & 6 deletions Backend/src/storage/models/geometry.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
use diesel::sql_types::Bool;
use geo::{coord, Coord};
use serde::{Deserialize, Serialize};


#[derive(Deserialize, Serialize)]
pub struct ServiceabilityRequest {
pub point: LatLong,
}

#[derive(Deserialize, Serialize)]
pub struct ServiceabilityRequest {
pub point : Coord,
pub struct LatLong {
pub lat: f64,
pub lon: f64,
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ServiceabilityResponse {
pub serviceable: bool,
}
}
2 changes: 1 addition & 1 deletion Backend/src/storage/models/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub mod auth;
pub mod geometry;
pub mod user;
pub mod geometry;
9 changes: 6 additions & 3 deletions Backend/src/storage/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use std::io::Write;

use crate::db::{
self,
schema::school_trips::{sql_types::RoleType, users::{self}},
schema::school_trips::{
sql_types::RoleType,
users::{self},
},
};
use chrono::NaiveDateTime;
use diesel::{
Expand Down Expand Up @@ -42,7 +45,7 @@ impl FromSql<RoleType, Pg> for Role {
}

/// User table sturct
#[derive(AsChangeset, Queryable, Insertable, Selectable)]
#[derive(AsChangeset, Queryable, Insertable, Selectable, Serialize, Deserialize, Clone)]
#[diesel(table_name = db::schema::school_trips::users)]
pub struct User {
pub name: Option<String>,
Expand All @@ -59,4 +62,4 @@ impl Selectable<Pg> for Role {
fn construct_selection() -> Self::SelectExpression {
users::role
}
}
}
3 changes: 1 addition & 2 deletions Backend/src/tools/contants.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

pub const ONEWEEK: i64 = 7 * 24 * 60;

pub const SHAPE_FILE_PATH: &str = "./shape_files";
pub const SHAPE_FILE_PATH: &str = "./shape_files";
6 changes: 3 additions & 3 deletions Backend/src/tools/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub mod utils;
pub mod contants;
pub mod session_utils;
pub mod polygon_utils;
pub mod types;
pub mod session_utils;
pub mod types;
pub mod utils;
11 changes: 8 additions & 3 deletions Backend/src/tools/polygon_utils/geo_json.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use log::{error, info};
use log::error;
use std::{fs, str::FromStr};

use crate::tools::{contants::SHAPE_FILE_PATH, types::MultiPolygonWithName, utils::get_file_name_without_extension};
use crate::tools::{
contants::SHAPE_FILE_PATH, types::MultiPolygonWithName, utils::get_file_name_without_extension,
};

pub fn get_available_shape_files() -> Vec<MultiPolygonWithName> {
let mut shape_files = Vec::new();
Expand All @@ -15,7 +17,10 @@ pub fn get_available_shape_files() -> Vec<MultiPolygonWithName> {
let multi_polygon: geo::MultiPolygon =
TryFrom::try_from(geojson.to_owned()).unwrap();

shape_files.push(MultiPolygonWithName::new(get_file_name_without_extension(file_name), multi_polygon))
shape_files.push(MultiPolygonWithName::new(
get_file_name_without_extension(file_name),
multi_polygon,
))
}
Err(err) => {
error!("Error while parsing geo json string {}", err);
Expand Down
32 changes: 14 additions & 18 deletions Backend/src/tools/session_utils.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
use std::collections::HashSet;

use jsonwebtoken::{DecodingKey, EncodingKey, Header, TokenData, Validation};
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};

use super::utils::get_current_time;




#[derive(Serialize, Deserialize)]
pub struct SessionToken {
exp : i64,
exp: i64,
iat: i64,
id : String
id: String,
}

impl SessionToken {
pub fn encode(&self, secret : String) -> String {
pub fn encode(&self, secret: String) -> String {
jsonwebtoken::encode(
&Header::default(),
&self,
Expand All @@ -25,22 +20,23 @@ impl SessionToken {
.unwrap()
}

pub fn decode(token: String, secret : String) -> Option<SessionToken> {
pub fn decode(token: String, secret: String) -> Option<SessionToken> {
match jsonwebtoken::decode::<SessionToken>(
&token,
&DecodingKey::from_secret(secret.to_owned().as_bytes()),
&Validation::default()
).ok() {
&Validation::default(),
)
.ok()
{
Some(token_data) => Some(token_data.claims),
None => None
None => None,
}
}
pub fn new(id:String, exp:i64) -> Self {
}
pub fn new(id: String, exp: i64) -> Self {
SessionToken {
id,
exp,
iat : get_current_time().timestamp()
iat: get_current_time().timestamp(),
}
}

}
}
Loading

0 comments on commit a52504c

Please sign in to comment.