feat: user login service

This commit is contained in:
Sebastian Pravda 2022-10-25 17:35:03 +02:00
parent 4a852fa915
commit 32c266e366
No known key found for this signature in database
GPG key ID: F3BC84F08EFA3F57
5 changed files with 51 additions and 0 deletions

View file

@ -2,6 +2,7 @@ mod mutation;
mod query;
pub mod crypto;
pub mod token;
pub mod services;
pub use mutation::*;
pub use query::*;

View file

@ -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<String> {
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
}

1
core/src/services/mod.rs Normal file
View file

@ -0,0 +1 @@
pub mod candidate_service;

View file

@ -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,
}
}
}

8
entity/src/mod.rs Normal file
View file

@ -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;