Add auth_to_token_header
@@ -123,6 +123,7 @@ impl AuthService {
Ok(AuthContext::new(auth, &self.permission_roles_map))
}
+ /// Generates the auth token
pub fn auth_to_token_string(auth: &Auth) -> Result<String, ApiError> {
let auth_str = serde_json::to_string(&auth).map_err(|err| ApiError::InternalServerError {
cause: format!("Cannot serialize auth into string. Err: {}", err),
@@ -130,6 +131,12 @@ impl AuthService {
Ok(base64::encode(auth_str.as_bytes()))
}
+ /// Generates the auth HTTP header in the form:
+ /// Bearer: <TOKEN>
+ pub fn auth_to_token_header(auth: &Auth) -> Result<String, ApiError> {
+ Ok(format!("{}{}", JWT_TOKEN_HEADER_SUFFIX, AuthService::auth_to_token_string(&auth)?))
+ }
+
}
#[cfg(test)]
@@ -155,6 +162,25 @@ mod test {
Ok(())
}
+ #[test]
+ fn auth_service_should_create_authorization_token() -> Result<(), ApiError> {
+ // Arrange
+ let auth = Auth {
+ user: "12456abc".to_owned(),
+ roles: vec!["role_a".to_owned(), "role_b".to_owned()],
+ };
+
+ let expected_token_header = "Bearer eyJ1c2VyIjoiMTI0NTZhYmMiLCJyb2xlcyI6WyJyb2xlX2EiLCJyb2xlX2IiXX0=";
+
+ // Act
+ let token_header = AuthService::auth_to_token_header(&auth)?;
+
+ // Assert
+ assert_eq!(expected_token_header, token_header);
+
+ Ok(())
+ }
+
#[test]
fn auth_service_should_decode_base64_token() -> Result<(), ApiError> {
// Arrange
