77 lines
2.2 KiB
Rust
77 lines
2.2 KiB
Rust
use serde::{Deserialize, Serialize};
|
|
use std::fmt;
|
|
|
|
lazy_static! {
|
|
static ref ENCODING_KEY: jsonwebtoken::EncodingKey =
|
|
jsonwebtoken::EncodingKey::from_rsa_pem(include_bytes!("../../resources/private.pem"))
|
|
.expect("ENCODING_KEY");
|
|
static ref DECODING_KEY: jsonwebtoken::DecodingKey =
|
|
jsonwebtoken::DecodingKey::from_rsa_pem(include_bytes!("../../resources/public.pem"))
|
|
.expect("DECODING_KEY");
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum Error {
|
|
Encoding(String),
|
|
Decoding(String),
|
|
}
|
|
|
|
impl std::error::Error for Error {}
|
|
|
|
impl fmt::Display for Error {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
match self {
|
|
Error::Encoding(e) => write!(f, "Encoding Error: {}", e),
|
|
Error::Decoding(e) => write!(f, "Decoding Error: {}", e),
|
|
}
|
|
}
|
|
}
|
|
|
|
// #[derive(Debug, Serialize, Deserialize)]
|
|
// struct Claims {
|
|
// aud: String, // Optional. Audience
|
|
// exp: usize, // Required (validate_exp defaults to true in validation). Expiration time (as UTC timestamp)
|
|
// iat: usize, // Optional. Issued at (as UTC timestamp)
|
|
// iss: String, // Optional. Issuer
|
|
// nbf: usize, // Optional. Not Before (as UTC timestamp)
|
|
// sub: String, // Optional. Subject (whom token refers to)
|
|
// }
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
pub struct Claims {
|
|
pub iss: String,
|
|
pub iat: i64,
|
|
pub exp: i64,
|
|
pub session_id: String,
|
|
}
|
|
|
|
pub fn encode(issuer: &str, session_id: &str) -> Result<String, Error> {
|
|
use jsonwebtoken::{encode, Algorithm, Header};
|
|
|
|
let header = Header::new(Algorithm::RS256);
|
|
|
|
let issued_at = (chrono::Utc::now()).timestamp();
|
|
let expiration_at = (chrono::Utc::now() + chrono::Duration::days(1)).timestamp();
|
|
|
|
let claims = Claims {
|
|
iss: issuer.to_string(),
|
|
iat: issued_at,
|
|
exp: expiration_at,
|
|
session_id: session_id.to_string(),
|
|
};
|
|
|
|
let token =
|
|
encode(&header, &claims, &ENCODING_KEY).map_err(|e| Error::Encoding(e.to_string()))?;
|
|
|
|
Ok(token)
|
|
}
|
|
|
|
pub fn decode(token: &str) -> Result<Claims, Error> {
|
|
use jsonwebtoken::{decode, Algorithm, Validation};
|
|
|
|
let token_data = decode::<Claims>(token, &DECODING_KEY, &Validation::new(Algorithm::RS256))
|
|
.map_err(|e| Error::Decoding(e.to_string()))?;
|
|
|
|
Ok(token_data.claims)
|
|
}
|