40 řádky
1.1 KiB
Rust
Spustitelný soubor
40 řádky
1.1 KiB
Rust
Spustitelný soubor
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::collections::HashSet;
|
|
|
|
use crate::{ctx::Ctx, error::NekrochanError};
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
pub struct Claims {
|
|
pub sub: String,
|
|
}
|
|
|
|
impl Claims {
|
|
pub fn new(sub: String) -> Self {
|
|
Self { sub }
|
|
}
|
|
|
|
pub fn encode(&self, ctx: &Ctx) -> Result<String, NekrochanError> {
|
|
let header = Header::default();
|
|
let key = EncodingKey::from_secret(ctx.cfg.secrets.auth_token.as_bytes());
|
|
|
|
let auth = encode(&header, &self, &key)?;
|
|
|
|
Ok(auth)
|
|
}
|
|
|
|
pub fn decode(ctx: &Ctx, auth: &str) -> Result<Self, NekrochanError> {
|
|
let key = DecodingKey::from_secret(ctx.cfg.secrets.auth_token.as_bytes());
|
|
|
|
let mut validation = Validation::default();
|
|
validation.required_spec_claims = HashSet::from_iter(["sub".to_owned()]);
|
|
validation.validate_exp = false;
|
|
|
|
let claims = decode(auth, &key, &validation)
|
|
.map_err(|_| NekrochanError::InvalidAuthError)?
|
|
.claims;
|
|
|
|
Ok(claims)
|
|
}
|
|
}
|