Skip to content

Commit c4b9fce

Browse files
committed
auth: Convert AuthenticatedUser to an enum
1 parent c0d3340 commit c4b9fce

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

src/auth.rs

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -111,26 +111,43 @@ impl AuthCheck {
111111
}
112112

113113
#[derive(Debug)]
114-
pub struct AuthenticatedUser {
114+
pub enum AuthenticatedUser {
115+
Cookie(CookieUser),
116+
Token(TokenUser),
117+
}
118+
119+
#[derive(Debug)]
120+
pub struct CookieUser {
121+
user: User,
122+
}
123+
124+
#[derive(Debug)]
125+
pub struct TokenUser {
126+
token: ApiToken,
115127
user: User,
116-
token: Option<ApiToken>,
117128
}
118129

119130
impl AuthenticatedUser {
120131
pub fn user_id(&self) -> i32 {
121-
self.user.id
132+
self.user().id
122133
}
123134

124135
pub fn api_token_id(&self) -> Option<i32> {
125136
self.api_token().map(|token| token.id)
126137
}
127138

128139
pub fn api_token(&self) -> Option<&ApiToken> {
129-
self.token.as_ref()
140+
match self {
141+
AuthenticatedUser::Token(token) => Some(&token.token),
142+
_ => None,
143+
}
130144
}
131145

132146
pub fn user(&self) -> &User {
133-
&self.user
147+
match self {
148+
AuthenticatedUser::Cookie(cookie) => &cookie.user,
149+
AuthenticatedUser::Token(token) => &token.user,
150+
}
134151
}
135152
}
136153

@@ -151,7 +168,7 @@ fn authenticate_user<B>(req: &Request<B>) -> AppResult<AuthenticatedUser> {
151168

152169
req.add_custom_metadata("uid", id);
153170

154-
return Ok(AuthenticatedUser { user, token: None });
171+
return Ok(AuthenticatedUser::Cookie(CookieUser { user }));
155172
}
156173

157174
// Otherwise, look for an `Authorization` header on the request
@@ -177,10 +194,7 @@ fn authenticate_user<B>(req: &Request<B>) -> AppResult<AuthenticatedUser> {
177194
req.add_custom_metadata("uid", token.user_id);
178195
req.add_custom_metadata("tokenid", token.id);
179196

180-
return Ok(AuthenticatedUser {
181-
user,
182-
token: Some(token),
183-
});
197+
return Ok(AuthenticatedUser::Token(TokenUser { user, token }));
184198
}
185199

186200
// Unable to authenticate the user

0 commit comments

Comments
 (0)