Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GetUsers endpoint #75

Merged
merged 51 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from 50 commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
c8b14c1
protobuf
ViktorPlatz Dec 4, 2023
d1d7a05
Add role check to create_access and fix tests
sabotack Dec 4, 2023
08719c3
Move comment
sabotack Dec 4, 2023
df0b9c8
add list access info endpoint
ViktorPlatz Dec 5, 2023
78ddaec
add FromQueryResult so database can convert
ViktorPlatz Dec 5, 2023
cde61b0
list access info endpoints tests
ViktorPlatz Dec 5, 2023
10bcc62
get_access_by_model_id crud
ViktorPlatz Dec 5, 2023
2832c6c
get_access_by_model_id crud tests
ViktorPlatz Dec 5, 2023
77f9db1
protobufffffffffffffffffff
ViktorPlatz Dec 5, 2023
3bbfba3
clippy
ViktorPlatz Dec 5, 2023
e77f78d
Implement role checking in create_access
sabotack Dec 5, 2023
1a577f1
protobuf stuff
ViktorPlatz Dec 5, 2023
f6a4b7d
Implement role checking in update_access
sabotack Dec 5, 2023
f87e1c0
Add editor_role_check_helper method
sabotack Dec 5, 2023
b79a3d0
Implement role checking in delete_access
sabotack Dec 5, 2023
32baa72
merge with alis branch
ViktorPlatz Dec 5, 2023
573445e
clippy fmt
ViktorPlatz Dec 5, 2023
4910565
Add thiserror crate
MadsSR Dec 5, 2023
e85d910
Add get_by_ids mock
MadsSR Dec 5, 2023
fead523
Fix tests
MadsSR Dec 5, 2023
c2d7276
Add get users endpoint
MadsSR Dec 5, 2023
cb125ba
Add get_by_ids on user context
MadsSR Dec 5, 2023
7923c4e
Fix Token
MadsSR Dec 5, 2023
0afc0c2
Fix path to Model
MadsSR Dec 5, 2023
01ef8b5
Verify hashed password and refactor
MadsSR Dec 5, 2023
c9547f5
Add get auth token tests
MadsSR Dec 5, 2023
cd29928
Add GetUsers rpc to protobuff
MadsSR Dec 5, 2023
8aa7e93
WIP: Fix session_logic test
MadsSR Dec 5, 2023
4d1ff18
Merge main
MadsSR Dec 6, 2023
6d22df0
Merge branch 'main' into GetUsers
MadsSR Dec 6, 2023
285136a
Add session_logic tests
MadsSR Dec 6, 2023
9cf4f53
Add repo-token to Install Protoc step to prevent rate limit
MadsSR Dec 6, 2023
71a8a0b
Add repo-token to Install Protoc step to prevent rate limit
MadsSR Dec 6, 2023
18a598a
Merge main
MadsSR Dec 6, 2023
d1ab0b1
Merge branch 'main' into GetUsers
MadsSR Dec 6, 2023
6399e23
Merge main
MadsSR Dec 6, 2023
1a7afbe
Add delete_by_token CRUD to session_context
MadsSR Dec 6, 2023
0dd0677
fix: Delete session when token is expired
MadsSR Dec 6, 2023
a1c30db
Fix TokenError
MadsSR Dec 6, 2023
2c2d70b
Organize functions
MadsSR Dec 6, 2023
bbffbec
Add comments to functions
MadsSR Dec 6, 2023
1429c54
fmt
MadsSR Dec 6, 2023
a26bd10
Merge branch 'main' into GetAccessList
sabotack Dec 6, 2023
6af2fc8
cargo fmt
sabotack Dec 6, 2023
38f85bd
Merge main
MadsSR Dec 6, 2023
26d1c7d
Merge main
MadsSR Dec 6, 2023
37eef9a
Fix imports
MadsSR Dec 6, 2023
967f0b9
Update submod
MadsSR Dec 6, 2023
7ca1f14
Merge branch 'main' into GetAccessList
sabotack Dec 6, 2023
6afc59e
Merge GetAccessList
MadsSR Dec 6, 2023
47808cd
Fixed import typo
williamwoldum Dec 6, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ jobs:
submodules: true
- name: Install Protoc
uses: arduino/setup-protoc@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- uses: Swatinem/rust-cache@v2
with:
cache-on-failure: true
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/check_format.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ jobs:
steps:
- name: Install Protoc
uses: arduino/setup-protoc@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/checkout@v3
with:
submodules: 'true'
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ jobs:

