about summary refs log tree commit diff
path: root/kittybox-rs/indieauth/src/scopes.rs
blob: 6d1ed7e1feb7e197a663a32cc89bacfece2d7aca (plain) (blame)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use serde::{
    Serialize, Serializer,
    Deserialize,
    de::{
        Deserializer, Visitor,
        Error as DeserializeError
    }
};

#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Scope {
    /// Allows to create posts using Micropub.
    Create,
    /// Allows to edit posts using Micropub.
    Update,
    /// Allows to delete posts using Micropub.
    Delete,
    /// Allows to upload blobs to the media endpoint.
    Media,
    /// Allows to read feeds via Microsub.
    Read,
    /// Allows to manage follows via Microsub.
    Follow,
    /// Allows to mute and unmute users in feeds via Microsub.
    Mute,
    /// Allows to block and unblock users.
    Block,
    /// Allows to create and manage feeds via Microsub.
    Channels,
    /// Allows to request profile information (except email, see Email)
    Profile,
    /// Allows to receive email in the profile information.
    Email,
    /// Custom scope not included above.
    Custom(String)
}
impl Scope {
    pub fn custom(scope: &str) -> Scope {
        Scope::Custom(scope.to_string())
    }
}
// TODO consider relying on serde for these conversions
impl AsRef<str> for Scope {
    fn as_ref(&self) -> &str {
        use Scope::*;
        match self {
            Create => "create",
            Update => "update",
            Delete => "delete",
            Media => "media",
            Read => "read",
            Follow => "follow",
            Mute => "mute",
            Block => "block",
            Channels => "channels",
            Profile => "profile",
            Email => "email",
            Custom(s) => s.as_ref()
        }
    }
}
impl From<&str> for Scope {
    fn from(scope: &str) -> Self {
        match scope {
            "create"   => Scope::Create,
            "update"   => Scope::Update,
            "delete"   => Scope::Delete,
            "media"    => Scope::Media,
            "read"     => Scope::Read,
            "follow"   => Scope::Follow,
            "mute"     => Scope::Mute,
            "block"    => Scope::Block,
            "channels" => Scope::Channels,
            "profile"  => Scope::Profile,
            "email"    => Scope::Email,
            other      => Scope::custom(other)
        }
    }
}
#[derive(Debug, Clone)]
pub struct Scopes(Vec<Scope>);
impl Scopes {
    pub fn new(scopes: Vec<Scope>) -> Self {
        Self(scopes)
    }
    pub fn has(&self, scope: &Scope) -> bool {
        self.0.iter().any(|s| s == scope)
    }
    pub fn has_all(&self, scopes: &[Scope]) -> bool {
        scopes.iter()
            .map(|s1| scopes.iter().any(|s2| s1 == s2))
            .all(|s| s)
    }
}
impl AsRef<[Scope]> for Scopes {
    fn as_ref(&self) -> &[Scope] {
        self.0.as_ref()
    }
}
impl ToString for Scopes {
    fn to_string(&self) -> String {
        self.0.iter()
            .map(|s| s.as_ref())
            .fold(String::new(), |a, s| if a.is_empty() {
                s.to_string()
            } else {
                a + " " + s
            })
    }
}
impl Serialize for Scopes {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer
    {
        serializer.serialize_str(&self.to_string())
    }
}
struct ScopeVisitor;
impl<'de> Visitor<'de> for ScopeVisitor {
    type Value = Scopes;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a string of space-separated OAuth2 scopes")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: DeserializeError
    {
        Ok(Scopes(value.split_ascii_whitespace()
                  .map(Scope::from)
                  .collect::<Vec<Scope>>()))
    }
}
impl<'de> Deserialize<'de> for Scopes {
    
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>
    {
        deserializer.deserialize_str(ScopeVisitor)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_serde_vec_scope() {
        let scopes = vec![
            Scope::Create, Scope::Update, Scope::Delete,
            Scope::Media,
            Scope::custom("kittybox_internal_access")
        ];

        let scope_serialized = serde_json::to_value(
            Scopes::new(scopes.clone())
        ).unwrap();
        let scope_str = scope_serialized.as_str().unwrap();
        assert_eq!(scope_str, "create update delete media kittybox_internal_access");

        assert!(serde_json::from_value::<Scopes>(scope_serialized).unwrap().has_all(&scopes))
        
    }

}