1use anyhow::{anyhow, Result};
2use hmac::{Hmac, Mac};
3use jwt::SignWithKey;
4use serde::Serialize;
5use sha2::Sha256;
6use std::{
7 ops::Add,
8 time::{Duration, SystemTime, UNIX_EPOCH},
9};
10
11static DEFAULT_TTL: Duration = Duration::from_secs(6 * 60 * 60); // 6 hours
12
13#[derive(Default, Serialize)]
14#[serde(rename_all = "camelCase")]
15struct ClaimGrants<'a> {
16 iss: &'a str,
17 sub: Option<&'a str>,
18 iat: u64,
19 exp: u64,
20 nbf: u64,
21 jwtid: Option<&'a str>,
22 video: VideoGrant<'a>,
23}
24
25#[derive(Default, Serialize)]
26#[serde(rename_all = "camelCase")]
27pub struct VideoGrant<'a> {
28 pub room_create: Option<bool>,
29 pub room_join: Option<bool>,
30 pub room_list: Option<bool>,
31 pub room_record: Option<bool>,
32 pub room_admin: Option<bool>,
33 pub room: Option<&'a str>,
34 pub can_publish: Option<bool>,
35 pub can_subscribe: Option<bool>,
36 pub can_publish_data: Option<bool>,
37 pub hidden: Option<bool>,
38 pub recorder: Option<bool>,
39}
40
41pub fn create(
42 api_key: &str,
43 secret_key: &str,
44 identity: Option<&str>,
45 video_grant: VideoGrant,
46) -> Result<String> {
47 if video_grant.room_join.is_some() && identity.is_none() {
48 Err(anyhow!(
49 "identity is required for room_join grant, but it is none"
50 ))?;
51 }
52
53 let secret_key: Hmac<Sha256> = Hmac::new_from_slice(secret_key.as_bytes())?;
54
55 let now = SystemTime::now();
56
57 let claims = ClaimGrants {
58 iss: api_key,
59 sub: identity,
60 iat: now.duration_since(UNIX_EPOCH).unwrap().as_secs(),
61 exp: now
62 .add(DEFAULT_TTL)
63 .duration_since(UNIX_EPOCH)
64 .unwrap()
65 .as_secs(),
66 nbf: 0,
67 jwtid: identity,
68 video: video_grant,
69 };
70 Ok(claims.sign_with_key(&secret_key)?)
71}