diff --git a/src/auth.rs b/src/auth.rs index 8c0f2c27..21432ac8 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -19,6 +19,7 @@ impl AuthorizationService { AuthorizationService { cfg, database } } + /// Create Json Web Token pub async fn sign_jwt(&self, user: UserCompact) -> String { let settings = self.cfg.settings.read().await; @@ -29,9 +30,14 @@ impl AuthorizationService { let claims = UserClaims { user, exp: exp_date }; - encode(&Header::default(), &claims, &EncodingKey::from_secret(key)).unwrap() + encode(&Header::default(), &claims, &EncodingKey::from_secret(key)).expect("argument `Header` should match `EncodingKey`") } + /// Verify Json Web Token + /// + /// # Errors + /// + /// This function will return an error if the JWT is not good or expired. pub async fn verify_jwt(&self, token: &str) -> Result { let settings = self.cfg.settings.read().await; @@ -50,12 +56,21 @@ impl AuthorizationService { } } + /// Get Claims from Request + /// + /// # Errors + /// + /// This function will return an `ServiceError::TokenNotFound` if `HeaderValue` is `None` + /// This function will pass through the `ServiceError::TokenInvalid` if unable to verify the JWT. pub async fn get_claims_from_request(&self, req: &HttpRequest) -> Result { - let _auth = req.headers().get("Authorization"); - match _auth { - Some(_) => { - let _split: Vec<&str> = _auth.unwrap().to_str().unwrap().split("Bearer").collect(); - let token = _split[1].trim(); + match req.headers().get("Authorization") { + Some(auth) => { + let split: Vec<&str> = auth + .to_str() + .expect("variable `auth` contains data that is not visible ASCII chars.") + .split("Bearer") + .collect(); + let token = split[1].trim(); match self.verify_jwt(token).await { Ok(claims) => Ok(claims), @@ -66,6 +81,11 @@ impl AuthorizationService { } } + /// Get User (in compact form) from Request + /// + /// # Errors + /// + /// This function will return an `ServiceError::UserNotFound` if unable to get user from database. pub async fn get_user_compact_from_request(&self, req: &HttpRequest) -> Result { let claims = self.get_claims_from_request(req).await?;