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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
use std::convert::TryFrom;
use std::fmt;

#[derive(PartialEq, Eq, Debug, Hash, Clone, Serialize, Deserialize)]
pub enum Platform {
    Twitch,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum InvalidIrcMessageError<'a> {
    MissingTags(&'a irc_rust::Message),
    MissingUserId(&'a irc_rust::Message),
    MissingPrefix(&'a irc_rust::Message),
}

impl fmt::Display for InvalidIrcMessageError<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InvalidIrcMessageError::MissingTags(msg) => {
                write!(f, "Missing Tags in IRC message: {}", msg)
            }
            InvalidIrcMessageError::MissingUserId(msg) => {
                write!(f, "Missing Tag 'user-id' in IRC tags of message: {}", msg)
            }
            InvalidIrcMessageError::MissingPrefix(msg) => {
                write!(f, "Missing prefix in IRC message: {}", msg)
            }
        }
    }
}

/// Generic enum for storing userinfo. Contains platform local information and
/// creates an API to access these data in a unified and platform independent way.
///
/// Can be created directly but should be derived with its [From] and [TryFrom] implementations.
/// Implements [From] for some api data structs if `features = ["twitch-api"]` is enabled.
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize, Hash)]
pub enum UserInfo {
    Twitch { name: String, id: String },
    None,
}

impl UserInfo {
    /// Returns the Name of the user on the corresponding platform.
    pub fn get_platform_name(&self) -> Option<&String> {
        match self {
            UserInfo::Twitch { name: login, .. } => Some(login),
            UserInfo::None => None,
        }
    }

    /// Returns the id of the user on the corresponding platform.
    pub fn get_platform_id(&self) -> Option<&String> {
        match self {
            UserInfo::Twitch { id: user_id, .. } => Some(user_id),
            UserInfo::None => None,
        }
    }

    /// Transforms the [UserInfo] to a unique id over all platforms.
    pub fn to_global_id(&self) -> String {
        match self {
            UserInfo::Twitch { id: user_id, .. } => format!("twitch#{}", user_id),
            UserInfo::None => String::new(),
        }
    }
}

#[cfg(feature = "twitch-api")]
impl From<crate::twitch_api::users::UserRes> for UserInfo {
    fn from(res: crate::twitch_api::users::UserRes) -> Self {
        let username = if res.display_name.is_empty() {
            res.name
        } else {
            res.display_name
        };
        UserInfo::Twitch {
            name: username,
            id: res.id,
        }
    }
}

#[cfg(feature = "twitch-api")]
impl From<&crate::twitch_api::users::UserRes> for UserInfo {
    fn from(res: &crate::twitch_api::users::UserRes) -> Self {
        let username = if res.display_name.is_empty() {
            &res.name
        } else {
            &res.display_name
        };
        UserInfo::Twitch {
            name: username.clone(),
            id: res.id.clone(),
        }
    }
}

impl<'a> TryFrom<&'a irc_rust::Message> for UserInfo {
    type Error = InvalidIrcMessageError<'a>;

    fn try_from(irc_message: &'a irc_rust::Message) -> Result<Self, Self::Error> {
        let tags = irc_message
            .tags()
            .expect("invalid irc message")
            .ok_or(InvalidIrcMessageError::MissingTags(irc_message))?;

        let user_id = tags
            .get("user-id")
            .map(|id| id.to_string())
            .ok_or(InvalidIrcMessageError::MissingUserId(irc_message))?;

        let username = tags
            .get("display-name")
            .map(|display_name| display_name.to_string());
        let username = match username {
            None => irc_message
                .prefix()
                .expect("invalid irc message")
                .map(|prefix| prefix.name().to_string())
                .ok_or(InvalidIrcMessageError::MissingPrefix(irc_message))?,
            Some(username) => username,
        };

        Ok(UserInfo::Twitch {
            name: username,
            id: user_id,
        })
    }
}

