|
1 | 1 | use crate::{ |
2 | | - domain::authorization::{self, LoginToken, get_or_create_user_from_tmc_mooc_fi_response}, |
| 2 | + domain::authorization::{self, get_or_create_user_from_tmc_mooc_fi_response}, |
3 | 3 | prelude::*, |
4 | 4 | }; |
5 | 5 | use actix_web::{FromRequest, http::header}; |
6 | 6 | use futures_util::{FutureExt, future::LocalBoxFuture}; |
7 | 7 | use headless_lms_utils::{cache::Cache, tmc::TmcClient}; |
8 | 8 | use models::users::User; |
9 | | -use oauth2::TokenResponse; |
| 9 | +use secrecy::{ExposeSecret, SecretString}; |
10 | 10 | use std::ops::{Deref, DerefMut}; |
11 | 11 | use std::time::Duration; |
12 | 12 |
|
@@ -48,7 +48,8 @@ impl FromRequest for UserFromTMCAccessToken { |
48 | 48 | .headers() |
49 | 49 | .get(header::AUTHORIZATION) |
50 | 50 | .map(|hv| String::from_utf8_lossy(hv.as_bytes())) |
51 | | - .and_then(|h| h.strip_prefix("Bearer ").map(str::to_string)); |
| 51 | + .and_then(|h| h.strip_prefix("Bearer ").map(str::to_string)) |
| 52 | + .map(|o| SecretString::new(o.into())); |
52 | 53 |
|
53 | 54 | let tmc_client: web::Data<TmcClient> = req |
54 | 55 | .app_data::<web::Data<TmcClient>>() |
@@ -79,15 +80,8 @@ impl FromRequest for UserFromTMCAccessToken { |
79 | 80 | match load_user(&cache, &token).await { |
80 | 81 | Some(user) => user, |
81 | 82 | None => { |
82 | | - let token = LoginToken::new( |
83 | | - oauth2::AccessToken::new(token), |
84 | | - oauth2::basic::BasicTokenType::Bearer, |
85 | | - oauth2::EmptyExtraTokenFields {}, |
86 | | - ); |
87 | 83 | let tmc_user = tmc_client |
88 | | - .get_user_from_tmc_mooc_fi_by_tmc_access_token( |
89 | | - token.access_token().secret(), |
90 | | - ) |
| 84 | + .get_user_from_tmc_mooc_fi_by_tmc_access_token(token.clone()) |
91 | 85 | .await?; |
92 | 86 |
|
93 | 87 | debug!( |
@@ -126,16 +120,22 @@ struct TmcUser { |
126 | 120 | administrator: bool, |
127 | 121 | } |
128 | 122 |
|
129 | | -pub async fn cache_user(cache: &Cache, token: &LoginToken, user: &User) { |
| 123 | +fn token_to_cache_key(token: &SecretString) -> String { |
| 124 | + let mut hasher = blake3::Hasher::new(); |
| 125 | + hasher.update(token.expose_secret().as_bytes()); |
| 126 | + format!("user:{}", hasher.finalize().to_hex()) |
| 127 | +} |
| 128 | + |
| 129 | +pub async fn cache_user(cache: &Cache, token: &SecretString, user: &User) { |
130 | 130 | cache |
131 | 131 | .cache_json( |
132 | | - token.access_token().secret(), |
| 132 | + token_to_cache_key(token), |
133 | 133 | user, |
134 | 134 | Duration::from_secs(60 * 60), |
135 | 135 | ) |
136 | 136 | .await; |
137 | 137 | } |
138 | 138 |
|
139 | | -pub async fn load_user(cache: &Cache, token: &str) -> Option<User> { |
140 | | - cache.get_json(token).await |
| 139 | +pub async fn load_user(cache: &Cache, token: &SecretString) -> Option<User> { |
| 140 | + cache.get_json(token_to_cache_key(token)).await |
141 | 141 | } |
0 commit comments