aboutsummaryrefslogtreecommitdiffstats
path: root/crates/api-auth/src/discord/mod.rs
blob: 43a62bf9fff8373f9029d7ec941945553d1fddd7 (plain)
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
use api_core::models::user::User;
use async_session::{Session, serde_json};
use async_trait::async_trait;
use oauth2::{AuthorizationCode, CsrfToken, TokenResponse};
use redis::AsyncCommands;
use serde::{Deserialize, Serialize};
use sh_util::cache::{CacheKey, RedisManager};
use sqlx::PgPool;

use crate::{
    BasicClient, CSRF_TOKEN, OauthDriver, SessionResponse, client::AuthHttpClient, error::AuthError,
};

// The user data we'll get back from Discord.
// https://discord.com/developers/docs/resources/user#user-object-user-structure
#[derive(Debug, Serialize, Deserialize)]
struct DiscordUser {
    id: String,
    avatar: Option<String>,
    username: String,
    discriminator: String,
    email: Option<String>,
    verified: bool,
}

impl TryFrom<DiscordUser> for User {
    type Error = AuthError;

    fn try_from(user_data: DiscordUser) -> Result<Self, Self::Error> {
        match (&user_data.email, user_data.verified) {
            (None, _) => Err(AuthError::MissingEmail),
            (_, false) => Err(AuthError::EmailNotVerified),
            (Some(_), true) => Ok(Self {}),
        }
    }
}

#[derive(Clone)]
pub struct AuthServiceDiscord {
    database: PgPool,
    cache: RedisManager,
    client: BasicClient,
}

impl AuthServiceDiscord {
    pub fn new(database: PgPool, client: BasicClient, cache: RedisManager) -> Self {
        Self {
            database,
            client,
            cache,
        }
    }
}

#[async_trait]
impl OauthDriver for AuthServiceDiscord {
    async fn get_user(&self, client: &AuthHttpClient, code: &str) -> Result<User, AuthError> {
        crate::util::get_user::<DiscordUser>(
            &self.client,
            client,
            code,
            "https://discordapp.com/api/users/@me",
        )
        .await
    }

    async fn validate_session(&self, cookie: &str, state: &str) -> Result<(), AuthError> {
        crate::util::validate_session(&self.cache, cookie, state).await
    }

    async fn create_oauth_session(&self) -> Result<SessionResponse, AuthError> {
        crate::util::create_oauth_session(&self.client, &self.cache, &["identify", "email"]).await
    }

    async fn save_session(&self, user: &User) -> Result<(), AuthError> {
        todo!()
    }
}