From 357b6ce79411d9435fdcab2a1d1a9d974b07374e Mon Sep 17 00:00:00 2001 From: nils <48135649+Nilstrieb@users.noreply.github.com> Date: Fri, 16 Jul 2021 17:06:09 +0200 Subject: [PATCH] LETS FUCKING GOOO --- src/auth.rs | 28 ++++++++++++++-------------- src/handlers.rs | 9 +++++++++ src/main.rs | 1 + 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/auth.rs b/src/auth.rs index 6cd73aa..8c4fe17 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -1,11 +1,17 @@ use crate::errors::ServiceError; use crate::models::User; use actix_web::dev::{Payload, ServiceRequest}; +use actix_web::error::ErrorUnauthorized; +use actix_web::http::header::Header; use actix_web::{FromRequest, HttpMessage, HttpRequest, HttpResponse}; use actix_web_httpauth::extractors::bearer::BearerAuth; +use actix_web_httpauth::extractors::AuthenticationError; +use actix_web_httpauth::headers::authorization; +use actix_web_httpauth::headers::authorization::Bearer; use chrono::Utc; -use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation}; +use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Validation}; use serde::{Deserialize, Serialize}; +use std::future; #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)] pub enum Role { @@ -28,16 +34,10 @@ impl FromRequest for Claims { type Config = (); fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { - std::future::ready( - req.extensions() - .get::() - .map(|claims| claims.clone()) - .ok_or( - HttpResponse::InternalServerError() - .json("Could not get claims") - .into(), - ), - ) + future::ready(match authorization::Authorization::::parse(req) { + Ok(auth) => validate_token(auth.into_scheme().token()), + Err(_) => Err(ErrorUnauthorized("No Bearer token present")), + }) } } @@ -54,7 +54,7 @@ pub async fn validator( } } -fn validate_token(token: &str) -> Result { +fn validate_token(token: &str) -> Result { let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET env var"); let decoded = jsonwebtoken::decode::( @@ -66,7 +66,7 @@ fn validate_token(token: &str) -> Result { .claims; if decoded.exp < Utc::now().timestamp() as usize { - Err(ServiceError::TokenExpiredError) + Err(ServiceError::TokenExpiredError.into()) } else { Ok(decoded) } @@ -90,7 +90,7 @@ pub fn create_jwt_role(user: &User, role: Role) -> Result let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET env var"); - let header = Header::new(Algorithm::HS512); + let header = jsonwebtoken::Header::new(Algorithm::HS512); jsonwebtoken::encode( &header, &claims, diff --git a/src/handlers.rs b/src/handlers.rs index 998d832..9ec6e75 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -1,5 +1,6 @@ use super::actions; use super::Pool; +use crate::auth::Role::Admin; use crate::auth::{create_jwt, create_jwt_role, Claims, Role}; use crate::models::User; use actix_web::error::ErrorUnauthorized; @@ -103,3 +104,11 @@ pub async fn admin_login(credentials: Json) -> HttpResult { Err(ErrorUnauthorized("Incorrect credentials")) } } + +pub async fn test_auth(claims: Claims) -> HttpResult { + if claims.role == Admin { + Ok(HttpResponse::Ok().body("Nice du bist admin")) + } else { + Err(ErrorUnauthorized("kein admin :(")) + } +} diff --git a/src/main.rs b/src/main.rs index c219a6d..31e355b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,6 +32,7 @@ async fn main() -> std::io::Result<()> { App::new() .data(pool.clone()) .route("/users", web::post().to(handlers::add_user)) + .route("/test", web::get().to(handlers::test_auth)) .route("/admin", web::post().to(handlers::admin_login)) .service( web::scope("/users")