1#![warn(missing_docs)]
26
27use std::fmt;
28use std::sync::Arc;
29
30use renox::db::Migration;
31use renox::prelude::*;
32use serde::Serialize;
33
34pub mod events;
35pub mod github;
36pub mod google;
37mod handlers;
38pub mod microsoft;
39mod model;
40pub mod provider;
41
42pub use events::{AccountLinked, AccountUnlinked, LoggedInWith, OAuthRefused};
43pub use github::GitHub;
44pub use google::Google;
45pub use microsoft::Microsoft;
46pub use model::OAuthAccount;
47pub use provider::{
48 BoxFuture, Credentials, Profile, Provider, Refused, Token, TokenRequest, exchange_code,
49};
50
51const MIGRATIONS: &[Migration] = &[Migration::new(
52 "00010101000800_create_oauth_accounts_table",
53 "",
54 Some(include_str!(
55 "../migrations/00010101000800_create_oauth_accounts_table.down.sql"
56 )),
57)
58.sqlite(
59 include_str!("../migrations/00010101000800_create_oauth_accounts_table.up.sql"),
60 None,
61)
62.postgres(
63 include_str!("../migrations/00010101000800_create_oauth_accounts_table.postgres.up.sql"),
64 None,
65)];
66
67const VIEWS: &[(&str, &str)] = &[
70 (
71 "renox/auth/login_options.html",
72 include_str!("../views/login_options.html"),
73 ),
74 ("oauth/section.html", include_str!("../views/section.html")),
75];
76
77#[derive(Clone, Default)]
80pub struct OAuth {
81 providers: Vec<Arc<dyn Provider>>,
82 domains: Vec<String>,
83}
84
85impl OAuth {
86 pub fn new() -> Self {
88 Self::default()
89 }
90
91 pub fn google(self) -> Self {
94 self.provider(Google::from_config())
95 }
96
97 pub fn github(self) -> Self {
100 self.provider(GitHub::from_config())
101 }
102
103 pub fn microsoft(self) -> Self {
108 self.provider(Microsoft::from_config())
109 }
110
111 pub fn allow_domains(mut self, domains: &[&str]) -> Self {
124 for domain in domains {
125 let domain = domain.trim().trim_start_matches('@').to_ascii_lowercase();
126 if !domain.is_empty() && !self.domains.contains(&domain) {
127 self.domains.push(domain);
128 }
129 }
130 self
131 }
132
133 pub fn provider(mut self, provider: impl Provider) -> Self {
137 self.providers.retain(|p| p.name() != provider.name());
138 self.providers.push(Arc::new(provider));
139 self
140 }
141}
142
143impl fmt::Debug for OAuth {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 f.debug_list()
146 .entries(self.providers.iter().map(|p| p.name().to_owned()))
147 .finish()
148 }
149}
150
151#[derive(Clone)]
153pub(crate) struct Providers {
154 list: Arc<Vec<Arc<dyn Provider>>>,
155 domains: Arc<Vec<String>>,
156}
157
158impl Providers {
159 fn new(oauth: &OAuth) -> Self {
160 Self {
161 list: Arc::new(oauth.providers.clone()),
162 domains: Arc::new(oauth.domains.clone()),
163 }
164 }
165
166 pub(crate) fn allows(&self, email: Option<&str>) -> bool {
168 self.domains.is_empty()
169 || email
170 .and_then(|email| email.rsplit_once('@'))
171 .is_some_and(|(_, domain)| {
172 self.domains.iter().any(|d| d.eq_ignore_ascii_case(domain))
173 })
174 }
175
176 pub(crate) fn domains(&self) -> &[String] {
178 &self.domains
179 }
180
181 pub(crate) fn enabled(&self, state: &AppState, name: &str) -> Option<Arc<dyn Provider>> {
183 self.list
184 .iter()
185 .find(|p| p.name() == name)
186 .filter(|p| p.credentials().resolve(&state.config).is_some())
187 .map(|p| p.with_config(&state.config).unwrap_or_else(|| p.clone()))
188 }
189
190 pub(crate) fn all_enabled(&self, state: &AppState) -> Vec<Arc<dyn Provider>> {
192 self.list
193 .iter()
194 .filter(|p| p.credentials().resolve(&state.config).is_some())
195 .cloned()
196 .collect()
197 }
198}
199
200#[derive(Serialize)]
202struct Button {
203 name: String,
204 label: String,
205 url: String,
206}
207
208#[derive(Serialize)]
210struct Row {
211 name: String,
212 label: String,
213 link_url: Option<String>,
215 linked: bool,
216 email: Option<String>,
217 since: Option<DateTime>,
218}
219
220#[derive(Serialize)]
222struct Section {
223 providers: Vec<Row>,
224 has_password: bool,
225 can_unlink: bool,
227 set_password_url: Option<String>,
229}
230
231impl Module for OAuth {
232 fn name(&self) -> &'static str {
233 "oauth"
234 }
235
236 fn migrations(&self) -> &'static [Migration] {
237 MIGRATIONS
238 }
239
240 fn routes(&self) -> Routes {
241 handlers::routes(Providers::new(self))
242 }
243
244 fn register(&self, app: &mut Registry) {
245 let providers = Providers::new(self);
246 let shared = providers.clone();
248 app.share("oauth_providers", move |ctx: renox::view::ViewContext| {
249 let providers = shared.clone();
250 async move { buttons(&ctx, &providers).await }
251 });
252 let listed = providers.clone();
253 app.account_section("oauth/section.html", 50, move |user, state| {
254 let providers = listed.clone();
255 async move {
256 let section = section(&state, &providers, &user).await?;
257 Ok(renox::serde_json::to_value(section)?)
258 }
259 });
260 app.templates(|env| {
261 for (name, source) in VIEWS {
262 if env.get_template(name).is_err() {
264 renox::view::add_template(env, *name, *source)
265 .expect("a built-in template compiles");
266 }
267 }
268 });
269 app.listen(|e: AccountLinked, state| async move {
271 let entry = renox::audit::Entry::new("oauth.linked")
272 .user(e.user_id)
273 .data(renox::serde_json::json!({ "provider": e.provider }));
274 audit(&state, entry).await
275 })
276 .listen(|e: AccountUnlinked, state| async move {
277 let entry = renox::audit::Entry::new("oauth.unlinked")
278 .user(e.user_id)
279 .data(renox::serde_json::json!({ "provider": e.provider }));
280 audit(&state, entry).await
281 })
282 .listen(|e: OAuthRefused, state| async move {
283 let entry = renox::audit::Entry::new("oauth.refused").data(renox::serde_json::json!({
284 "provider": e.provider,
285 "reason": e.reason,
286 "email": e.email,
287 }));
288 audit(&state, entry).await
289 })
290 .listen(|e: LoggedInWith, state| async move {
291 let entry = renox::audit::Entry::new("oauth.login")
292 .user(e.user_id)
293 .data(renox::serde_json::json!({
294 "provider": e.provider,
295 "second_step": e.second_step,
296 }));
297 audit(&state, entry).await
298 });
299 }
300}
301
302async fn buttons(ctx: &renox::view::ViewContext, providers: &Providers) -> Result<Vec<Button>> {
305 let state = &ctx.state;
306 let mut enabled = providers.all_enabled(state);
307 if enabled.is_empty() {
308 return Ok(Vec::new());
309 }
310 let confirming = state
311 .url("password.confirm", &[])
312 .is_ok_and(|path| path == ctx.path);
313 let mut confirm = false;
314 if let Some(user) = ctx.user.as_ref().filter(|_| confirming) {
315 let linked = OAuthAccount::of_user(&state.db, user.id).await?;
316 enabled.retain(|p| linked.iter().any(|a| a.provider == p.name()));
317 confirm = true;
318 }
319 enabled
320 .iter()
321 .map(|p| {
322 let mut url = state.url("oauth.redirect", &[&p.name()])?;
323 if confirm {
324 url.push_str("?intent=confirm");
325 }
326 Ok(Button {
327 name: p.name().to_owned(),
328 label: p.label().to_owned(),
329 url,
330 })
331 })
332 .collect()
333}
334
335async fn section(state: &AppState, providers: &Providers, user: &User) -> Result<Section> {
337 let linked = OAuthAccount::of_user(&state.db, user.id).await?;
338 let mut rows = Vec::new();
339 for provider in providers.all_enabled(state) {
340 let account = linked.iter().find(|a| a.provider == provider.name());
341 rows.push(Row {
342 name: provider.name().to_owned(),
343 label: provider.label().to_owned(),
344 link_url: Some(state.url("oauth.redirect", &[&provider.name()])?),
345 linked: account.is_some(),
346 email: account.and_then(|a| a.email.clone()),
347 since: account.and_then(|a| a.created_at),
348 });
349 }
350 for account in &linked {
352 if !rows.iter().any(|row| row.name == account.provider) {
353 let label = providers
354 .list
355 .iter()
356 .find(|p| p.name() == account.provider)
357 .map_or_else(|| account.provider.clone(), |p| p.label().to_owned());
358 rows.push(Row {
359 name: account.provider.clone(),
360 label,
361 link_url: None,
362 linked: true,
363 email: account.email.clone(),
364 since: account.created_at,
365 });
366 }
367 }
368 Ok(Section {
369 can_unlink: handlers::can_unlink(user, linked.len()),
370 has_password: user.has_password(),
371 set_password_url: state.url("password.request", &[]).ok(),
372 providers: rows,
373 })
374}
375
376async fn audit(state: &AppState, entry: renox::audit::Entry) -> Result {
378 let has_log = renox::db::sql("SELECT COUNT(*) FROM audit_logs WHERE 1 = 0")
379 .scalar::<i64>(&state.db)
380 .await
381 .is_ok();
382 if has_log {
383 renox::audit::record(&state.db, entry).await?;
384 }
385 Ok(())
386}
387
388#[cfg(doctest)]
390#[doc = include_str!("../../../docs/oauth.md")]
391pub struct Guide;