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
use crate::api::rcos::users::accounts::reverse_lookup::ReverseLookup;
use crate::api::rcos::users::UserAccountType;
use crate::env::global_config;
use crate::error::TelescopeError;
use crate::web::services::auth::identity::{AuthenticationCookie, RootIdentity};
use crate::web::services::auth::oauth2_providers::{Oauth2Identity, Oauth2IdentityProvider};
use crate::web::services::auth::IdentityProvider;
use actix_web::http::header::ACCEPT;
use chrono::{DateTime, Duration, Utc};
use futures::future::LocalBoxFuture;
use oauth2::basic::{BasicClient, BasicTokenResponse};
use oauth2::{AccessToken, RefreshToken, Scope, TokenResponse};
use oauth2::{AuthUrl, TokenUrl};
use reqwest::header::AUTHORIZATION;
use serenity::model::id::RoleId;
use serenity::model::user::CurrentUser;
use std::sync::Arc;
use uuid::Uuid;
pub const DISCORD_API_ENDPOINT: &'static str = "https://discord.com/api/v8";
pub struct DiscordOAuth;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct DiscordIdentity {
access_token: AccessToken,
expiration: DateTime<Utc>,
refresh_token: RefreshToken,
}
lazy_static! {
static ref DISCORD_CLIENT: Arc<BasicClient> = {
let config = global_config();
let client = BasicClient::new(
config.discord_config.client_id.clone(),
Some(config.discord_config.client_secret.clone()),
AuthUrl::new("https://discord.com/api/oauth2/authorize".into())
.expect("Invalid Discord Auth URL"),
Some(TokenUrl::new("https://discord.com/api/oauth2/token".into())
.expect("Invalid Discord Token URL")));
Arc::new(client)
};
}
impl Oauth2IdentityProvider for DiscordOAuth {
type IdentityType = DiscordIdentity;
const SERVICE_NAME: &'static str = "discord";
fn get_client() -> Arc<BasicClient> {
DISCORD_CLIENT.clone()
}
fn scopes() -> Vec<Scope> {
vec![
Scope::new("identify".to_string()),
Scope::new("guilds.join".to_string()),
]
}
}
impl Oauth2Identity for DiscordIdentity {
const USER_ACCOUNT_TY: UserAccountType = UserAccountType::Discord;
fn from_basic_token(token: &BasicTokenResponse) -> Self {
Self::from_response(token)
}
fn platform_user_id(&self) -> LocalBoxFuture<Result<String, TelescopeError>> {
Box::pin(async move { self.get_discord_id().await })
}
fn into_root(self) -> RootIdentity {
RootIdentity::Discord(self)
}
fn add_to_cookie(self, cookie: &mut AuthenticationCookie) {
cookie.discord = Some(self);
}
}
impl DiscordIdentity {
fn from_response(token_response: &BasicTokenResponse) -> Self {
let token_duration = token_response
.expires_in()
.expect("Discord did not return token duration.");
let chrono_duration =
Duration::from_std(token_duration).expect("Token duration out of range.");
DiscordIdentity {
access_token: token_response.access_token().clone(),
expiration: Utc::now() + chrono_duration,
refresh_token: token_response
.refresh_token()
.expect("Discord did not return refresh token.")
.clone(),
}
}
pub async fn refresh(self) -> Result<Self, TelescopeError> {
if self.expiration < Utc::now() {
let client: Arc<BasicClient> = <DiscordOAuth as Oauth2IdentityProvider>::get_client();
let mut refresh_token_request = client.exchange_refresh_token(&self.refresh_token);
for scope in DiscordOAuth::scopes() {
refresh_token_request = refresh_token_request.add_scope(scope);
}
let response = refresh_token_request
.add_extra_param("redirect_uri", DiscordOAuth::login_redirect_path().as_str())
.request(oauth2::reqwest::http_client)
.map_err(|err| {
TelescopeError::ise(format!(
"Could not refresh Discord OAuth2 token. Error: {}",
err
))
})?;
return Ok(Self::from_response(&response));
} else {
return Ok(self);
}
}
pub async fn get_discord_id(&self) -> Result<String, TelescopeError> {
self.get_authenticated_user()
.await
.map(|u| u.id.to_string())
}
pub async fn get_rcos_user_id(&self) -> Result<Option<Uuid>, TelescopeError> {
let platform_id: String = self.get_discord_id().await?;
ReverseLookup::execute(UserAccountType::Discord, platform_id).await
}
pub async fn get_authenticated_user(&self) -> Result<CurrentUser, TelescopeError> {
return reqwest::Client::new()
.get(format!("{}/users/@me", DISCORD_API_ENDPOINT).as_str())
.bearer_auth(self.access_token.secret())
.header(ACCEPT, "application/json")
.send()
.await
.map_err(|e| {
TelescopeError::ise(format!(
"Could not send identification query to Discord \
API. Internal error: {}",
e
))
})?
.json::<CurrentUser>()
.await
.map_err(|e| {
TelescopeError::ise(format!(
"Error with identification response from Discord \
API. Internal error: {}",
e
))
});
}
pub async fn add_to_rcos_guild(
&self,
nickname: Option<String>,
roles: Vec<RoleId>,
) -> Result<(), TelescopeError> {
let user_id: String = self.get_discord_id().await?;
let rcos_discord = &global_config().discord_config.rcos_guild_id;
let url: String = format!(
"{}/guilds/{}/members/{}",
DISCORD_API_ENDPOINT, rcos_discord, user_id
);
let body = json!({
"access_token": self.access_token.secret(),
"nick": nickname,
"roles": roles
});
let response = reqwest::Client::new()
.put(url.as_str())
.json(&body)
.header(
AUTHORIZATION,
format!("Bot {}", global_config().discord_config.bot_token.as_str()),
)
.send()
.await
.map_err(|err| {
error!("Could not add user to RCOS Discord. Reqwest error: {}", err);
TelescopeError::ise(format!(
"Could not join RCOS Discord. Internal Error: {}",
err
))
})?;
info!(
"Added user {} (ID {}) to RCOS Discord.",
nickname.unwrap_or("(no nickname)".to_string()),
user_id
);
if !response.status().is_success() {
error!("Discord returned non-success status code when adding user to RCOS Guild. Response: {:#?}", response);
return Err(TelescopeError::GatewayError {
header: "Discord API Error".to_string(),
message: format!(
"Discord API returned status {}{}.",
response.status().as_u16(),
response
.status()
.canonical_reason()
.map(|s| format!(" ({})", s))
.unwrap_or("".to_string())
),
});
}
return Ok(());
}
}