From 32c266e3663a978e0105dbc9d6280b8524ae7ed7 Mon Sep 17 00:00:00 2001 From: Sebastian Pravda Date: Tue, 25 Oct 2022 17:35:03 +0200 Subject: [PATCH] feat: user login service --- core/src/lib.rs | 1 + core/src/services/candidate_service.rs | 28 ++++++++++++++++++++++++++ core/src/services/mod.rs | 1 + core/src/token/candidate_token.rs | 13 ++++++++++++ entity/src/mod.rs | 8 ++++++++ 5 files changed, 51 insertions(+) create mode 100644 core/src/services/candidate_service.rs create mode 100644 core/src/services/mod.rs create mode 100644 entity/src/mod.rs diff --git a/core/src/lib.rs b/core/src/lib.rs index 4f820ca..942af37 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -2,6 +2,7 @@ mod mutation; mod query; pub mod crypto; pub mod token; +pub mod services; pub use mutation::*; pub use query::*; diff --git a/core/src/services/candidate_service.rs b/core/src/services/candidate_service.rs new file mode 100644 index 0000000..dffb5ba --- /dev/null +++ b/core/src/services/candidate_service.rs @@ -0,0 +1,28 @@ +use jsonwebtoken::{Header, EncodingKey}; +use sea_orm::DatabaseConnection; + +use crate::{crypto, Query, token::candidate_token::CandidateToken}; + +pub async fn login(db: &DatabaseConnection, id: i32, password: String) -> Option { + let candidate = Query::find_candidate_by_id(db, id).await + .unwrap() + .unwrap(); + + + let valid = crypto::verify_password(&password,&candidate.code ) + .expect("Invalid password"); + + if !valid { + return None; + } + let payload = CandidateToken::generate(candidate.name.unwrap(), + candidate.surname.unwrap()); + + let jwt = jsonwebtoken::encode( + &Header::default(), + &payload, + &EncodingKey::from_secret(&[0]) + ).ok(); + jwt +} + diff --git a/core/src/services/mod.rs b/core/src/services/mod.rs new file mode 100644 index 0000000..1992ce2 --- /dev/null +++ b/core/src/services/mod.rs @@ -0,0 +1 @@ +pub mod candidate_service; \ No newline at end of file diff --git a/core/src/token/candidate_token.rs b/core/src/token/candidate_token.rs index 5a43493..7c5a973 100644 --- a/core/src/token/candidate_token.rs +++ b/core/src/token/candidate_token.rs @@ -1,3 +1,4 @@ +use chrono::Utc; use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize)] @@ -8,4 +9,16 @@ pub struct CandidateToken { pub exp: i64, pub name: String, pub surname: String, +} + +impl CandidateToken { + pub fn generate(name: String, surname: String) -> Self { + let now = Utc::now().timestamp(); + CandidateToken { + iat: now, + exp: now + 60 * 60, // 1 hour for now + name, + surname, + } + } } \ No newline at end of file diff --git a/entity/src/mod.rs b/entity/src/mod.rs new file mode 100644 index 0000000..63cf621 --- /dev/null +++ b/entity/src/mod.rs @@ -0,0 +1,8 @@ +//! SeaORM Entity. Generated by sea-orm-codegen 0.9.3 + +pub mod prelude; + +pub mod admin; +pub mod candidate; +pub mod parent; +pub mod session;