/// Platform independent Credentials enum.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize, Hash, Ord, PartialOrd)]
pub enum Credentials {
    OAuthToken { token: String },
    None,
}

impl fmt::Display for Credentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Credentials::OAuthToken { token } => write!(f, "oauth:{}", token),
            Credentials::None => write!(f, "NONE"),
        }
    }
}

impl<S> From<S> for Credentials
where
    S: AsRef<str>,
{
    fn from(t: S) -> Self {
        let s_t = t.as_ref();
        if let Some(token) = s_t.strip_prefix("oauth:") {
            Credentials::OAuthToken {
                token: token.to_string(),
            }
        } else {
            panic!("token has no supported format: {}", s_t)
        }
    }
}

#[derive(Debug)]
pub enum ValidationError {
    Invalid,
    BadClientId,
}

#[async_trait]
pub trait Authenticator {
    async fn authenticate(&self) -> Credentials;
    async fn validate(&self, cred: &Credentials) -> Result<UserInfo, ValidationError>;
}

#[cfg(test)]
mod tests {
    use crate::auth::Credentials;

    #[test]
    fn test_credentials_from_str() {
        assert_eq!(
            Credentials::OAuthToken {
                token: "thisisatoken".to_string()
            }
            .to_string(),
            "oauth:thisisatoken"
        );
        assert_eq!(
            Credentials::from("oauth:thisisatoken"),
            Credentials::OAuthToken {
                token: "thisisatoken".to_string()
            }
        );
    }

    mod userinfo {
        use crate::auth::{InvalidIrcMessageError, UserInfo};
        use std::convert::TryFrom;

        #[test]
        fn test_platform_name() {
            let userinfo = UserInfo::Twitch {
                name: "name".to_string(),
                id: "id".to_string(),
            };
            assert_eq!(userinfo.get_platform_name(), Some(&"name".to_string()));
        }

        #[test]
        fn test_platform_id() {
            let userinfo = UserInfo::Twitch {
                name: "name".to_string(),
                id: "id".to_string(),
            };
            assert_eq!(userinfo.get_platform_id(), Some(&"id".to_string()));
        }

        #[test]
        fn test_irc_no_tags() {
            let no_tags_message = irc_rust::Message::builder("PRIVMSG").build();
            let result = UserInfo::try_from(&no_tags_message);
            assert_eq!(
                result,
                Err(InvalidIrcMessageError::MissingTags(&no_tags_message))
            );
        }

        #[test]
        fn test_irc_no_userid() {
            let no_user_id = irc_rust::Message::builder("PRIVMSG")
                .tag("id", "messageid1")
                .build();
            let result = UserInfo::try_from(&no_user_id);
            assert_eq!(
                result,
                Err(InvalidIrcMessageError::MissingUserId(&no_user_id))
            );
        }

        #[test]
        fn test_irc_no_prefix() {
            let no_user_id = irc_rust::Message::builder("PRIVMSG")
                .tag("user-id", "userid1")
                .build();
            let result = UserInfo::try_from(&no_user_id);
            assert_eq!(
                result,
                Err(InvalidIrcMessageError::MissingPrefix(&no_user_id))
            );
        }

        #[test]
        fn test_irc_with_prefix() {
            let no_user_id = irc_rust::Message::builder("PRIVMSG")
                .tag("user-id", "userid1")
                .prefix("username", None, None)
                .build();
            let result = UserInfo::try_from(&no_user_id);
            assert_eq!(
                result,
                Ok(UserInfo::Twitch {
                    name: "username".to_string(),
                    id: "userid1".to_string()
                })
            );
        }

        #[test]
        fn test_irc_with_display_name() {
            let no_user_id = irc_rust::Message::builder("PRIVMSG")
                .tag("user-id", "userid1")
                .tag("display-name", "username")
                .build();
            let result = UserInfo::try_from(&no_user_id);
            assert_eq!(
                result,
                Ok(UserInfo::Twitch {
                    name: "username".to_string(),
                    id: "userid1".to_string()
                })
            );
        }
    }
}