summaryrefslogtreecommitdiff
path: root/server/src/models/auth.rs
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2022-08-23 18:10:18 +0200
committerSanto Cariotti <santo@dcariotti.me>2022-08-23 18:10:18 +0200
commiteedc536c23c3230c6ebeac8b495b2cfef0317830 (patch)
tree198007257cfa195c410c28b0a576f46fb8870ab9 /server/src/models/auth.rs
parent0dace9fb82953cc91e6d603c4c9970631ac036ad (diff)
Auth login
Diffstat (limited to 'server/src/models/auth.rs')
-rw-r--r--server/src/models/auth.rs63
1 files changed, 63 insertions, 0 deletions
diff --git a/server/src/models/auth.rs b/server/src/models/auth.rs
new file mode 100644
index 0000000..03b198b
--- /dev/null
+++ b/server/src/models/auth.rs
@@ -0,0 +1,63 @@
+use crate::errors::AppError;
+use chrono::{Duration, Local};
+use jsonwebtoken::{encode, DecodingKey, EncodingKey, Header, Validation};
+use once_cell::sync::Lazy;
+use serde::{Deserialize, Serialize};
+
+struct Keys {
+ encoding: EncodingKey,
+ decoding: DecodingKey,
+}
+
+#[derive(Serialize, Deserialize)]
+pub struct Claims {
+ user_id: i32,
+ exp: usize,
+}
+
+#[derive(Serialize)]
+pub struct AuthBody {
+ access_token: String,
+ token_type: String,
+}
+
+static KEYS: Lazy<Keys> = Lazy::new(|| {
+ let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set");
+ Keys::new(secret.as_bytes())
+});
+
+impl Keys {
+ fn new(secret: &[u8]) -> Self {
+ Self {
+ encoding: EncodingKey::from_secret(secret),
+ decoding: DecodingKey::from_secret(secret),
+ }
+ }
+}
+
+impl Claims {
+ pub fn new(user_id: i32) -> Self {
+ let expiration = Local::now() + Duration::days(2);
+
+ Self {
+ user_id,
+ exp: expiration.timestamp() as usize,
+ }
+ }
+
+ pub fn get_token(&self) -> Result<String, AppError> {
+ let token = encode(&Header::default(), &self, &KEYS.encoding)
+ .map_err(|_| AppError::TokenCreation)?;
+
+ Ok(token)
+ }
+}
+
+impl AuthBody {
+ pub fn new(access_token: String) -> Self {
+ Self {
+ access_token,
+ token_type: "Bearer".to_string(),
+ }
+ }
+}