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
|
use actix_web::{web, Scope, HttpResponse};
use serde::{Serialize, Deserialize};
use chrono::{Utc, Duration};
use jsonwebtoken::{encode, EncodingKey, Header};
use crate::AppState;
pub fn auth_scope() -> Scope {
web::scope("/auth")
.route("/encode-token/{id}", web::get().to(encode_token))
.route("/decode-token", web::post().to(decode_token))
.route("/protected", web::get().to(protected))
}
#[derive(Serialize, Deserialize)]
struct Claims{
id: usize,
exp: usize,
}
#[derive(Serialize, Deserialize)]
struct Response{
message: String,
}
#[derive(Serialize, Deserialize)]
struct EncodeResponse{
message: String,
token: String,
}
async fn encode_token(path: web::Path<usize>, data: web::Data<AppState>) -> HttpResponse {
let id: usize = path.into_inner();
let exp: usize = (Utc::now() + Duration::days(365)).timestamp() as usize;
let claims: Claims = Claims {id, exp};
let token: String = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(data.secret.as_str().as_ref()),
).unwrap();
HttpResponse::Ok().json(EncodeResponse {
message: "success".to_owned(),
token: token.to_owned(),
})
}
async fn decode_token() -> HttpResponse {
HttpResponse::Ok().body("decode_token\n".to_owned())
}
async fn protected() -> HttpResponse {
HttpResponse::Ok().body("protected\n".to_owned())
}
|