Skip to content

Commit

Permalink
refactored fallible helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Uewotm90 committed Dec 7, 2023
1 parent c00dce7 commit 39ef814
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 38 deletions.
49 changes: 26 additions & 23 deletions src/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@ use jsonwebtoken::{

use serde::{Deserialize, Serialize};
use std::{env, fmt::Display, str::FromStr};
use tonic::{metadata, Request, Status};
use tonic::{
metadata::{self, errors::ToStrError},
Request, Status,
};

/// This method is used to validate the access token (not refresh).
pub fn validation_interceptor(mut req: Request<()>) -> Result<Request<()>, Status> {
let token = match req.token_string() {
let token = match req
.token_string()
.map_err(|err| Status::internal("failed to get token string"))?
{
Some(token) => Token::from_str(TokenType::AccessToken, &token),
None => return Err(Status::unauthenticated("Token not found")),
};
Expand Down Expand Up @@ -252,36 +258,33 @@ impl From<TokenError> for Status {
/// An extension trait for [Request]`s that provides a variety of convenient
/// auth related methods.
pub trait RequestExt {
fn token_string(&self) -> Option<String>;
fn token_str(&self) -> Option<&str>;
fn token_string(&self) -> Result<Option<String>, ToStrError>;
fn token_str(&self) -> Result<Option<&str>, ToStrError>;

fn uid(&self) -> Option<i32>;
}

impl<T> RequestExt for Request<T> {
/// Returns the token string from the request metadata.
//TODO should return result
fn token_string(&self) -> Option<String> {
self.metadata().get("authorization").map(|token| {
token
.to_str()
.expect("failed to parse token string")
.trim_start_matches("Bearer ")
.to_string()
})
fn token_string(&self) -> Result<Option<String>, ToStrError> {
let res = self.metadata().get("authorization");
match res {
Some(val) => Ok(Some(
val.to_str()?.trim_start_matches("Bearer ").to_string(),
)),
None => Ok(None),
}
}
/// Returns the token string slice from the request metadata.
//TODO should return result
fn token_str(&self) -> Option<&str> {
fn token_str(&self) -> Result<Option<&str>, ToStrError> {
match self.metadata().get("authorization") {
//TODO better error handling
Some(token) => Some(
Some(token) => Ok(Some(
token
.to_str()
.expect("failed to parse token string")
.to_str()?
// .expect("failed to parse token string")
.trim_start_matches("Bearer "),
),
None => None,
)),
None => Ok(None),
}
}
//TODO should return result
Expand All @@ -290,8 +293,8 @@ impl<T> RequestExt for Request<T> {
//TODO better error handling
let uid = match self
.metadata()
.get("uid")
.expect("failed to parse user id")
.get("uid")?
// .expect("failed to parse user id")
.to_str()
{
Ok(uid) => uid,
Expand Down
43 changes: 30 additions & 13 deletions src/api/ecdar_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,12 @@ pub async fn handle_session(
let mut session = match session_context
.get_by_token(
TokenType::RefreshToken,
request.token_string().ok_or(Status::internal(
"failed to get token from request metadata",
))?,
request
.token_string()
.map_err(|err| Status::internal("failed to get token from request metadata"))?

Check warning on line 99 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

unused variable: `err`

warning: unused variable: `err` --> src/api/ecdar_api.rs:99:31 | 99 | .map_err(|err| Status::internal("failed to get token from request metadata"))? | ^^^ help: if this is intentional, prefix it with an underscore: `_err` | = note: `#[warn(unused_variables)]` on by default

Check warning on line 99 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

unused variable: `err`

warning: unused variable: `err` --> src/api/ecdar_api.rs:99:31 | 99 | .map_err(|err| Status::internal("failed to get token from request metadata"))? | ^^^ help: if this is intentional, prefix it with an underscore: `_err` | = note: `#[warn(unused_variables)]` on by default
.ok_or(Status::internal(
"failed to get token from request metadata",
))?,
)
.await
{
Expand Down Expand Up @@ -198,9 +201,16 @@ impl EcdarApi for ConcreteEcdarApi {
.session_context
.get_by_token(
TokenType::AccessToken,
request.token_string().ok_or(Status::internal(
"failed to get token from request metadata",
))?,
request
.token_string()
.map_err(|err| {

Check warning on line 206 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

unused variable: `err`

warning: unused variable: `err` --> src/api/ecdar_api.rs:206:47 | 206 | ... .map_err(|err| { | ^^^ help: if this is intentional, prefix it with an underscore: `_err`

Check warning on line 206 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

unused variable: `err`

warning: unused variable: `err` --> src/api/ecdar_api.rs:206:47 | 206 | ... .map_err(|err| { | ^^^ help: if this is intentional, prefix it with an underscore: `_err`
Status::internal(
"failed to get token from request metadata",
)
})?
.ok_or(Status::internal(
"failed to get token from request metadata",
))?,
)
.await
.map_err(|err| Status::new(Code::Internal, err.to_string()))?
Expand Down Expand Up @@ -319,9 +329,12 @@ impl EcdarApi for ConcreteEcdarApi {
.session_context
.get_by_token(
TokenType::AccessToken,
request.token_string().ok_or(Status::internal(
"Failed to get token from request metadata",
))?,
request
.token_string()
.map_err(|err| Status::internal("failed to get token from request metadata"))?

Check warning on line 334 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

unused variable: `err`

warning: unused variable: `err` --> src/api/ecdar_api.rs:334:31 | 334 | .map_err(|err| Status::internal("failed to get token from request metadata"))? | ^^^ help: if this is intentional, prefix it with an underscore: `_err`
.ok_or(Status::internal(
"Failed to get token from request metadata",
))?,
)
.await
.map_err(|_err| Status::internal("failed to query database"))? //TODO better error message
Expand Down Expand Up @@ -401,10 +414,13 @@ impl EcdarApi for ConcreteEcdarApi {
.session_context
.get_by_token(
TokenType::AccessToken,
request.token_string().ok_or(Status::new(
Code::Internal,
"Failed to get token from request metadata",
))?,
request
.token_string()
.map_err(|err| Status::internal("failed to get token from request metadata"))?

Check warning on line 419 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

unused variable: `err`

warning: unused variable: `err` --> src/api/ecdar_api.rs:419:31 | 419 | .map_err(|err| Status::internal("failed to get token from request metadata"))? | ^^^ help: if this is intentional, prefix it with an underscore: `_err`
.ok_or(Status::new(
Code::Internal,
"Failed to get token from request metadata",
))?,
) //? better error message?
.await
{
Expand Down Expand Up @@ -848,6 +864,7 @@ impl EcdarApiAuth for ConcreteEcdarApi {
TokenType::RefreshToken,
request
.token_str()
.map_err(|err| Status::internal("failed to get token from request metadata"))?

Check warning on line 867 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

unused variable: `err`

warning: unused variable: `err` --> src/api/ecdar_api.rs:867:31 | 867 | .map_err(|err| Status::internal("failed to get token from request metadata"))? | ^^^ help: if this is intentional, prefix it with an underscore: `_err`
.ok_or(Status::unauthenticated("No refresh token provided"))?,
);
let token_data = refresh_token.validate()?;
Expand Down
4 changes: 2 additions & 2 deletions src/tests/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ mod auth {

let result = request.token_str().unwrap();

assert_eq!(result, token.trim_start_matches("Bearer "));
assert_eq!(result.unwrap(), token.trim_start_matches("Bearer "));
}

#[tokio::test]
async fn request_token_no_token_returns_none() {
let request = Request::new(());
let result = request.token_str();
let result = request.token_str().unwrap();

assert!(result.is_none());
}
Expand Down

0 comments on commit 39ef814

Please sign in to comment.