1
0
mirror of https://github.com/actix/examples synced 2025-02-13 14:02:19 +01:00

83 lines
2.2 KiB
Rust
Raw Normal View History

2022-03-06 00:15:16 +00:00
use std::future::{ready, Ready};
2019-06-17 12:48:03 +06:00
use actix_identity::Identity;
2022-10-26 16:51:27 +01:00
use actix_web::{
dev::Payload, web, Error, FromRequest, HttpMessage as _, HttpRequest, HttpResponse,
};
2022-09-10 23:33:09 +01:00
use diesel::prelude::*;
use serde::Deserialize;
2019-03-29 13:43:03 -07:00
2022-08-28 18:39:28 +01:00
use crate::{
errors::ServiceError,
models::{Pool, SlimUser, User},
utils::verify,
};
#[derive(Debug, Deserialize)]
pub struct AuthData {
pub email: String,
pub password: String,
}
// we need the same data
// simple aliasing makes the intentions clear and its more readable
pub type LoggedUser = SlimUser;
2019-04-14 10:34:41 -07:00
impl FromRequest for LoggedUser {
2019-03-29 13:43:03 -07:00
type Error = Error;
type Future = Ready<Result<LoggedUser, Error>>;
2019-03-29 13:43:03 -07:00
2019-04-14 10:34:41 -07:00
fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
if let Ok(identity) = Identity::from_request(req, pl).into_inner() {
2022-10-26 16:51:27 +01:00
if let Ok(user_json) = identity.id() {
if let Ok(user) = serde_json::from_str(&user_json) {
2022-03-06 00:15:16 +00:00
return ready(Ok(user));
}
}
}
2022-03-06 00:15:16 +00:00
ready(Err(ServiceError::Unauthorized.into()))
}
}
2019-12-07 23:59:24 +06:00
pub async fn logout(id: Identity) -> HttpResponse {
2022-10-26 16:51:27 +01:00
id.logout();
HttpResponse::NoContent().finish()
}
2019-12-07 23:59:24 +06:00
pub async fn login(
2022-10-26 16:51:27 +01:00
req: HttpRequest,
auth_data: web::Json<AuthData>,
pool: web::Data<Pool>,
) -> Result<HttpResponse, actix_web::Error> {
let user = web::block(move || query(auth_data.into_inner(), pool)).await??;
2019-12-07 23:59:24 +06:00
let user_string = serde_json::to_string(&user).unwrap();
2022-10-26 16:51:27 +01:00
Identity::login(&req.extensions(), user_string).unwrap();
2022-09-10 23:33:09 +01:00
2022-10-26 16:51:27 +01:00
Ok(HttpResponse::NoContent().finish())
}
2019-12-07 23:59:24 +06:00
pub async fn get_me(logged_user: LoggedUser) -> HttpResponse {
HttpResponse::Ok().json(logged_user)
}
/// Diesel query
fn query(auth_data: AuthData, pool: web::Data<Pool>) -> Result<SlimUser, ServiceError> {
use crate::schema::users::dsl::{email, users};
2022-09-10 23:33:09 +01:00
let mut conn = pool.get().unwrap();
let mut items = users
.filter(email.eq(&auth_data.email))
2022-09-10 23:33:09 +01:00
.load::<User>(&mut conn)?;
if let Some(user) = items.pop() {
if let Ok(matching) = verify(&user.hash, &auth_data.password) {
if matching {
return Ok(user.into());
}
}
}
Err(ServiceError::Unauthorized)
}