forked from Roflin/gamenight
Splits database into a separate crate
This commit is contained in:
@@ -6,7 +6,7 @@ use jsonwebtoken::{encode, Header, EncodingKey, decode, DecodingKey, Validation}
|
||||
use serde::{Serialize, Deserialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{schema::user::{User, get_user}, DbPool};
|
||||
use gamenight_database::{user::{get_user, Role, User}, DbPool};
|
||||
|
||||
use super::error::ApiError;
|
||||
|
||||
@@ -16,6 +16,24 @@ pub struct Claims {
|
||||
uid: Uuid
|
||||
}
|
||||
|
||||
pub struct AuthUser {
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
pub email: String,
|
||||
pub role: Role,
|
||||
}
|
||||
|
||||
impl From<User> for AuthUser {
|
||||
fn from(value: User) -> Self {
|
||||
Self{
|
||||
id: value.id,
|
||||
username: value.username,
|
||||
email: value.email,
|
||||
role: value.role,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_claims(req: &HttpRequest) -> Result<Claims, ApiError> {
|
||||
let token = req.headers()
|
||||
.get(http::header::AUTHORIZATION)
|
||||
@@ -43,18 +61,19 @@ pub fn get_token(user: &User) -> Result<String, ApiError> {
|
||||
&EncodingKey::from_secret(secret.as_bytes()))?)
|
||||
}
|
||||
|
||||
impl FromRequest for User {
|
||||
impl FromRequest for AuthUser {
|
||||
type Error = ApiError;
|
||||
type Future = Ready<Result<Self, Self::Error>>;
|
||||
|
||||
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
|
||||
ready(
|
||||
(|| -> Result<User, ApiError>{
|
||||
(|| -> Result<AuthUser, ApiError>{
|
||||
let pool = req.app_data::<Data<DbPool>>().expect("No database configured");
|
||||
let mut conn = pool.get().expect("couldn't get db connection from pool");
|
||||
let uid = get_claims(req)?.uid;
|
||||
let user = get_user(&mut conn, uid)?;
|
||||
|
||||
Ok(get_user(&mut conn, uid)?)
|
||||
Ok(user.into())
|
||||
})()
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user