| 83940d53 Andy McCall ↶ |
1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
use super::session::signed_in; |
| 7 |
use super::settings::{csrf, require}; |
| 8 |
use super::{Error, Shell}; |
| 9 |
use crate::auth::{self, Viewer}; |
| 10 |
use crate::db::accounts; |
| 11 |
use crate::signin::{self, External, Provider, STATE_COOKIE}; |
| 12 |
use crate::Shared; |
| 13 |
use axum::extract::{Path, Query, State}; |
| 14 |
use axum::http::{header, HeaderMap}; |
| 15 |
use axum::response::{IntoResponse, Redirect, Response}; |
| 16 |
use axum::Form; |
| 17 |
use serde::Deserialize; |
| 18 |
|
| 19 |
fn state_cookie(app: &Shared, value: &str, max_age: u32) -> String { |
| 20 |
let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" }; |
| 21 |
format!("{STATE_COOKIE}={value}; Path=/login; HttpOnly; SameSite=Lax; Max-Age={max_age}{secure}") |
| 22 |
} |
| 23 |
|
| 24 |
fn cookie_value(headers: &HeaderMap) -> Option<String> { |
| 25 |
headers |
| 26 |
.get_all(header::COOKIE) |
| 27 |
.iter() |
| 28 |
.filter_map(|v| v.to_str().ok()) |
| 29 |
.flat_map(|v| v.split(';')) |
| 30 |
.filter_map(|c| c.trim().strip_prefix(&format!("{STATE_COOKIE}="))) |
| 31 |
.map(String::from) |
| 32 |
.next() |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
async fn begin(app: &Shared, p: &'static Provider, mode: &str) -> Result<Response, String> { |
| 37 |
let s = signin::settings(app, p.id).await.map_err(|e| e.to_string())?; |
| 38 |
if !s.usable() { |
| 39 |
return Err(format!("Signing in with {} is not set up on this hub.", p.name)); |
| 40 |
} |
| 41 |
let state = signin::state_value(app, mode); |
| 42 |
let to = signin::authorize_url(app, p, &s.client_id, &state); |
| 43 |
Ok(([(header::SET_COOKIE, state_cookie(app, &state, 600))], Redirect::to(&to)).into_response()) |
| 44 |
} |
| 45 |
|
| 46 |
|
| 47 |
pub async fn start(State(app): State<Shared>, viewer: Viewer, Path(id): Path<String>) -> Result<Response, Error> { |
| 48 |
let shell = Shell::new(&app, "/login", &viewer); |
| 49 |
let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?; |
| 50 |
if viewer.signed_in() { |
| 51 |
return Ok(Redirect::to("/").into_response()); |
| 52 |
} |
| 53 |
begin(&app, p, "in").await.map_err(|m| Error::bad(shell.clone(), m)) |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
pub async fn connect(State(app): State<Shared>, viewer: Viewer, Path(id): Path<String>) -> Result<Response, Error> { |
| 59 |
let shell = Shell::new(&app, "/settings/security", &viewer); |
| 60 |
let me = require(&viewer, &shell)?; |
| 61 |
let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?; |
| 62 |
begin(&app, p, &format!("link:{}", me.account.id)).await.map_err(|m| Error::bad(shell.clone(), m)) |
| 63 |
} |
| 64 |
|
| 65 |
#[derive(Deserialize)] |
| 66 |
pub struct Callback { |
| 67 |
#[serde(default)] |
| 68 |
code: String, |
| 69 |
#[serde(default)] |
| 70 |
state: String, |
| 71 |
#[serde(default)] |
| 72 |
error: String, |
| 73 |
#[serde(default)] |
| 74 |
error_description: String, |
| 75 |
} |
| 76 |
|
| 77 |
fn to_login(msg: &str) -> Response { |
| 78 |
Redirect::to(&format!("/login?error={}", super::settings::urlencode(msg))).into_response() |
| 79 |
} |
| 80 |
|
| 81 |
fn to_security(msg: &str, ok: bool) -> Response { |
| 82 |
let k = if ok { "notice" } else { "error" }; |
| 83 |
Redirect::to(&format!("/settings/security?{k}={}", super::settings::urlencode(msg))).into_response() |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
pub async fn callback( |
| 88 |
State(app): State<Shared>, |
| 89 |
viewer: Viewer, |
| 90 |
Path(id): Path<String>, |
| 91 |
headers: HeaderMap, |
| 92 |
Query(q): Query<Callback>, |
| 93 |
) -> Result<Response, Error> { |
| 94 |
let shell = Shell::new(&app, "/login", &viewer); |
| 95 |
let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?; |
| 96 |
|
| 97 |
|
| 98 |
let clear = state_cookie(&app, "", 0); |
| 99 |
let with_clear = |mut r: Response| { |
| 100 |
if let Ok(v) = header::HeaderValue::from_str(&clear) { |
| 101 |
r.headers_mut().append(header::SET_COOKIE, v); |
| 102 |
} |
| 103 |
r |
| 104 |
}; |
| 105 |
if !q.error.is_empty() { |
| 106 |
let why = if q.error_description.is_empty() { q.error.clone() } else { q.error_description.clone() }; |
| 107 |
return Ok(with_clear(to_login(&format!("{} did not sign you in: {why}", p.name)))); |
| 108 |
} |
| 109 |
let Some(cookie) = cookie_value(&headers) else { |
| 110 |
return Ok(with_clear(to_login("The sign-in took too long or the browser kept no cookie; try again."))); |
| 111 |
}; |
| 112 |
if cookie != q.state || q.code.is_empty() { |
| 113 |
return Ok(with_clear(to_login("The sign-in did not match the one started here; try again."))); |
| 114 |
} |
| 115 |
let Some(mode) = signin::state_mode(&app, &cookie) else { |
| 116 |
return Ok(with_clear(to_login("The sign-in did not match the one started here; try again."))); |
| 117 |
}; |
| 118 |
let s = signin::settings(&app, p.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 119 |
if !s.usable() { |
| 120 |
return Ok(with_clear(to_login(&format!("Signing in with {} is not set up on this hub.", p.name)))); |
| 121 |
} |
| 122 |
let who = match signin::identify(&app, p, &s, &q.code).await { |
| 123 |
Ok(w) => w, |
| 124 |
Err(msg) => return Ok(with_clear(to_login(&msg))), |
| 125 |
}; |
| 126 |
let e = |e| Error::from_db(shell.clone(), e); |
| 127 |
|
| 128 |
if let Some(account_id) = mode.strip_prefix("link:").and_then(|i| i.parse::<i64>().ok()) { |
| 129 |
let Some(me) = viewer.account().filter(|a| a.id == account_id) else { |
| 130 |
return Ok(with_clear(to_security("Sign in first, then connect the account.", false))); |
| 131 |
}; |
| 132 |
if let Some(other) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? { |
| 133 |
if other.id != me.id { |
| 134 |
return Ok(with_clear(to_security(&format!("That {} account is connected to {} already.", p.name, other.username), false))); |
| 135 |
} |
| 136 |
} |
| 137 |
signin::link(&app.db, p.id, &who.subject, me.id, &who.login).await.map_err(e)?; |
| 138 |
accounts::audit(&app.db, Some(me), "signin.connected", &me.username, p.id).await.ok(); |
| 139 |
return Ok(with_clear(to_security(&format!("{} connected as {}.", p.name, who.login), true))); |
| 140 |
} |
| 141 |
|
| 142 |
|
| 143 |
if let Some(account) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? { |
| 144 |
if account.blocked() { |
| 145 |
return Ok(with_clear(to_login("This account cannot sign in."))); |
| 146 |
} |
| 147 |
accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok(); |
| 148 |
return Ok(with_clear(signed_in(&app, &account, "/"))); |
| 149 |
} |
| 150 |
if let Some(email) = &who.email { |
| 151 |
if let Some(account) = accounts::account_by_verified_email(&app.db, email).await.map_err(e)? { |
| 152 |
if account.blocked() { |
| 153 |
return Ok(with_clear(to_login("This account cannot sign in."))); |
| 154 |
} |
| 155 |
signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await.map_err(e)?; |
| 156 |
accounts::audit(&app.db, Some(&account), "signin.connected", &account.username, &format!("{} by email", p.id)).await.ok(); |
| 157 |
accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok(); |
| 158 |
return Ok(with_clear(signed_in(&app, &account, "/"))); |
| 159 |
} |
| 160 |
} |
| 161 |
let mode = super::session::registration_mode(&app).await; |
| 162 |
if mode != "open" { |
| 163 |
return Ok(with_clear(to_login(&format!( |
| 164 |
"No account here is connected to that {} account, and registration is {}. Register or sign in first, then connect it under Settings › Security.", |
| 165 |
p.name, |
| 166 |
if mode == "invite" { "by invitation" } else { "closed" } |
| 167 |
)))); |
| 168 |
} |
| 169 |
let account = register(&app, p, &who).await.map_err(e)?; |
| 170 |
Ok(with_clear(signed_in(&app, &account, "/"))) |
| 171 |
} |
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
async fn register(app: &Shared, p: &Provider, who: &External) -> sqlx::Result<accounts::Account> { |
| 177 |
let username = signin::free_username(&app.db, &who.login, p.id).await?; |
| 178 |
let hash = auth::hash_password(&auth::random_hex(24)).unwrap_or_default(); |
| 179 |
let first = accounts::account_count(&app.db).await? == 0; |
| 180 |
let account = |
| 181 |
accounts::create_account(&app.db, &username, who.email.as_deref().unwrap_or(""), &hash, &auth::random_hex(16), first).await?; |
| 182 |
if who.email.is_some() { |
| 183 |
accounts::set_email_verified(&app.db, account.id, true).await?; |
| 184 |
} |
| 185 |
if !who.name.is_empty() { |
| 186 |
accounts::set_profile(&app.db, account.id, &who.name, who.email.as_deref().unwrap_or("")).await?; |
| 187 |
if who.email.is_some() { |
| 188 |
accounts::set_email_verified(&app.db, account.id, true).await?; |
| 189 |
} |
| 190 |
} |
| 191 |
signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await?; |
| 192 |
accounts::audit(&app.db, Some(&account), "register", &username, &format!("with {}", p.id)).await.ok(); |
| 193 |
accounts::account_by_id(&app.db, account.id).await.map(|a| a.unwrap_or(account)) |
| 194 |
} |
| 195 |
|
| 196 |
#[derive(Deserialize)] |
| 197 |
pub struct DisconnectForm { |
| 198 |
#[serde(rename = "_csrf")] |
| 199 |
csrf_token: String, |
| 200 |
} |
| 201 |
|
| 202 |
|
| 203 |
pub async fn disconnect( |
| 204 |
State(app): State<Shared>, |
| 205 |
viewer: Viewer, |
| 206 |
Path(id): Path<String>, |
| 207 |
Form(f): Form<DisconnectForm>, |
| 208 |
) -> Result<Response, Error> { |
| 209 |
let shell = Shell::new(&app, "/settings/security", &viewer); |
| 210 |
let me = require(&viewer, &shell)?; |
| 211 |
csrf(&viewer, &f.csrf_token, &shell)?; |
| 212 |
let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?; |
| 213 |
if signin::unlink(&app.db, p.id, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))? { |
| 214 |
accounts::audit(&app.db, Some(&me.account), "signin.disconnected", &me.account.username, p.id).await.ok(); |
| 215 |
} |
| 216 |
Ok(to_security(&format!("{} disconnected.", p.name), true)) |
| 217 |
} |
| 218 |
|
| 219 |
|
| 220 |
pub struct ProviderView { |
| 221 |
pub id: &'static str, |
| 222 |
pub name: &'static str, |
| 223 |
pub client_id: String, |
| 224 |
pub has_secret: bool, |
| 225 |
pub enabled: bool, |
| 226 |
pub callback: String, |
| 227 |
} |
| 228 |
|
| 229 |
pub async fn provider_views(app: &Shared) -> sqlx::Result<Vec<ProviderView>> { |
| 230 |
let mut out = vec![]; |
| 231 |
for p in &signin::PROVIDERS { |
| 232 |
let s = signin::settings(app, p.id).await?; |
| 233 |
out.push(ProviderView { |
| 234 |
id: p.id, |
| 235 |
name: p.name, |
| 236 |
client_id: s.client_id, |
| 237 |
has_secret: !s.secret.is_empty(), |
| 238 |
enabled: s.enabled, |
| 239 |
callback: p.callback_url(app), |
| 240 |
}); |
| 241 |
} |
| 242 |
Ok(out) |
| 243 |
} |
| 244 |
|
| 245 |
#[derive(Deserialize)] |
| 246 |
pub struct ProviderForm { |
| 247 |
#[serde(rename = "_csrf")] |
| 248 |
pub csrf_token: String, |
| 249 |
pub provider: String, |
| 250 |
#[serde(default)] |
| 251 |
pub client_id: String, |
| 252 |
#[serde(default)] |
| 253 |
pub secret: String, |
| 254 |
#[serde(default)] |
| 255 |
pub enabled: Option<String>, |
| 256 |
} |
| 257 |
|
| 258 |
|
| 259 |
pub async fn apply(app: &Shared, viewer: &Viewer, f: ProviderForm) -> sqlx::Result<Result<String, String>> { |
| 260 |
let Some(p) = signin::provider(&f.provider) else { return Ok(Err("Unknown provider.".into())) }; |
| 261 |
let client_id = f.client_id.trim(); |
| 262 |
if client_id.len() > 200 || client_id.contains(char::is_whitespace) && !client_id.is_empty() { |
| 263 |
return Ok(Err("A client id is one token.".into())); |
| 264 |
} |
| 265 |
let secret = f.secret.trim(); |
| 266 |
let secret = if secret.is_empty() { None } else { Some(secret) }; |
| 267 |
let enabled = f.enabled.is_some(); |
| 268 |
signin::save(app, p.id, client_id, secret, enabled).await?; |
| 269 |
let s = signin::settings(app, p.id).await?; |
| 270 |
accounts::audit(&app.db, viewer.account(), "admin.signin", p.id, if s.usable() { "on" } else { "off" }).await.ok(); |
| 271 |
Ok(Ok(if s.usable() { |
| 272 |
format!("Signing in with {} is on.", p.name) |
| 273 |
} else if enabled { |
| 274 |
format!("{} is saved but off until it has a client id and secret.", p.name) |
| 275 |
} else { |
| 276 |
format!("{} is off.", p.name) |
| 277 |
})) |
| 278 |
} |
| 279 |
|
| 280 |
|
| 281 |
pub async fn buttons(app: &Shared) -> Vec<(&'static str, &'static str)> { |
| 282 |
signin::enabled(app).await.into_iter().map(|p| (p.id, p.name)).collect() |
| 283 |
} |