Skip to main content

tuwunel_admin/debug/
create_jwt.rs

1use serde::Serialize;
2use tuwunel_core::{
3	Result, err,
4	jwt::{Header, encode},
5	utils::time::now_secs,
6};
7
8use crate::admin_command;
9
10#[admin_command]
11pub(super) async fn create_jwt(
12	&self,
13	user: String,
14	exp_from_now: Option<u64>,
15	nbf_from_now: Option<u64>,
16	issuer: Option<String>,
17	audience: Option<String>,
18) -> Result {
19	#[derive(Serialize)]
20	struct Claim {
21		sub: String,
22		iss: Option<String>,
23		aud: Option<String>,
24		exp: Option<usize>,
25		nbf: Option<usize>,
26	}
27
28	let config = &self.services.config.jwt;
29	let key = config.encoding_key()?;
30	let alg = config.algorithm()?;
31
32	let header = Header { alg, ..Default::default() };
33	let claim = Claim {
34		sub: user,
35
36		iss: issuer,
37
38		aud: audience,
39
40		exp: exp_from_now
41			.and_then(|val| now_secs().checked_add(val))
42			.map(TryInto::try_into)
43			.and_then(Result::ok),
44
45		nbf: nbf_from_now
46			.and_then(|val| now_secs().checked_add(val))
47			.map(TryInto::try_into)
48			.and_then(Result::ok),
49	};
50
51	encode(&header, &claim, &key)
52		.map_err(|e| err!("Failed to encode JWT: {e}"))
53		.map(async |token| self.write_str(&token).await)?
54		.await
55}