Skip to content

Commit 51a6bc4

Browse files
committed
Merge remote-tracking branch 'origin/main' into mdabir1203-Main
2 parents 83c597c + f4a5749 commit 51a6bc4

File tree

1 file changed

+52
-52
lines changed
  • Module02/auth_server/src

1 file changed

+52
-52
lines changed

Module02/auth_server/src/jwt.rs

+52-52
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,52 @@
1-
use chrono::{Duration, Utc};
2-
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
3-
use serde::{Deserialize, Serialize};
4-
5-
// Define the Claims struct for JWT
6-
#[derive(Serialize, Deserialize)]
7-
struct Claims {
8-
sub: String,
9-
exp: usize,
10-
}
11-
12-
// Generate a JWT token
13-
pub fn generate_jwt(username: &str) -> String {
14-
let expiration = Utc::now()
15-
.checked_add_signed(Duration::seconds(60))
16-
.expect("valid timestamp")
17-
.timestamp();
18-
19-
let claims = Claims {
20-
sub: username.to_owned(),
21-
exp: expiration as usize,
22-
};
23-
24-
encode(
25-
&Header::default(),
26-
&claims,
27-
&EncodingKey::from_secret("secret".as_ref()),
28-
)
29-
.unwrap()
30-
}
31-
32-
// Validate the JWT token
33-
pub fn jwt_validation(token: &str) -> bool {
34-
let validation = Validation::new(Algorithm::HS256);
35-
let token_data = decode::<Claims>(
36-
token,
37-
&DecodingKey::from_secret("secret".as_ref()),
38-
&validation,
39-
);
40-
token_data.is_ok()
41-
}
42-
43-
#[cfg(test)]
44-
mod tests {
45-
use super::*;
46-
47-
#[test]
48-
fn test_generate_jwt() {
49-
let token = generate_jwt("DragonBall");
50-
assert!(jwt_validation(&token));
51-
}
52-
}
1+
use chrono::{Duration, Utc};
2+
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
3+
use serde::{Deserialize, Serialize};
4+
5+
// Define the Claims struct for JWT
6+
#[derive(Serialize, Deserialize)]
7+
struct Claims {
8+
sub: String,
9+
exp: usize,
10+
}
11+
12+
// Generate a JWT token
13+
pub fn generate_jwt(username: &str) -> String {
14+
let expiration = Utc::now()
15+
.checked_add_signed(Duration::seconds(60))
16+
.expect("valid timestamp")
17+
.timestamp();
18+
19+
let claims = Claims {
20+
sub: username.to_owned(),
21+
exp: expiration as usize,
22+
};
23+
24+
encode(
25+
&Header::default(),
26+
&claims,
27+
&EncodingKey::from_secret("secret".as_ref()),
28+
)
29+
.unwrap()
30+
}
31+
32+
// Validate the JWT token
33+
pub fn jwt_validation(token: &str) -> bool {
34+
let validation = Validation::new(Algorithm::HS256);
35+
let token_data = decode::<Claims>(
36+
token,
37+
&DecodingKey::from_secret("secret".as_ref()),
38+
&validation,
39+
);
40+
token_data.is_ok()
41+
}
42+
43+
#[cfg(test)]
44+
mod tests {
45+
use super::*;
46+
47+
#[test]
48+
fn test_generate_jwt() {
49+
let token = generate_jwt("DragonBall");
50+
assert!(jwt_validation(&token));
51+
}
52+
}

0 commit comments

Comments
 (0)