surrealdb/iam/entities/
roles.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use crate::iam::Error;
use crate::sql::Ident;
use cedar_policy::{Entity, EntityTypeName, EntityUid, RestrictedExpression};
use revision::revisioned;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

// In the future, we will allow for custom roles. For now, provide predefined roles.
#[derive(Hash, Clone, Default, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize)]
#[revisioned(revision = 1)]
pub enum Role {
	#[default]
	Viewer,
	Editor,
	Owner,
}

impl std::fmt::Display for Role {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		match self {
			Self::Viewer => write!(f, "Viewer"),
			Self::Editor => write!(f, "Editor"),
			Self::Owner => write!(f, "Owner"),
		}
	}
}

impl FromStr for Role {
	type Err = Error;
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		match s.to_ascii_lowercase().as_str() {
			"viewer" => Ok(Self::Viewer),
			"editor" => Ok(Self::Editor),
			"owner" => Ok(Self::Owner),
			_ => Err(Error::InvalidRole(s.to_string())),
		}
	}
}

impl std::convert::From<&str> for Role {
	fn from(s: &str) -> Self {
		Self::from_str(s).unwrap()
	}
}

impl std::convert::From<String> for Role {
	fn from(s: String) -> Self {
		Self::from_str(&s).unwrap()
	}
}

impl std::convert::From<&Ident> for Role {
	fn from(id: &Ident) -> Self {
		Role::from_str(id).unwrap()
	}
}

impl std::convert::From<Role> for Ident {
	fn from(role: Role) -> Self {
		role.to_string().into()
	}
}

impl std::convert::From<&Role> for EntityUid {
	fn from(role: &Role) -> Self {
		EntityUid::from_type_name_and_id(
			EntityTypeName::from_str("Role").unwrap(),
			format!("{}", role).parse().unwrap(),
		)
	}
}

impl std::convert::From<&Role> for Entity {
	fn from(role: &Role) -> Self {
		Entity::new(role.into(), Default::default(), Default::default())
	}
}

impl std::convert::From<&Role> for RestrictedExpression {
	fn from(role: &Role) -> Self {
		format!("{}", EntityUid::from(role)).parse().unwrap()
	}
}