Add JWT signing and verification
This commit is contained in:
parent
1bcbd9d2ff
commit
37cf254c35
1 changed files with 35 additions and 0 deletions
35
src/auth/jwt.rs
Normal file
35
src/auth/jwt.rs
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Claims {
|
||||||
|
pub sub: String, // user id
|
||||||
|
pub exp: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sign(user_id: &str) -> anyhow::Result<String> {
|
||||||
|
let secret = env::var("JWT_SECRET")?;
|
||||||
|
let expiry: usize = env::var("JWT_EXPIRY_SECS")
|
||||||
|
.unwrap_or("3600".into())
|
||||||
|
.parse()?;
|
||||||
|
let now = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)?
|
||||||
|
.as_secs() as usize;
|
||||||
|
let claims = Claims { sub: user_id.to_owned(), exp: now + expiry };
|
||||||
|
Ok(encode(
|
||||||
|
&Header::default(),
|
||||||
|
&claims,
|
||||||
|
&EncodingKey::from_secret(secret.as_bytes()),
|
||||||
|
)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify(token: &str) -> anyhow::Result<Claims> {
|
||||||
|
let secret = env::var("JWT_SECRET")?;
|
||||||
|
let data = decode::<Claims>(
|
||||||
|
token,
|
||||||
|
&DecodingKey::from_secret(secret.as_bytes()),
|
||||||
|
&Validation::default(),
|
||||||
|
)?;
|
||||||
|
Ok(data.claims)
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue