surrealdb_core/iam/
issue.rs

1use crate::err::Error;
2use crate::sql::duration::Duration;
3use crate::sql::Algorithm;
4use chrono::Duration as ChronoDuration;
5use chrono::Utc;
6use jsonwebtoken::EncodingKey;
7
8pub(crate) fn config(alg: Algorithm, key: &str) -> Result<EncodingKey, Error> {
9	match alg {
10		Algorithm::Hs256 => Ok(EncodingKey::from_secret(key.as_ref())),
11		Algorithm::Hs384 => Ok(EncodingKey::from_secret(key.as_ref())),
12		Algorithm::Hs512 => Ok(EncodingKey::from_secret(key.as_ref())),
13		Algorithm::EdDSA => Ok(EncodingKey::from_ed_pem(key.as_ref())?),
14		Algorithm::Es256 => Ok(EncodingKey::from_ec_pem(key.as_ref())?),
15		Algorithm::Es384 => Ok(EncodingKey::from_ec_pem(key.as_ref())?),
16		Algorithm::Es512 => Ok(EncodingKey::from_ec_pem(key.as_ref())?),
17		Algorithm::Ps256 => Ok(EncodingKey::from_rsa_pem(key.as_ref())?),
18		Algorithm::Ps384 => Ok(EncodingKey::from_rsa_pem(key.as_ref())?),
19		Algorithm::Ps512 => Ok(EncodingKey::from_rsa_pem(key.as_ref())?),
20		Algorithm::Rs256 => Ok(EncodingKey::from_rsa_pem(key.as_ref())?),
21		Algorithm::Rs384 => Ok(EncodingKey::from_rsa_pem(key.as_ref())?),
22		Algorithm::Rs512 => Ok(EncodingKey::from_rsa_pem(key.as_ref())?),
23	}
24}
25
26pub(crate) fn expiration(d: Option<Duration>) -> Result<Option<i64>, Error> {
27	let exp = match d {
28		Some(v) => {
29			// The defined duration must be valid
30			match ChronoDuration::from_std(v.0) {
31				// The resulting expiration must be valid
32				Ok(d) => match Utc::now().checked_add_signed(d) {
33					Some(exp) => Some(exp.timestamp()),
34					None => return Err(Error::AccessInvalidExpiration),
35				},
36				Err(_) => return Err(Error::AccessInvalidDuration),
37			}
38		}
39		_ => None,
40	};
41
42	Ok(exp)
43}