initial commit

This commit is contained in:
Miguel da Mota 2023-12-31 01:21:07 +01:00
commit 8a19a733d6
35 changed files with 2489 additions and 0 deletions

68
src/middlewares/error.rs Normal file
View file

@ -0,0 +1,68 @@
use actix_web::{http::StatusCode, HttpResponse, ResponseError};
use diesel::result::Error;
use serde::Serialize;
use std::fmt::{Debug, Display, Formatter, Result};
#[derive(Debug)]
pub struct ErrorResponse {
pub message: String,
pub status: StatusCode,
}
impl Display for ErrorResponse {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}: {}", self.status, self.message)
}
}
impl From<actix_web::Error> for ErrorResponse {
fn from(err: actix_web::Error) -> Self {
ErrorResponse {
status: err.error_response().status(),
message: err.to_string(),
}
}
}
impl From<Error> for ErrorResponse {
fn from(err: Error) -> Self {
match err {
Error::NotFound => ErrorResponse {
status: StatusCode::NOT_FOUND,
message: err.to_string(),
},
_ => ErrorResponse {
status: StatusCode::INTERNAL_SERVER_ERROR,
message: err.to_string(),
},
}
}
}
impl ResponseError for ErrorResponse {
fn status_code(&self) -> StatusCode {
self.status
}
fn error_response(&self) -> HttpResponse {
#[derive(Serialize)]
struct Response {
error: ErrorResponse,
}
#[derive(Serialize)]
struct ErrorResponse {
message: String,
status: u16,
}
HttpResponse::build(self.status_code())
.content_type("application/json")
.json(Response {
error: ErrorResponse {
message: self.message.to_string(),
status: self.status_code().as_u16(),
},
})
}
}

2
src/middlewares/mod.rs Normal file
View file

@ -0,0 +1,2 @@
pub mod error;
pub mod user;

35
src/middlewares/user.rs Normal file
View file

@ -0,0 +1,35 @@
use crate::helpers::jwt::get_token;
use crate::middlewares::error::ErrorResponse;
use crate::models::user::Users;
use actix_web::http::{header, StatusCode};
use actix_web::HttpRequest;
pub fn get_user(req: HttpRequest) -> Result<Users, ErrorResponse> {
let authorization = req.headers().get(header::AUTHORIZATION);
match authorization {
Some(header) => {
let claims = get_token(header.to_str().unwrap());
match claims {
Ok(claims) => {
let user = Users::find(claims["user_id"].as_str())?;
Ok(user)
}
Err(e) => {
return Err(ErrorResponse {
message: e.to_string(),
status: StatusCode::INTERNAL_SERVER_ERROR,
})
}
}
}
None => {
return Err(ErrorResponse {
message: "Not Authorized".to_string(),
status: StatusCode::UNAUTHORIZED,
});
}
}
}