@@ -9,6 +9,7 @@ use crate::util::errors::{
9
9
account_locked, forbidden, internal, AppError , AppResult , InsecurelyGeneratedTokenRevoked ,
10
10
} ;
11
11
use chrono:: Utc ;
12
+ use diesel:: PgConnection ;
12
13
use http:: header;
13
14
14
15
#[ derive( Debug , Clone ) ]
@@ -152,11 +153,10 @@ impl Authentication {
152
153
}
153
154
}
154
155
155
- fn authenticate_user < T : RequestPartsExt > ( req : & T ) -> AppResult < Authentication > {
156
- controllers:: util:: verify_origin ( req) ?;
157
-
158
- let conn = req. app ( ) . db_write ( ) ?;
159
-
156
+ fn authenticate_via_cookie < T : RequestPartsExt > (
157
+ req : & T ,
158
+ conn : & PgConnection ,
159
+ ) -> AppResult < Option < CookieAuthentication > > {
160
160
let user_id_from_session = req
161
161
. session_get ( "user_id" )
162
162
. and_then ( |s| s. parse :: < i32 > ( ) . ok ( ) ) ;
@@ -169,10 +169,16 @@ fn authenticate_user<T: RequestPartsExt>(req: &T) -> AppResult<Authentication> {
169
169
170
170
req. add_custom_metadata ( "uid" , id) ;
171
171
172
- return Ok ( Authentication :: Cookie ( CookieAuthentication { user } ) ) ;
172
+ return Ok ( Some ( CookieAuthentication { user } ) ) ;
173
173
}
174
174
175
- // Otherwise, look for an `Authorization` header on the request
175
+ return Ok ( None ) ;
176
+ }
177
+
178
+ fn authenticate_via_token < T : RequestPartsExt > (
179
+ req : & T ,
180
+ conn : & PgConnection ,
181
+ ) -> AppResult < Option < TokenAuthentication > > {
176
182
let maybe_authorization = req
177
183
. headers ( )
178
184
. get ( header:: AUTHORIZATION )
@@ -195,7 +201,27 @@ fn authenticate_user<T: RequestPartsExt>(req: &T) -> AppResult<Authentication> {
195
201
req. add_custom_metadata ( "uid" , token. user_id ) ;
196
202
req. add_custom_metadata ( "tokenid" , token. id ) ;
197
203
198
- return Ok ( Authentication :: Token ( TokenAuthentication { user, token } ) ) ;
204
+ return Ok ( Some ( TokenAuthentication { user, token } ) ) ;
205
+ }
206
+
207
+ return Ok ( None ) ;
208
+ }
209
+
210
+ fn authenticate_user < T : RequestPartsExt > ( req : & T ) -> AppResult < Authentication > {
211
+ controllers:: util:: verify_origin ( req) ?;
212
+
213
+ let conn = req. app ( ) . db_write ( ) ?;
214
+
215
+ match authenticate_via_cookie ( req, & conn) {
216
+ Ok ( None ) => { }
217
+ Ok ( Some ( auth) ) => return Ok ( Authentication :: Cookie ( auth) ) ,
218
+ Err ( err) => return Err ( err) ,
219
+ }
220
+
221
+ match authenticate_via_token ( req, & conn) {
222
+ Ok ( None ) => { }
223
+ Ok ( Some ( auth) ) => return Ok ( Authentication :: Token ( auth) ) ,
224
+ Err ( err) => return Err ( err) ,
199
225
}
200
226
201
227
// Unable to authenticate the user
0 commit comments