feat: authenticate user from jwt

This commit is contained in:
Sebastian Pravda 2022-10-26 11:22:42 +02:00
parent 04bc69501f
commit ecc9b54ce5
No known key found for this signature in database
GPG key ID: F3BC84F08EFA3F57
3 changed files with 27 additions and 5 deletions

View file

@ -66,10 +66,15 @@ async fn login(conn: Connection<'_, Db>, login_form: Json<LoginRequest>) -> Resu
}
#[get("/whoami")]
async fn whoami(token: TokenRequest) -> Result<String, Custom<String>> {
println!("{:?}", token.to_token());
async fn whoami(conn: Connection<'_, Db>, token_req: Result<TokenRequest, Status>) -> Result<String, Custom<String>> {
let db = conn.into_inner();
let token = token_req.ok().unwrap().to_token();
let user = CandidateService::authenticate_candidate(db, token).await;
Ok("authenticated!".to_owned())
match user {
Ok(user) => Ok(format!("{} {}", user.name.unwrap(), user.surname.unwrap())),
Err(e) => Err(custom_err_from_service_err(e)),
}
}
#[get("/hello")]

View file

@ -12,4 +12,7 @@ pub const USER_NOT_FOUND_ERROR: ServiceError = ServiceError(Status { code: 404 }
pub const DB_ERROR: ServiceError = ServiceError(Status { code: 500 },
"Database error");
pub const USER_NOT_FOUND_BY_JWT_ID: ServiceError = ServiceError(Status { code: 500 }, // User got somehow
"User not found, please contact technical support"); // Shouldn't ever happen
pub struct ServiceError<'a>(pub Status, pub &'a str);

View file

@ -1,10 +1,12 @@
use entity::candidate;
use sea_orm::DatabaseConnection;
use crate::{crypto, Query, token::{generate_candidate_token}, error::{ServiceError, USER_NOT_FOUND_ERROR, INVALID_CREDENTIALS_ERROR, DB_ERROR}};
use crate::{crypto, Query, token::{generate_candidate_token, decode_candidate_token, candidate_token::CandidateToken}, error::{ServiceError, USER_NOT_FOUND_ERROR, INVALID_CREDENTIALS_ERROR, DB_ERROR, JWT_ERROR, USER_NOT_FOUND_BY_JWT_ID}};
pub struct CandidateService;
impl CandidateService {
pub async fn login(db: &DatabaseConnection, id: i32, password: String) -> Result<String, ServiceError> {
let candidate = match Query::find_candidate_by_id(db, id).await {
Ok(candidate) => match candidate {
@ -25,5 +27,17 @@ impl CandidateService {
let jwt = generate_candidate_token(candidate); // TODO better error handling
Ok(jwt)
}
}
pub async fn authenticate_candidate(db: &DatabaseConnection, token: CandidateToken) -> Result<candidate::Model, ServiceError> {
let candidate = match Query::find_candidate_by_id(db, token.application_id).await {
Ok(candidate) => match candidate {
Some(candidate) => candidate,
None => return Err(USER_NOT_FOUND_BY_JWT_ID)
},
Err(_) => {return Err(DB_ERROR)}
};
Ok(candidate)
}
}