Skip to content

Commit

Permalink
change to sqlx
Browse files Browse the repository at this point in the history
  • Loading branch information
Sxyntheon committed Dec 4, 2024
1 parent 6de9838 commit 893e577
Show file tree
Hide file tree
Showing 28 changed files with 255 additions and 148 deletions.
2 changes: 2 additions & 0 deletions backend/db
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
UPDATE teachers SET lessons = ['L8', 'GE'] WHERE shortname = 'JMÜL';
CREATE teachers SET shortname = 'JKRÜ', longname = 'Jule Krützmann', lessons = ['D']; CREATE teachers SET shortname = 'SJOC', longname = 'Samira Jochmaring', lessons = ['M']; CREATE teachers SET shortname = 'JRÜS', longname = 'Julia Rüsing', lessons = ['E', 'GE']; CREATE teachers SET shortname = 'MHES', longname = 'Marc Hesse', lessons = ['SW', 'D']; CREATE teachers SET shortname = 'ALOO', longname = 'Anika Loose', lessons = ['BI', 'PA']; CREATE teachers SET shortname = 'JPFL', longname = ' Jan-Phillip Pflügel', lessons = ['MU', 'E']; CREATE teachers SET shortname = 'MROS', longname = 'Maria Rosenthal', lessons = ['MU', 'S0']; CREATE teachers SET shortname = 'SBER', longname = 'Simone Bergenthal', lessons = ['S0']; CREATE teachers SET shortname = 'LIBR', longname = 'Lisa Brentjes', lessons = ['E', 'D'];
6 changes: 6 additions & 0 deletions backend/history.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#V2
UPDATE teachers SET lessons = ['L8', 'D', "LI"] WHERE shortname = 'HRPA'; UPDATE teachers SET lessons = ['LI', 'D', "EK"] WHERE shortname = 'RSCH'; UPDATE teachers SET lessons = ['LI', 'D', "S0"] WHERE shortname = 'RWAL'; UPDATE teachers SET lessons = ['M', 'CH', "IF"] WHERE shortname = 'BROT';
select * from users;
namespace = test
db = test
select * from users;
4 changes: 2 additions & 2 deletions backend/src/api/change_password.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ pub async fn change_password_post(
verified: user.verified,
};

