|
1 | | -use anyhow::Result; |
| 1 | +use anyhow::{anyhow, Result}; |
2 | 2 |
|
| 3 | +use redis::{AsyncTypedCommands, SetOptions}; |
3 | 4 | use sea_orm::prelude::*; |
4 | 5 |
|
5 | 6 | use _database::{models, DB_CONN}; |
6 | | -use _utils::types::auth::{OauthAnonymousResponse, OauthLoginResponse}; |
| 7 | +use _utils::{ |
| 8 | + bcrypt::verify_hash, |
| 9 | + jwt::{generate_token, EXPIRED_APPEND_DURATION}, |
| 10 | + types::auth::{OauthAnonymousResponse, OauthLoginResponse, OauthScopeType, OauthTokenType}, |
| 11 | +}; |
7 | 12 |
|
8 | 13 | pub async fn oauth_password_login( |
9 | 14 | username: String, |
10 | 15 | password: String, |
11 | 16 | ) -> Result<OauthLoginResponse> { |
12 | | - let user = models::system::sys_user::Entity::find() |
| 17 | + let item = models::system::sys_user::Entity::find() |
| 18 | + .filter(models::system::sys_user::Column::DelFlag.eq(false)) |
13 | 19 | .filter(models::system::sys_user::Column::Username.eq(username)) |
14 | 20 | .one(&DB_CONN.wait().pg_conn) |
15 | | - .await?; |
| 21 | + .await? |
| 22 | + .ok_or(anyhow!("User not found"))?; |
16 | 23 |
|
17 | | - // Continue with the login logic |
| 24 | + if !verify_hash( |
| 25 | + password, |
| 26 | + item.password |
| 27 | + .strip_prefix("{bcrypt}") |
| 28 | + .ok_or(anyhow!("Failed to strip bcrypt prefix"))?, |
| 29 | + )? { |
| 30 | + return Err(anyhow!("Invalid password")); |
| 31 | + } |
18 | 32 |
|
19 | | - todo!() |
| 33 | + let jti = Uuid::now_v7(); |
| 34 | + let now = chrono::Utc::now(); |
| 35 | + let access_token = generate_token(now, item.id, jti).await?; |
| 36 | + let refresh_token = generate_token(now, item.id, jti).await?; |
| 37 | + |
| 38 | + let mut redis_conn = DB_CONN |
| 39 | + .wait() |
| 40 | + .redis_conn |
| 41 | + .get_multiplexed_async_connection() |
| 42 | + .await?; |
| 43 | + redis_conn |
| 44 | + .set_options( |
| 45 | + format!("jwt:access:{}:{}", item.id, jti), |
| 46 | + &access_token, |
| 47 | + SetOptions::default() |
| 48 | + .conditional_set(redis::ExistenceCheck::NX) |
| 49 | + .with_expiration(redis::SetExpiry::EX( |
| 50 | + EXPIRED_APPEND_DURATION.as_seconds_f32() as u64, |
| 51 | + )), |
| 52 | + ) |
| 53 | + .await?; |
| 54 | + redis_conn |
| 55 | + .set_options( |
| 56 | + format!("jwt:refresh:{}:{}", item.id, jti), |
| 57 | + &refresh_token, |
| 58 | + SetOptions::default() |
| 59 | + .conditional_set(redis::ExistenceCheck::NX) |
| 60 | + .with_expiration(redis::SetExpiry::EX( |
| 61 | + EXPIRED_APPEND_DURATION.as_seconds_f32() as u64, |
| 62 | + )), |
| 63 | + ) |
| 64 | + .await?; |
| 65 | + |
| 66 | + Ok(OauthLoginResponse { |
| 67 | + access_token, |
| 68 | + refresh_token, |
| 69 | + token_type: OauthTokenType::Bearer, |
| 70 | + expires_in: EXPIRED_APPEND_DURATION.as_seconds_f32() as u64, |
| 71 | + scope: OauthScopeType::All, |
| 72 | + jti, |
| 73 | + }) |
20 | 74 | } |
21 | 75 |
|
22 | 76 | pub async fn oauth_client_credentials(scope: String) -> Result<OauthAnonymousResponse> { |
|
0 commit comments