//! Sign in with GitHub or Google on the web (hub spec §5.1.2, #106): //! the start of the flow, the callback, the administrator's provider //! settings, and connecting or disconnecting a provider from Settings › //! Security. use super::session::signed_in; use super::settings::{csrf, require}; use super::{Error, Shell}; use crate::auth::{self, Viewer}; use crate::db::accounts; use crate::signin::{self, External, Provider, STATE_COOKIE}; use crate::Shared; use axum::extract::{Path, Query, State}; use axum::http::{header, HeaderMap}; use axum::response::{IntoResponse, Redirect, Response}; use axum::Form; use serde::Deserialize; fn state_cookie(app: &Shared, value: &str, max_age: u32) -> String { let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" }; format!("{STATE_COOKIE}={value}; Path=/login; HttpOnly; SameSite=Lax; Max-Age={max_age}{secure}") } fn cookie_value(headers: &HeaderMap) -> Option { headers .get_all(header::COOKIE) .iter() .filter_map(|v| v.to_str().ok()) .flat_map(|v| v.split(';')) .filter_map(|c| c.trim().strip_prefix(&format!("{STATE_COOKIE}="))) .map(String::from) .next() } /// Begin: a state cookie, then off to the provider. async fn begin(app: &Shared, p: &'static Provider, mode: &str) -> Result { let s = signin::settings(app, p.id).await.map_err(|e| e.to_string())?; if !s.usable() { return Err(format!("Signing in with {} is not set up on this hub.", p.name)); } let state = signin::state_value(app, mode); let to = signin::authorize_url(app, p, &s.client_id, &state); Ok(([(header::SET_COOKIE, state_cookie(app, &state, 600))], Redirect::to(&to)).into_response()) } /// `GET /login/{provider}`: sign in with the provider. pub async fn start(State(app): State, viewer: Viewer, Path(id): Path) -> Result { let shell = Shell::new(&app, "/login", &viewer); let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?; if viewer.signed_in() { return Ok(Redirect::to("/").into_response()); } begin(&app, p, "in").await.map_err(|m| Error::bad(shell.clone(), m)) } /// `GET /settings/security/connect/{provider}`: link the provider to the /// signed-in account. pub async fn connect(State(app): State, viewer: Viewer, Path(id): Path) -> Result { let shell = Shell::new(&app, "/settings/security", &viewer); let me = require(&viewer, &shell)?; let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?; begin(&app, p, &format!("link:{}", me.account.id)).await.map_err(|m| Error::bad(shell.clone(), m)) } #[derive(Deserialize)] pub struct Callback { #[serde(default)] code: String, #[serde(default)] state: String, #[serde(default)] error: String, #[serde(default)] error_description: String, } fn to_login(msg: &str) -> Response { Redirect::to(&format!("/login?error={}", super::settings::urlencode(msg))).into_response() } fn to_security(msg: &str, ok: bool) -> Response { let k = if ok { "notice" } else { "error" }; Redirect::to(&format!("/settings/security?{k}={}", super::settings::urlencode(msg))).into_response() } /// `GET /login/{provider}/callback`: the provider sent the person back. pub async fn callback( State(app): State, viewer: Viewer, Path(id): Path, headers: HeaderMap, Query(q): Query, ) -> Result { let shell = Shell::new(&app, "/login", &viewer); let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?; // The state cookie goes, whatever else the answer sets (appended, so a // session cookie beside it is kept). let clear = state_cookie(&app, "", 0); let with_clear = |mut r: Response| { if let Ok(v) = header::HeaderValue::from_str(&clear) { r.headers_mut().append(header::SET_COOKIE, v); } r }; if !q.error.is_empty() { let why = if q.error_description.is_empty() { q.error.clone() } else { q.error_description.clone() }; return Ok(with_clear(to_login(&format!("{} did not sign you in: {why}", p.name)))); } let Some(cookie) = cookie_value(&headers) else { return Ok(with_clear(to_login("The sign-in took too long or the browser kept no cookie; try again."))); }; if cookie != q.state || q.code.is_empty() { return Ok(with_clear(to_login("The sign-in did not match the one started here; try again."))); } let Some(mode) = signin::state_mode(&app, &cookie) else { return Ok(with_clear(to_login("The sign-in did not match the one started here; try again."))); }; let s = signin::settings(&app, p.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; if !s.usable() { return Ok(with_clear(to_login(&format!("Signing in with {} is not set up on this hub.", p.name)))); } let who = match signin::identify(&app, p, &s, &q.code).await { Ok(w) => w, Err(msg) => return Ok(with_clear(to_login(&msg))), }; let e = |e| Error::from_db(shell.clone(), e); // Connecting to a signed-in account. if let Some(account_id) = mode.strip_prefix("link:").and_then(|i| i.parse::().ok()) { let Some(me) = viewer.account().filter(|a| a.id == account_id) else { return Ok(with_clear(to_security("Sign in first, then connect the account.", false))); }; if let Some(other) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? { if other.id != me.id { return Ok(with_clear(to_security(&format!("That {} account is connected to {} already.", p.name, other.username), false))); } } signin::link(&app.db, p.id, &who.subject, me.id, &who.login).await.map_err(e)?; accounts::audit(&app.db, Some(me), "signin.connected", &me.username, p.id).await.ok(); return Ok(with_clear(to_security(&format!("{} connected as {}.", p.name, who.login), true))); } // Signing in: a known link, else the account with that verified email, // else a new account when registration is open. if let Some(account) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? { if account.blocked() { return Ok(with_clear(to_login("This account cannot sign in."))); } accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok(); return Ok(with_clear(signed_in(&app, &account, "/"))); } if let Some(email) = &who.email { if let Some(account) = accounts::account_by_verified_email(&app.db, email).await.map_err(e)? { if account.blocked() { return Ok(with_clear(to_login("This account cannot sign in."))); } signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await.map_err(e)?; accounts::audit(&app.db, Some(&account), "signin.connected", &account.username, &format!("{} by email", p.id)).await.ok(); accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok(); return Ok(with_clear(signed_in(&app, &account, "/"))); } } let mode = super::session::registration_mode(&app).await; if mode != "open" { return Ok(with_clear(to_login(&format!( "No account here is connected to that {} account, and registration is {}. Register or sign in first, then connect it under Settings › Security.", p.name, if mode == "invite" { "by invitation" } else { "closed" } )))); } let account = register(&app, p, &who).await.map_err(e)?; Ok(with_clear(signed_in(&app, &account, "/"))) } /// A new account for someone the provider vouches for: a username from /// their login there, an unusable password, the email verified when the /// provider says so. async fn register(app: &Shared, p: &Provider, who: &External) -> sqlx::Result { let username = signin::free_username(&app.db, &who.login, p.id).await?; let hash = auth::hash_password(&auth::random_hex(24)).unwrap_or_default(); let first = accounts::account_count(&app.db).await? == 0; let account = accounts::create_account(&app.db, &username, who.email.as_deref().unwrap_or(""), &hash, &auth::random_hex(16), first).await?; if who.email.is_some() { accounts::set_email_verified(&app.db, account.id, true).await?; } if !who.name.is_empty() { accounts::set_profile(&app.db, account.id, &who.name, who.email.as_deref().unwrap_or("")).await?; if who.email.is_some() { accounts::set_email_verified(&app.db, account.id, true).await?; } } signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await?; accounts::audit(&app.db, Some(&account), "register", &username, &format!("with {}", p.id)).await.ok(); accounts::account_by_id(&app.db, account.id).await.map(|a| a.unwrap_or(account)) } #[derive(Deserialize)] pub struct DisconnectForm { #[serde(rename = "_csrf")] csrf_token: String, } /// `POST /settings/security/disconnect/{provider}`. pub async fn disconnect( State(app): State, viewer: Viewer, Path(id): Path, Form(f): Form, ) -> Result { let shell = Shell::new(&app, "/settings/security", &viewer); let me = require(&viewer, &shell)?; csrf(&viewer, &f.csrf_token, &shell)?; let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?; if signin::unlink(&app.db, p.id, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))? { accounts::audit(&app.db, Some(&me.account), "signin.disconnected", &me.account.username, p.id).await.ok(); } Ok(to_security(&format!("{} disconnected.", p.name), true)) } /// A provider as the admin page shows it. pub struct ProviderView { pub id: &'static str, pub name: &'static str, pub client_id: String, pub has_secret: bool, pub enabled: bool, pub callback: String, } pub async fn provider_views(app: &Shared) -> sqlx::Result> { let mut out = vec![]; for p in &signin::PROVIDERS { let s = signin::settings(app, p.id).await?; out.push(ProviderView { id: p.id, name: p.name, client_id: s.client_id, has_secret: !s.secret.is_empty(), enabled: s.enabled, callback: p.callback_url(app), }); } Ok(out) } #[derive(Deserialize)] pub struct ProviderForm { #[serde(rename = "_csrf")] pub csrf_token: String, pub provider: String, #[serde(default)] pub client_id: String, #[serde(default)] pub secret: String, #[serde(default)] pub enabled: Option, } /// Apply the admin form: `Ok(notice)` or `Err(message)`. pub async fn apply(app: &Shared, viewer: &Viewer, f: ProviderForm) -> sqlx::Result> { let Some(p) = signin::provider(&f.provider) else { return Ok(Err("Unknown provider.".into())) }; let client_id = f.client_id.trim(); if client_id.len() > 200 || client_id.contains(char::is_whitespace) && !client_id.is_empty() { return Ok(Err("A client id is one token.".into())); } let secret = f.secret.trim(); let secret = if secret.is_empty() { None } else { Some(secret) }; let enabled = f.enabled.is_some(); signin::save(app, p.id, client_id, secret, enabled).await?; let s = signin::settings(app, p.id).await?; accounts::audit(&app.db, viewer.account(), "admin.signin", p.id, if s.usable() { "on" } else { "off" }).await.ok(); Ok(Ok(if s.usable() { format!("Signing in with {} is on.", p.name) } else if enabled { format!("{} is saved but off until it has a client id and secret.", p.name) } else { format!("{} is off.", p.name) })) } /// A page's view of what people may sign in with. pub async fn buttons(app: &Shared) -> Vec<(&'static str, &'static str)> { signin::enabled(app).await.into_iter().map(|p| (p.id, p.name)).collect() }