summaryrefslogtreecommitdiff
path: root/src/auth.rs
diff options
context:
space:
mode:
authorniliara-edu <nil.jimeno@estudiant.fjaverianas.com>2025-01-22 14:10:08 +0100
committerniliara-edu <nil.jimeno@estudiant.fjaverianas.com>2025-01-22 14:10:08 +0100
commit6a7a49fb3804d0d27bbaee08b6feb26b4973b4bc (patch)
tree8a08c15301965bb4ea3bfbab54468e2879db9ad5 /src/auth.rs
parentc277e9937115cc1473219a04199566c7bfdcbaf7 (diff)
prepare for apiHEADmaster
Diffstat (limited to 'src/auth.rs')
-rw-r--r--src/auth.rs53
1 files changed, 53 insertions, 0 deletions
diff --git a/src/auth.rs b/src/auth.rs
new file mode 100644
index 0000000..8bf29f7
--- /dev/null
+++ b/src/auth.rs
@@ -0,0 +1,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())
+}