Skip to content

Commit

Permalink
Merge pull request #42 from ECDAR-AAU-SW-P5/auth-documentation
Browse files Browse the repository at this point in the history
Adds documentation for multiple auth methods
  • Loading branch information
EmilML authored Nov 14, 2023
2 parents 9adcea0 + 06f10d6 commit 7c92274
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub struct Claims {
exp: usize,
}

/// This method is used to create a new access token based on the uid.
/// The token is valid for 20 minutes.
pub fn create_access_token(uid: &str) -> Result<String, Error> {
let secret = env::var("ACCESS_TOKEN_HS512_SECRET")
.expect("Expected ACCESS_TOKEN_HS512_SECRET to be set.");
Expand All @@ -37,6 +39,8 @@ pub fn create_access_token(uid: &str) -> Result<String, Error> {
.map_err(|_| ErrorKind::InvalidToken.into())
}

/// This method is used to create a new refresh token based on the uid.
/// The token is valid for 90 days.
pub fn create_refresh_token(uid: &str) -> Result<String, Error> {
let secret = env::var("REFRESH_TOKEN_HS512_SECRET")
.expect("Expected REFRESH_TOKEN_HS512_SECRET to be set.");
Expand All @@ -60,6 +64,7 @@ pub fn create_refresh_token(uid: &str) -> Result<String, Error> {
.map_err(|_| ErrorKind::InvalidToken.into())
}

/// This method is used to validate the access token (not refresh).
pub fn validation_interceptor(mut req: Request<()>) -> Result<Request<()>, Status> {
let token = match get_token_from_request(&req) {
Ok(token) => token,
Expand All @@ -78,6 +83,7 @@ pub fn validation_interceptor(mut req: Request<()>) -> Result<Request<()>, Statu
}
}

/// This method is used to get a token (access or refresh) from the request metadata.
pub fn get_token_from_request<T>(req: &Request<T>) -> Result<String, Status> {
let token = match req.metadata().get("authorization") {
Some(token) => token.to_str(),
Expand All @@ -93,6 +99,8 @@ pub fn get_token_from_request<T>(req: &Request<T>) -> Result<String, Status> {
}
}

/// This method is used to validate a token (access or refresh).
/// It returns the token data if the token is valid.
pub fn validate_token(token: String, is_refresh_token: bool) -> Result<TokenData<Claims>, Status> {
let secret: String;

Expand All @@ -104,7 +112,7 @@ pub fn validate_token(token: String, is_refresh_token: bool) -> Result<TokenData

let mut validation = Validation::new(Algorithm::HS512);

validation.validate_exp = true;
validation.validate_exp = true; // This might be redundant as this should be defualt, however, it doesn't seem to work without it.

match decode::<Claims>(
&token,
Expand Down

0 comments on commit 7c92274

Please sign in to comment.