diff options
| author | Tolmachev Igor <me@igorek.dev> | 2025-09-01 13:32:05 +0300 |
|---|---|---|
| committer | Tolmachev Igor <me@igorek.dev> | 2025-09-01 13:32:05 +0300 |
| commit | b9d75e22db72aabf47815e381aa6432c1bff3877 (patch) | |
| tree | b6b0741461484c36919a3ec74fb075c77e867a59 /src/auth.rs | |
| parent | 56d155ac2de9261575d7fd4671a08b95cd16e6bb (diff) | |
| download | queue_server-b9d75e22db72aabf47815e381aa6432c1bff3877.tar.gz queue_server-b9d75e22db72aabf47815e381aa6432c1bff3877.zip | |
Add account endpoints
Diffstat (limited to 'src/auth.rs')
| -rw-r--r-- | src/auth.rs | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..418f64e --- /dev/null +++ b/src/auth.rs | |||
| @@ -0,0 +1,49 @@ | |||
| 1 | use argon2::password_hash::rand_core::OsRng; | ||
| 2 | use argon2::password_hash::{PasswordHasher, SaltString}; | ||
| 3 | use argon2::{Argon2, PasswordHash, PasswordVerifier}; | ||
| 4 | use jsonwebtoken::{self as jwt, DecodingKey, EncodingKey, Header, Validation}; | ||
| 5 | use serde::{Deserialize, Serialize}; | ||
| 6 | |||
| 7 | #[derive(Serialize, Deserialize)] | ||
| 8 | pub struct JwtClaims { | ||
| 9 | pub sub: i64, | ||
| 10 | pub iat: i64, | ||
| 11 | pub exp: i64, | ||
| 12 | } | ||
| 13 | |||
| 14 | pub fn create_password(password: &str) -> argon2::password_hash::Result<String> { | ||
| 15 | Ok(Argon2::default() | ||
| 16 | .hash_password(password.as_bytes(), &SaltString::generate(&mut OsRng))? | ||
| 17 | .to_string()) | ||
| 18 | } | ||
| 19 | |||
| 20 | pub fn validate_password( | ||
| 21 | password: &str, | ||
| 22 | password_hash: &str, | ||
| 23 | ) -> argon2::password_hash::Result<bool> { | ||
| 24 | Ok(Argon2::default() | ||
| 25 | .verify_password(password.as_bytes(), &PasswordHash::new(password_hash)?) | ||
| 26 | .is_ok()) | ||
| 27 | } | ||
| 28 | |||
| 29 | pub fn create_jwt(claims: &JwtClaims, secret: &str) -> jwt::errors::Result<String> { | ||
| 30 | jwt::encode( | ||
| 31 | &Header::default(), | ||
| 32 | claims, | ||
| 33 | &EncodingKey::from_secret(secret.as_bytes()), | ||
| 34 | ) | ||
| 35 | } | ||
| 36 | |||
| 37 | pub fn validate_jwt(token: &str, secret: &str) -> jwt::errors::Result<JwtClaims> { | ||
| 38 | let mut validation = Validation::default(); | ||
| 39 | validation.set_required_spec_claims(&["exp"]); | ||
| 40 | validation.validate_exp = true; | ||
| 41 | validation.leeway = 0; | ||
| 42 | |||
| 43 | Ok(jwt::decode( | ||
| 44 | token, | ||
| 45 | &DecodingKey::from_secret(secret.as_bytes()), | ||
| 46 | &validation, | ||
| 47 | )? | ||
| 48 | .claims) | ||
| 49 | } | ||
