2022-10-14 16:00:50 +00:00
|
|
|
use anyhow::{anyhow, Result};
|
2022-10-14 15:00:38 +00:00
|
|
|
use hmac::{Hmac, Mac};
|
|
|
|
use jwt::SignWithKey;
|
|
|
|
use serde::Serialize;
|
|
|
|
use sha2::Sha256;
|
|
|
|
use std::{
|
|
|
|
ops::Add,
|
|
|
|
time::{Duration, SystemTime, UNIX_EPOCH},
|
|
|
|
};
|
|
|
|
|
|
|
|
static DEFAULT_TTL: Duration = Duration::from_secs(6 * 60 * 60); // 6 hours
|
|
|
|
|
|
|
|
#[derive(Default, Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct ClaimGrants<'a> {
|
|
|
|
iss: &'a str,
|
2022-10-14 16:00:50 +00:00
|
|
|
sub: Option<&'a str>,
|
2022-10-14 15:00:38 +00:00
|
|
|
iat: u64,
|
|
|
|
exp: u64,
|
|
|
|
nbf: u64,
|
2022-10-14 16:00:50 +00:00
|
|
|
jwtid: Option<&'a str>,
|
2022-10-14 15:00:38 +00:00
|
|
|
video: VideoGrant<'a>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Default, Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2022-10-14 16:00:50 +00:00
|
|
|
pub struct VideoGrant<'a> {
|
|
|
|
pub room_create: Option<bool>,
|
|
|
|
pub room_join: Option<bool>,
|
|
|
|
pub room_list: Option<bool>,
|
|
|
|
pub room_record: Option<bool>,
|
|
|
|
pub room_admin: Option<bool>,
|
|
|
|
pub room: Option<&'a str>,
|
|
|
|
pub can_publish: Option<bool>,
|
|
|
|
pub can_subscribe: Option<bool>,
|
|
|
|
pub can_publish_data: Option<bool>,
|
|
|
|
pub hidden: Option<bool>,
|
|
|
|
pub recorder: Option<bool>,
|
2022-10-14 15:00:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn create(
|
|
|
|
api_key: &str,
|
|
|
|
secret_key: &str,
|
2022-10-14 16:00:50 +00:00
|
|
|
identity: Option<&str>,
|
|
|
|
video_grant: VideoGrant,
|
2022-10-14 15:00:38 +00:00
|
|
|
) -> Result<String> {
|
2022-10-14 16:00:50 +00:00
|
|
|
if video_grant.room_join.is_some() && identity.is_none() {
|
|
|
|
Err(anyhow!(
|
|
|
|
"identity is required for room_join grant, but it is none"
|
|
|
|
))?;
|
|
|
|
}
|
|
|
|
|
2022-10-14 15:00:38 +00:00
|
|
|
let secret_key: Hmac<Sha256> = Hmac::new_from_slice(secret_key.as_bytes())?;
|
|
|
|
|
|
|
|
let now = SystemTime::now();
|
|
|
|
|
|
|
|
let claims = ClaimGrants {
|
|
|
|
iss: api_key,
|
2022-10-14 16:00:50 +00:00
|
|
|
sub: identity,
|
2022-10-14 15:00:38 +00:00
|
|
|
iat: now.duration_since(UNIX_EPOCH).unwrap().as_secs(),
|
|
|
|
exp: now
|
|
|
|
.add(DEFAULT_TTL)
|
|
|
|
.duration_since(UNIX_EPOCH)
|
|
|
|
.unwrap()
|
|
|
|
.as_secs(),
|
|
|
|
nbf: 0,
|
2022-10-14 16:00:50 +00:00
|
|
|
jwtid: identity,
|
|
|
|
video: video_grant,
|
2022-10-14 15:00:38 +00:00
|
|
|
};
|
|
|
|
Ok(claims.sign_with_key(&secret_key)?)
|
|
|
|
}
|