- name: Install dependencies
uses: arduino/setup-protoc@v2

with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- uses: Swatinem/rust-cache@v2
with:
cache-on-failure: true
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ regex = "1.10.2"
mockall = "0.11.4"
bcrypt = "0.15.0"
serde_json = "1.0.108"
thiserror = "1.0.50"

[build-dependencies]
tonic-build = "0.10.2"
Expand Down
2 changes: 1 addition & 1 deletion Ecdar-ProtoBuf
Submodule Ecdar-ProtoBuf updated 2 files
+33 −1 api.proto
+9 −0 services.proto
118 changes: 65 additions & 53 deletions src/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@

/// 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() {
Some(token) => Token::from_str(TokenType::AccessToken, &token),
let token = match req.token_str() {
Some(token) => Token::from_str(TokenType::AccessToken, token),
None => return Err(Status::unauthenticated("Token not found")),
};

Expand Down Expand Up @@ -75,6 +75,7 @@
/// assert_eq!(token.token_type(), TokenType::AccessToken);
/// assert_eq!(token.to_string(), token.as_str());
/// ```
#[derive(Debug)]
pub struct Token {
token_type: TokenType,
token: String,
Expand Down Expand Up @@ -115,6 +116,41 @@

Ok(Token { token_type, token })
}

/// Creates a new refresh token.
///
/// # Arguments
/// * `uid` - The user id to create the token for.
///
/// # Examples
/// ```
/// use ecdar_api::api::auth::{Token, TokenType};
///
/// let refresh_token = Token::refresh("1").unwrap();
///
/// assert_eq!(refresh_token.token_type(), TokenType::RefreshToken);
/// ```
pub fn refresh(uid: &str) -> Result<Token, TokenError> {
Token::new(TokenType::RefreshToken, uid)
}

/// Creates a new access token.
///
/// # Arguments
/// * `uid` - The user id to create the token for.
///
/// # Examples
/// ```
/// use ecdar_api::api::auth::{Token, TokenType};
///
/// let access_token = Token::access("1").unwrap();
///
/// assert_eq!(access_token.token_type(), TokenType::AccessToken);
/// ```
pub fn access(uid: &str) -> Result<Token, TokenError> {
Token::new(TokenType::AccessToken, uid)
}

/// Create a token from a string.
///
/// # Arguments
Expand All @@ -125,7 +161,7 @@
/// ```
/// use ecdar_api::api::auth::{Token, TokenType};
///
/// let token = Token::from_str(TokenType::AccessToken, "token").unwrap();
/// let token = Token::from_str(TokenType::AccessToken, "token")
/// ```
pub fn from_str(token_type: TokenType, token: &str) -> Token {
Token {
Expand Down Expand Up @@ -158,23 +194,16 @@
Err(err) => Err(err.into()),
}
}