if let Err(e) = User::update_replace(db.clone(), old_user.id, new_user.clone()).await {
if let Err(e) = User::update_replace(db.clone(), new_user.clone()).await {
error!("Error updating user\n{e}");
return Err(error::ErrorInternalServerError( "Internal Server Error"));
}

let new_user_id = new_user.clone().id;
if let Err(e) = delete_user_sessions(db.clone(), format!("{}:{}", new_user_id.0, new_user_id.1)).await {
if let Err(e) = delete_user_sessions(db.clone(), format!("{}", new_user_id)).await {
error!("Error logging user out\n{e}");
return Err(error::ErrorInternalServerError( "Internal Server Error"));
}
Expand Down
2 changes: 1 addition & 1 deletion backend/src/api/change_untis_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ pub async fn change_untis_data_post(
person_id: body.person_id,
};

if let Err(e) = User::update_replace(db.clone(), id.clone(), new_user).await {
if let Err(e) = User::update_replace(db.clone(), new_user).await {
error!("Error updating user\n{e}");
return Err(error::ErrorInternalServerError("Internal Server Error"));
}
Expand Down
2 changes: 1 addition & 1 deletion backend/src/api/gdpr_data_compliance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub async fn gdpr_data_compliance_get(
};

let user_id = user.clone().id;
let sessions = match Session::get_user_sessions(db.clone(), format!("{}:{}", user_id.0, user_id.1)).await {
let sessions = match Session::get_user_sessions(db.clone(), format!("{}", user_id)).await {
Ok(a) => a,
Err(e) => {
error!("Error trying to get sessions\n{e}");
Expand Down
2 changes: 1 addition & 1 deletion backend/src/api/get_free_rooms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub struct TimetableQuery {

pub async fn get_free_rooms(
id: Option<Identity>, query: web::Query<TimetableQuery>, req: HttpRequest, untis_data: web::Data<GlobalUntisData>,
db: web::Data<DBConnection>,
db: web::Data<crate::AppState>,
) -> Result<impl Responder> {
if id.is_none() {
return Err(error::ErrorForbidden( "Not logged in".to_string()));
Expand Down
2 changes: 1 addition & 1 deletion backend/src/api/get_lernbueros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub struct TimetableQuery {

pub async fn get_lernbueros(
id: Option<Identity>, query: web::Query<TimetableQuery>, req: HttpRequest, untis_data: web::Data<GlobalUntisData>,
db: web::Data<DBConnection>,
db: web::Data<crate::AppState>,
) -> Result<impl Responder> {
if id.is_none() {
return Err(error::ErrorForbidden( "Not logged in".to_string()));
Expand Down
6 changes: 3 additions & 3 deletions backend/src/api/get_timetable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use serde::{Deserialize, Serialize};
use crate::{
api_wrapper::{
untis_client::UntisClient, utils::{FormattedLesson, TimetableParameter}
}, models::{
}, error::Error, models::{
model::{DBConnection, CRUD}, user_model::User
}, error::Error, utils::time::{format_for_untis, get_this_friday, get_this_monday}, GlobalUntisData
}, utils::time::{format_for_untis, get_this_friday, get_this_monday}, AppState, GlobalUntisData
};


Expand All @@ -26,7 +26,7 @@ pub struct TimetableQuery {

pub async fn get_timetable(
id: Option<Identity>, query: web::Query<TimetableQuery>, req: HttpRequest, untis_data: web::Data<GlobalUntisData>,
db: web::Data<DBConnection>,
db: web::Data<crate::AppState>,
) -> Result<impl Responder> {
if id.is_none() {
return Err(error::ErrorForbidden("Not logged in"));
Expand Down
2 changes: 1 addition & 1 deletion backend/src/api/get_timetable_serviceworker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub struct ServiceWorkerQuery {

pub async fn get_timetable_serviceworker(
id: Option<Identity>, query: web::Query<TimetableQuery>, data: web::Json<ServiceWorkerQuery>, untis_data: web::Data<GlobalUntisData>,
db: web::Data<DBConnection>,
db: web::Data<crate::AppState>,
) -> Result<impl Responder> {
if id.is_none() {
return Err(error::ErrorForbidden( "Not logged in").into());
Expand Down
8 changes: 4 additions & 4 deletions backend/src/api/link/email_change.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub async fn email_change_post(

let user_id = link.user;

let user = match User::get_from_id(db.clone(), user_id.clone()).await {
let user = match User::get_from_id(db.clone(), ("users".to_string(),user_id.clone())).await {
Ok(a) => match a {
Some(a) => a,
None => {
Expand Down Expand Up @@ -106,12 +106,12 @@ pub async fn email_change_post(
verified: user.verified,
};

if let Err(e) = User::update_replace(db.clone(), user_id.clone(), new_user).await {
if let Err(e) = User::update_replace(db.clone(), new_user).await {
error!("Error updating user email\n{e}");
return Err(error::ErrorInternalServerError( "There was a database error"));
}

if let Err(e) = Link::delete(db.clone(), link.id).await {
if let Err(e) = Link::delete(db.clone(), ("links".to_string(), link.id)).await {
warn!("Failed to delete link, ignoring\n{e}");
}

Expand All @@ -130,7 +130,7 @@ pub async fn email_change_post(
};

// Logout user from all devices
if let Err(e) = delete_user_sessions(db.clone(), format!("{}:{}", user_id.0, user_id.1)).await {
if let Err(e) = delete_user_sessions(db.clone(), format!("{}", user_id)).await {
error!("Error deleting user sessions\n{e}");
return Err(error::ErrorInternalServerError( "There was a database error"));
};
Expand Down
8 changes: 4 additions & 4 deletions backend/src/api/link/email_reset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub async fn email_reset_post(

let user_id = link.user;

let user = match User::get_from_id(db.clone(), user_id.clone()).await {
let user = match User::get_from_id(db.clone(), ("users".to_string(),user_id.clone())).await {
Ok(a) => match a {
Some(a) => a,
None => {
Expand Down Expand Up @@ -93,17 +93,17 @@ pub async fn email_reset_post(
verified: user.verified,
};

if User::update_replace(db.clone(), user_id.clone(), new_user).await.is_err() {
if User::update_replace(db.clone(), new_user).await.is_err() {
error!("Error updating user email");
return Err(error::ErrorInternalServerError( "There was a database error"));
}

if let Err(e) = Link::delete(db.clone(), link.id).await {
if let Err(e) = Link::delete(db.clone(), ("links".to_string(),link.id)).await {
warn!("Failed to delete link, ignoring\n{e}");
}

// Logout user from all devices
if let Err(e) = delete_user_sessions(db.clone(), format!("{}:{}", user_id.0, user_id.1)).await {
if let Err(e) = delete_user_sessions(db.clone(), format!("{}", user_id)).await {
error!("Error deleting user sessions\n{e}");
return Err(error::ErrorInternalServerError( "There was a database error"));
};
Expand Down
8 changes: 4 additions & 4 deletions backend/src/api/link/password.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub async fn reset_password_post(

let user_id = link.user;

let user = match User::get_from_id(db.clone(), user_id.clone()).await {
let user = match User::get_from_id(db.clone(), ("users".to_string(), user_id.clone())).await {
Ok(a) => match a {
Some(a) => a,
None => {
Expand Down Expand Up @@ -105,16 +105,16 @@ pub async fn reset_password_post(
verified: old_user.verified,
};

if let Err(e) = User::update_replace(db.clone(), new_user.clone().id, new_user.clone()).await {
if let Err(e) = User::update_replace(db.clone(), new_user.clone()).await {
error!("Error updating user\n{e}");
return Err(error::ErrorInternalServerError( "Internal Server Error"));
}

if let Err(e) = Link::delete(db.clone(), link.id).await {
if let Err(e) = Link::delete(db.clone(), ("links".to_string(), link.id)).await {
warn!("Failed to delete link, ignoring\n{e}");
}

if let Err(e) = delete_user_sessions(db.clone(), format!("{}:{}", new_user.id.0, new_user.id.1)).await {
if let Err(e) = delete_user_sessions(db.clone(), format!("{}", new_user.id)).await {
error!("Error logging user out\n{e}");
return Err(error::ErrorInternalServerError( "Internal Server Error"));
}
Expand Down
6 changes: 3 additions & 3 deletions backend/src/api/link/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub async fn verify_get(path: web::Path<String>, db: ConnectionData) -> Result<i
}
}

let user = match User::get_from_id(db.clone(), link.user.clone()).await {
let user = match User::get_from_id(db.clone(), ("users".to_string(), link.user.clone())).await {
Ok(a) => match a {
Some(a) => a,
None => {
Expand All @@ -68,12 +68,12 @@ pub async fn verify_get(path: web::Path<String>, db: ConnectionData) -> Result<i
verified: true,
};

if let Err(e) = User::update_replace(db.clone(), link.user, new_user).await {
if let Err(e) = User::update_replace(db.clone(), new_user).await {
error!("Updating user failed\n{e}");
return Err(error::ErrorInternalServerError("Internal Server Error"));
}

if let Err(e) = Link::delete(db, link.id).await {
if let Err(e) = Link::delete(db, ("links".to_string(), link.id)).await {
warn!("Failed to delete link, ignoring\n{e}");
}

Expand Down
4 changes: 2 additions & 2 deletions backend/src/api/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct LoginResponse {
}

pub async fn login_post(
data: web::Json<LoginData>, db: web::Data<DBConnection>, req: HttpRequest,
data: web::Json<LoginData>, db: web::Data<crate::AppState>, req: HttpRequest,
) -> Result<impl Responder> {
let db_user: User = {
// Very readable yes yes. Suprisingly clippy doesn't have a Problem with this
Expand All @@ -36,7 +36,7 @@ pub async fn login_post(
};

match db_user.verify_password(data.password.clone()) {
Ok(_) => match Identity::login(&req.extensions(), format!("{}:{}", db_user.id.0, db_user.id.1)) {
Ok(_) => match Identity::login(&req.extensions(), format!("{}", db_user.id)) {
Ok(_) => Ok(web::Json(LoginResponse {
untis_cypher: db_user.untis_cypher,
})),
Expand Down
2 changes: 1 addition & 1 deletion backend/src/api/logout_all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use log::error;

use crate::{api::utils::TextResponse, database::sessions::delete_user_sessions, models::model::DBConnection};

pub async fn logout_all_post(id: Option<Identity>, db: web::Data<DBConnection>) -> Result<impl Responder> {
pub async fn logout_all_post(id: Option<Identity>, db: web::Data<crate::AppState>) -> Result<impl Responder> {
if let Some(identity) = id {
let id = match identity.id() {
Ok(a) => a,
Expand Down
8 changes: 4 additions & 4 deletions backend/src/api/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub struct RegisterData {
}

pub async fn register_post(
data: web::Json<RegisterData>, db: web::Data<DBConnection>, request: HttpRequest, mailer: web::Data<Mailer>,
data: web::Json<RegisterData>, db: web::Data<crate::AppState>, request: HttpRequest, mailer: web::Data<Mailer>,
) -> Result<impl Responder> {
if data.email.clone().parse::<Address>().is_err() {
return Err(error::ErrorUnprocessableEntity( "Not a valid email address"));
Expand Down Expand Up @@ -57,9 +57,9 @@ pub async fn register_post(
verified: false,
};

let ret_user = match User::create(db.clone(), "users".to_owned(), db_user).await {
let ret_user = match User::create(db.clone(), db_user).await {
Ok(a) => a,
Err(e) => return Err(e.into()),
Err(e) => return Err(error::ErrorInternalServerError("Interal Server Error")),
};

let expiry_time = Utc::now().checked_add_months(Months::new(1)).unwrap();
Expand Down Expand Up @@ -94,7 +94,7 @@ pub async fn register_post(
return Err(error::ErrorInternalServerError("Internal Server Error"));
}

if let Err(e) = Identity::login(&request.extensions(), format!("{}:{}", ret_user.id.0, ret_user.id.1)) {
if let Err(e) = Identity::login(&request.extensions(), format!("{}", ret_user.id)) {
error!("Error trying to log into Identity\n{}", e);
return Err(error::ErrorInternalServerError("Internal Server Error"));
};
Expand Down
20 changes: 10 additions & 10 deletions backend/src/api_wrapper/untis_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use super::utils::{
self, day_of_week, DetailedSubject, FormattedFreeRoom, FormattedLesson, Holidays, Klasse, LoginResults, PeriodObject, Schoolyear, Substitution, TimegridUnits, TimetableParameter, UntisArrayResponse
};
use crate::{
api_wrapper::utils::UntisResponse, models::{manual_lb_model::ManualLB, model::DBConnection, room_model::Room, teacher_model::Teacher}, error::Error
api_wrapper::utils::UntisResponse, error::Error, models::{manual_lb_model::ManualLB, room_model::Room, teacher_model::Teacher}
};

#[derive(Clone)]
Expand All @@ -23,7 +23,7 @@ pub struct UntisClient {
client: Client,
jsessionid: String,
ids: HashMap<String, u16>,
db: web::Data<DBConnection>,
db: web::Data<crate::AppState>,
}

#[allow(dead_code)]
Expand Down Expand Up @@ -51,7 +51,7 @@ impl UntisClient {
}

pub async fn init(
user: String, password: String, id: String, school: String, subdomain: String, db: web::Data<DBConnection>,
user: String, password: String, id: String, school: String, subdomain: String, db: web::Data<crate::AppState>,
) -> Result<Self, Error> {
let mut untis_client = Self {
person_type: 0,
Expand All @@ -73,7 +73,7 @@ impl UntisClient {

pub async fn unsafe_init(
jsessionid: String, person_id: u16, person_type: u16, id: String, school: String, subdomain: String,
db: web::Data<DBConnection>,
db: web::Data<crate::AppState>,
) -> Result<Self, Error> {
let client = Client::new();

Expand Down Expand Up @@ -353,7 +353,7 @@ impl UntisClient {
let mut formatted_lesson = FormattedLesson {
teacher,
is_lb: false,
start: u8::try_from(start).map_err(|err| Error::UntisError(err.to_string() + " 369"))?,
start: u8::try_from(start).map_err(|err| Error::UntisError(err.to_string() + " 369"))?.into(),
length: if !lesson.su.is_empty()
&& d.iter().any(|les| {
!les.su.is_empty()
Expand Down Expand Up @@ -383,12 +383,12 @@ impl UntisClient {
10
}
else{
(((lesson.end_time - lesson.start_time) / 85) as f32).floor() as u8
((((lesson.end_time - lesson.start_time) / 85) as f32).floor() as u8).into()
}
} else {
1
},
day,
day: day.into(),
subject,
subject_short,
room,
Expand Down Expand Up @@ -443,7 +443,7 @@ impl UntisClient {
//Swim lessons
!formatted_lesson.room.contains("Bad");
if formatted_lesson.length > 1 && !lesson.su.is_empty() {
skip.insert(lesson.su[0].id, formatted_lesson.length - 1);
skip.insert(lesson.su[0].id, (formatted_lesson.length - 1).try_into().unwrap());
}
formatted.push(formatted_lesson);
}
Expand Down Expand Up @@ -654,9 +654,9 @@ impl UntisClient {
every_lb.push(FormattedLesson {
teacher: teachers,
is_lb: true,
start,
start: start.into(),
length: 1,
day,
day: day.into(),
subject: lesson.0.clone(),
subject_short: lesson.0.clone(),
room: rooms,
Expand Down
6 changes: 3 additions & 3 deletions backend/src/api_wrapper/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,9 @@ pub struct FormattedFreeRoom {
pub struct FormattedLesson {
pub teacher: String,
pub is_lb: bool,
pub start: u8,
pub length: u8,
pub day: u8,
pub start: i32,
pub length: i32,
pub day: i32,
pub subject: String,
pub subject_short: String,
pub room: String,
Expand Down
2 changes: 1 addition & 1 deletion backend/src/database/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ use crate::{models::model::ConnectionData, error::Error};
/// NEXER EXPOSE THIS FUNCTION TO USER INPUT, IT WILL ALLOW THEM TO SQL INJECT
pub async fn delete_user_sessions(db: ConnectionData, id: String) -> Result<(), Error> {
// Do not ever do this
db.query(format!("DELETE sessions WHERE token = /.*{}.*/;", id)).await?;

Ok(())
}
1 change: 0 additions & 1 deletion backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ async fn main() -> io::Result<()> {
.await
.expect("DB Credentials to be correct");

session_db.use_ns(db_namespace).use_db(db_database).await.expect("using namespace and db to work");

info!("Connecting SMTP...");

Expand Down
Loading

0 comments on commit 893e577

Please sign in to comment.