1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use actix_web::{HttpResponse, ResponseError};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;
use uuid::Uuid;
mod test;
const SECRET: &[u8] = b"my_secret";
#[derive(Debug, Error)]
pub enum TokenError {
#[error("unable to create session token")]
Create,
#[error("unable to verify session token")]
Verify,
}
impl ResponseError for TokenError {
fn error_response(&self) -> HttpResponse {
match self {
TokenError::Create => HttpResponse::InternalServerError().into(),
TokenError::Verify => HttpResponse::Unauthorized().into(),
}
}
}
#[derive(Deserialize, Serialize)]
pub struct Token {
sub: String,
exp: i64,
iat: i64,
jti: String,
}
impl Token {
pub fn create(username: &str) -> Result<String, TokenError> {
const DEFAULT_TOKEN_VALIDITY: i64 = 3600;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| TokenError::Create)?;
let claim = Token {
sub: username.to_owned(),
exp: now.as_secs() as i64 + DEFAULT_TOKEN_VALIDITY,
iat: now.as_secs() as i64,
jti: Uuid::new_v4().to_string(),
};
encode(
&Header::default(),
&claim,
&EncodingKey::from_secret(SECRET),
)
.map_err(|_| TokenError::Create)
}
pub fn verify(token: &str) -> Result<String, TokenError> {
let data = decode::<Token>(
token,
&DecodingKey::from_secret(SECRET),
&Validation::default(),
)
.map_err(|_| TokenError::Verify)?;
Self::create(&data.claims.sub)
}
}