/// Returns the token as a string.
// pub fn to_string(&self) -> String {
// self.token.clone()
// }
/// Extracts the token as a string slice.
///
/// # Examples
///
/// ```
/// use ecdar_api::api::auth::{Token, TokenType};
///
/// let token = Token::new(TokenType::AccessToken, "1").unwrap();
/// let token = Token::from_str(TokenType::AccessToken, "token");
///
/// assert_eq!(token.as_str(), "token");
/// ```
pub fn as_str(&self) -> &str {

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

View workflow job for this annotation

GitHub Actions / Clippy lint and check

methods `as_str` and `token_type` are never used

warning: methods `as_str` and `token_type` are never used --> src/api/auth.rs:206:12 | 84 | impl Token { | ---------- methods in this implementation ... 206 | pub fn as_str(&self) -> &str { | ^^^^^^ ... 220 | pub fn token_type(&self) -> TokenType { | ^^^^^^^^^^ | = note: `#[warn(dead_code)]` on by default
&self.token
}
/// Returns the token type.
Expand All @@ -199,46 +228,38 @@
}
}

#[derive(Debug)]
#[derive(Debug, PartialEq, thiserror::Error)]
pub enum TokenError {
#[error("Invalid token")]
InvalidToken,
#[error("Invalid signature")]
InvalidSignature,
#[error("Expired signature")]
ExpiredSignature,
Custom(String),
}

/// This is used to get the token error as a string.
impl Display for TokenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TokenError::InvalidToken => write!(f, "Invalid token"),
TokenError::InvalidSignature => write!(f, "Invalid signature"),
TokenError::ExpiredSignature => write!(f, "Expired signature"),
TokenError::Custom(message) => write!(f, "{}", message),
}
}
#[error("{0}")]
Unknown(String),
}

/// This is used to convert the jsonwebtoken error kind to a [TokenError].
/// This is used to convert a [jsonwebtoken::errors::ErrorKind] to a [TokenError].
impl From<jsonwebtoken::errors::ErrorKind> for TokenError {
fn from(error: jsonwebtoken::errors::ErrorKind) -> Self {
match error {
fn from(error_kind: jsonwebtoken::errors::ErrorKind) -> Self {
match error_kind {
jsonwebtoken::errors::ErrorKind::InvalidToken => TokenError::InvalidToken,
jsonwebtoken::errors::ErrorKind::InvalidSignature => TokenError::InvalidSignature,
jsonwebtoken::errors::ErrorKind::ExpiredSignature => TokenError::ExpiredSignature,
_ => TokenError::Custom("Failed to validate token".to_string()),
_ => TokenError::Unknown("Unknown token error".to_string()),
}
}
}

/// This is used to convert the jsonwebtoken error to a [TokenError].
/// This is used to convert a [jsonwebtoken::errors::Error] to a [TokenError].
impl From<jsonwebtoken::errors::Error> for TokenError {
fn from(error: jsonwebtoken::errors::Error) -> Self {
TokenError::from(error.kind().clone())
}
}

/// This is used to convert the [TokenError] to a [Status].
/// This is used to convert a [TokenError] to a [Status].
impl From<TokenError> for Status {
fn from(error: TokenError) -> Self {
Status::unauthenticated(error.to_string())
Expand All @@ -248,39 +269,30 @@
/// 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) -> Option<String>;
fn uid(&self) -> Option<i32>;
}

impl<T> RequestExt for Request<T> {
/// Returns the token string from the request metadata.
fn token_string(&self) -> Option<String> {
self.metadata().get("authorization").map(|token| {
token
.to_str()
.unwrap()
.trim_start_matches("Bearer ")
.to_string()
})
}
/// Returns the token string slice from the request metadata.
fn token_str(&self) -> Option<&str> {
match self.metadata().get("authorization") {
Some(token) => Some(token.to_str().unwrap().trim_start_matches("Bearer ")),
None => None,
}
self.metadata()
.get("authorization")
.and_then(|token| token.to_str().ok())
.map(|token_str| token_str.trim_start_matches("Bearer "))
}

/// Returns the token string from the request metadata.
fn token_string(&self) -> Option<String> {
self.token_str().map(String::from)
}
/// Returns the uid from the request metadata.
fn uid(&self) -> Option<i32> {
let uid = match self.metadata().get("uid").unwrap().to_str() {
Ok(uid) => uid,
Err(_) => return None,
};

Some(uid.parse().unwrap())
self.metadata()
.get("uid")
.and_then(|uid| uid.to_str().ok())
.and_then(|uid_str| uid_str.parse().ok())
}
}

Expand Down
Loading
Loading