| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | | use super::{filters, Error, Page, Shell}; |
| 5 | | use crate::auth::{self, totp, Viewer, ViewerAccount}; |
| 6 | | use crate::db::{self, accounts}; |
| 7 | | use crate::Shared; |
| 8 | | use askama::Template; |
| 9 | | use axum::extract::{Form, Multipart, Path, Query, State}; |
| 10 | | use axum::http::{header, HeaderMap, StatusCode}; |
| 11 | | use axum::response::{IntoResponse, Redirect, Response}; |
| 12 | | use oxy_core::identity::{Identity, Signature}; |
| 13 | | use serde::Deserialize; |
| 14 | |
|
| 15 | |
|
| 16 | 455× | pub fn require(viewer: &Viewer, shell: &Shell) -> Result<ViewerAccount, Error> { |
| 17 | 455× | viewer.0.clone().ok_or_else(|| Error::redirect(format!("/login?next={}", urlencode(&shell.path)))) |
| 18 | 455× | } |
| 19 | |
|
| 20 | 393× | pub fn urlencode(s: &str) -> String { |
| 21 | 393× | let mut out = String::new(); |
| 22 | 8541× | for b in s.bytes() { |
| 23 | 8541× | match b { |
| 24 | 7653× | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(b as char), |
| 25 | 888× | _ => out.push_str(&format!("%{b:02X}")), |
| 26 | | } |
| 27 | | } |
| 28 | 393× | out |
| 29 | 393× | } |
| 30 | |
|
| 31 | 506× | pub fn csrf(viewer: &Viewer, token: &str, shell: &Shell) -> Result<(), Error> { |
| 32 | 506× | if viewer.csrf_ok(token) { |
| 33 | 503× | Ok(()) |
| 34 | | } else { |
| 35 | 3× | Err(Error::bad(shell.clone(), "This form has expired; reload the page and try again.")) |
| 36 | | } |
| 37 | 506× | } |
| 38 | |
|
| 39 | | #[derive(Template)] |
| 40 | | #[template(path = "settings.html")] |
| 41 | | pub struct SettingsPage { |
| 42 | | shell: Shell, |
| 43 | | me: accounts::Account, |
| 44 | | notice: Option<String>, |
| 45 | | error: Option<String>, |
| 46 | | |
| 47 | | theme: &'static str, |
| 48 | | themes: &'static [(&'static str, &'static str)], |
| 49 | | |
| 50 | | backdrop: &'static str, |
| 51 | | backdrops: &'static [(&'static str, &'static str)], |
| 52 | | |
| 53 | | mail: bool, |
| 54 | | |
| 55 | | |
| 56 | | default_bookmark: String, |
| 57 | | site_bookmark: String, |
| 58 | | } |
| 59 | |
|
| 60 | |
|
| 61 | | const THEMES: &[(&str, &str)] = &[("light", "Light"), ("dark", "Dark"), ("auto", "Match the system")]; |
| 62 | |
|
| 63 | |
|
| 64 | | const BACKDROPS: &[(&str, &str)] = &[("moving", "Moving"), ("still", "Still"), ("off", "Off")]; |
| 65 | |
|
| 66 | |
|
| 67 | 27× | fn backdrop_of(headers: &HeaderMap) -> &'static str { |
| 68 | 27× | let v = auth::viewer::cookie(headers, "backdrop").unwrap_or_default(); |
| 69 | 81× | BACKDROPS.iter().map(|(t, _)| *t).find(|t| *t == v).unwrap_or("moving") |
| 70 | 27× | } |
| 71 | |
|
| 72 | |
|
| 73 | 27× | fn theme_of(headers: &HeaderMap) -> &'static str { |
| 74 | 27× | let v = auth::viewer::cookie(headers, "theme").unwrap_or_default(); |
| 75 | 80× | THEMES.iter().map(|(t, _)| *t).find(|t| *t == v).unwrap_or("light") |
| 76 | 27× | } |
| 77 | |
|
| 78 | | impl SettingsPage { |
| 79 | 27× | fn new(shell: Shell, me: accounts::Account, headers: &HeaderMap) -> SettingsPage { |
| 80 | 27× | SettingsPage { |
| 81 | 27× | shell, |
| 82 | 27× | me, |
| 83 | 27× | notice: None, |
| 84 | 27× | error: None, |
| 85 | 27× | theme: theme_of(headers), |
| 86 | 27× | themes: THEMES, |
| 87 | 27× | backdrop: backdrop_of(headers), |
| 88 | 27× | backdrops: BACKDROPS, |
| 89 | 27× | mail: false, |
| 90 | 27× | default_bookmark: String::new(), |
| 91 | 27× | site_bookmark: crate::repo_setup::MAIN.into(), |
| 92 | 27× | } |
| 93 | 27× | } |
| 94 | |
|
| 95 | | |
| 96 | | |
| 97 | 27× | async fn with_hub(mut self, app: &Shared) -> Self { |
| 98 | | use crate::repo_setup::{bookmark_setting, BookmarkScope}; |
| 99 | 27× | self.mail = crate::mail::enabled(app); |
| 100 | 27× | self.default_bookmark = bookmark_setting(&app.db, BookmarkScope::Account(self.me.id)).await.ok().flatten().unwrap_or_default(); |
| 101 | 27× | if let Ok(Some(b)) = bookmark_setting(&app.db, BookmarkScope::Site).await { |
| 102 | 2× | self.site_bookmark = b; |
| 103 | 25× | } |
| 104 | 27× | self |
| 105 | 27× | } |
| 106 | |
|
| 107 | 9× | fn notice(mut self, n: impl Into<String>) -> Self { |
| 108 | 9× | self.notice = Some(n.into()); |
| 109 | 9× | self |
| 110 | 9× | } |
| 111 | |
|
| 112 | 4× | fn error(mut self, e: impl Into<String>) -> Self { |
| 113 | 4× | self.error = Some(e.into()); |
| 114 | 4× | self |
| 115 | 4× | } |
| 116 | | } |
| 117 | |
|
| 118 | 19× | pub async fn profile(State(app): State<Shared>, viewer: Viewer, headers: HeaderMap) -> Result<Page<SettingsPage>, Error> { |
| 119 | 19× | let shell = Shell::new(&app, "/settings", &viewer); |
| 120 | 19× | let me = require(&viewer, &shell)?; |
| 121 | 14× | Ok(Page(SettingsPage::new(shell, me.account, &headers).with_hub(&app).await)) |
| 122 | 19× | } |
| 123 | |
|
| 124 | |
|
| 125 | 4× | pub async fn avatar( |
| 126 | 4× | State(app): State<Shared>, |
| 127 | 4× | viewer: Viewer, |
| 128 | 4× | headers: HeaderMap, |
| 129 | 4× | multipart: Multipart, |
| 130 | 4× | ) -> Result<Page<SettingsPage>, Error> { |
| 131 | 4× | let shell = Shell::new(&app, "/settings", &viewer); |
| 132 | 4× | let me = require(&viewer, &shell)?; |
| 133 | 4× | let upload = super::avatar::read_upload(multipart).await; |
| 134 | 4× | csrf(&viewer, &upload.csrf, &shell)?; |
| 135 | 3× | let result = super::avatar::apply(&app, "account", me.account.id, upload).await; |
| 136 | 3× | if result.is_ok() { |
| 137 | 2× | accounts::audit(&app.db, Some(&me.account), "profile.picture", &me.account.username, "").await.ok(); |
| 138 | 1× | } |
| 139 | 3× | let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account); |
| 140 | 3× | let page = SettingsPage::new(shell, fresh, &headers).with_hub(&app).await; |
| 141 | 3× | Ok(Page(match result { |
| 142 | 2× | Ok(m) => page.notice(m), |
| 143 | 1× | Err(e) => page.error(e), |
| 144 | | })) |
| 145 | 4× | } |
| 146 | |
|
| 147 | |
|
| 148 | 1× | pub async fn resend_verification( |
| 149 | 1× | State(app): State<Shared>, |
| 150 | 1× | viewer: Viewer, |
| 151 | 1× | headers: HeaderMap, |
| 152 | 1× | Form(f): Form<super::session::CsrfForm>, |
| 153 | 1× | ) -> Result<Page<SettingsPage>, Error> { |
| 154 | 1× | let shell = Shell::new(&app, "/settings", &viewer); |
| 155 | 1× | let me = require(&viewer, &shell)?; |
| 156 | 1× | csrf(&viewer, &f.csrf, &shell)?; |
| 157 | 1× | let page = SettingsPage::new(shell, me.account.clone(), &headers).with_hub(&app).await; |
| 158 | 1× | Ok(Page(match super::recovery::send_verification(&app, &me.account).await { |
| 159 | 0× | Ok(()) if me.account.email_verified => page.notice("Your email is already verified."), |
| 160 | 0× | Ok(()) => page.notice(format!("A verification link is on its way to {}.", me.account.email)), |
| 161 | 1× | Err(e) => page.error(e), |
| 162 | | })) |
| 163 | 1× | } |
| 164 | |
|
| 165 | | #[derive(Deserialize)] |
| 166 | | pub struct AppearanceForm { |
| 167 | | #[serde(rename = "_csrf")] |
| 168 | | csrf_token: String, |
| 169 | | theme: String, |
| 170 | | #[serde(default)] |
| 171 | | backdrop: String, |
| 172 | | } |
| 173 | |
|
| 174 | |
|
| 175 | |
|
| 176 | 5× | pub async fn appearance(State(app): State<Shared>, viewer: Viewer, Form(f): Form<AppearanceForm>) -> Result<Response, Error> { |
| 177 | 5× | let shell = Shell::new(&app, "/settings", &viewer); |
| 178 | 5× | require(&viewer, &shell)?; |
| 179 | 5× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 180 | 7× | let Some((theme, _)) = THEMES.iter().find(|(t, _)| *t == f.theme) else { |
| 181 | 1× | return Err(Error::bad(shell, "Pick dark, light or match the system.")); |
| 182 | | }; |
| 183 | 3× | let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" }; |
| 184 | 3× | let backdrop = if f.backdrop.is_empty() { "moving" } else { f.backdrop.as_str() }; |
| 185 | 6× | let Some((backdrop, _)) = BACKDROPS.iter().find(|(b, _)| *b == backdrop) else { |
| 186 | 1× | return Err(Error::bad(shell, "Pick a moving, still or no background.")); |
| 187 | | }; |
| 188 | 2× | Ok(( |
| 189 | 2× | StatusCode::SEE_OTHER, |
| 190 | 2× | axum::response::AppendHeaders([ |
| 191 | 2× | (header::SET_COOKIE, format!("theme={theme}; Path=/; Max-Age=31536000; SameSite=Lax{secure}")), |
| 192 | 2× | (header::SET_COOKIE, format!("backdrop={backdrop}; Path=/; Max-Age=31536000; SameSite=Lax{secure}")), |
| 193 | 2× | (header::LOCATION, "/settings".to_string()), |
| 194 | 2× | ]), |
| 195 | 2× | ) |
| 196 | 2× | .into_response()) |
| 197 | 5× | } |
| 198 | |
|
| 199 | | #[derive(Deserialize)] |
| 200 | | pub struct ProfileForm { |
| 201 | | #[serde(rename = "_csrf")] |
| 202 | | csrf_token: String, |
| 203 | | display_name: String, |
| 204 | | email: String, |
| 205 | | #[serde(default)] |
| 206 | | bio: String, |
| 207 | | #[serde(default)] |
| 208 | | website: String, |
| 209 | | #[serde(default)] |
| 210 | | location: String, |
| 211 | | #[serde(default)] |
| 212 | | bluesky: String, |
| 213 | | #[serde(default)] |
| 214 | | mastodon: String, |
| 215 | | #[serde(default)] |
| 216 | | github: String, |
| 217 | | } |
| 218 | |
|
| 219 | 9× | pub async fn update_profile( |
| 220 | 9× | State(app): State<Shared>, |
| 221 | 9× | viewer: Viewer, |
| 222 | 9× | headers: HeaderMap, |
| 223 | 9× | Form(f): Form<ProfileForm>, |
| 224 | 9× | ) -> Result<Page<SettingsPage>, Error> { |
| 225 | 9× | let shell = Shell::new(&app, "/settings", &viewer); |
| 226 | 9× | let me = require(&viewer, &shell)?; |
| 227 | 9× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 228 | 8× | let website = f.website.trim(); |
| 229 | 8× | if !(website.is_empty() || website.starts_with("https://") || website.starts_with("http://")) || website.len() > 200 { |
| 230 | | return Ok(Page( |
| 231 | 1× | SettingsPage::new(shell, me.account, &headers) |
| 232 | 1× | .with_hub(&app) |
| 233 | 1× | .await |
| 234 | 1× | .error("The website must be an http:// or https:// address."), |
| 235 | | )); |
| 236 | 7× | } |
| 237 | | |
| 238 | 19× | let link = |given: &str, what: &str, parse: fn(&str) -> Option<String>| -> Result<String, String> { |
| 239 | 19× | if given.trim().is_empty() { |
| 240 | 15× | Ok(String::new()) |
| 241 | | } else { |
| 242 | 4× | parse(given).ok_or_else(|| format!("That is not a {what}.")) |
| 243 | | } |
| 244 | 19× | }; |
| 245 | 7× | let links = (|| { |
| 246 | | Ok::<_, String>(( |
| 247 | 7× | link(&f.bluesky, "Bluesky handle (such as andy.bsky.social)", crate::social::bluesky)?, |
| 248 | 6× | link(&f.mastodon, "Mastodon address (such as @[email protected])", crate::social::mastodon)?, |
| 249 | 6× | link(&f.github, "GitHub username", crate::social::github)?, |
| 250 | | )) |
| 251 | | })(); |
| 252 | 7× | let (bluesky, mastodon, github) = match links { |
| 253 | 6× | Ok(l) => l, |
| 254 | 1× | Err(msg) => return Ok(Page(SettingsPage::new(shell, me.account, &headers).with_hub(&app).await.error(&msg))), |
| 255 | | }; |
| 256 | 6× | let bio: String = f.bio.trim().chars().take(280).collect(); |
| 257 | 6× | let location: String = f.location.trim().chars().take(80).collect(); |
| 258 | 6× | accounts::set_profile(&app.db, me.account.id, f.display_name.trim(), f.email.trim()) |
| 259 | 6× | .await |
| 260 | 6× | .map_err(|e| Error::from_db(shell.clone(), e))?; |
| 261 | 6× | accounts::set_bio(&app.db, me.account.id, &bio, website, &location).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 262 | 6× | accounts::set_links(&app.db, me.account.id, &bluesky, &mastodon, &github).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 263 | 6× | let changed = me.account.email != f.email.trim(); |
| 264 | 6× | let updated = |
| 265 | 6× | accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account); |
| 266 | 6× | let mut notice = "Profile saved.".to_string(); |
| 267 | 6× | if changed && !updated.email.is_empty() { |
| 268 | 4× | accounts::audit(&app.db, Some(&updated), "email.changed", &updated.username, "").await.ok(); |
| 269 | 4× | match super::recovery::send_verification(&app, &updated).await { |
| 270 | 3× | Ok(()) => notice = format!("Profile saved. A verification link is on its way to {}.", updated.email), |
| 271 | 1× | Err(e) => notice = format!("Profile saved. {e}"), |
| 272 | | } |
| 273 | 2× | } |
| 274 | 6× | Ok(Page(SettingsPage::new(shell, updated, &headers).with_hub(&app).await.notice(notice))) |
| 275 | 9× | } |
| 276 | |
|
| 277 | | #[derive(Deserialize)] |
| 278 | | pub struct PasswordForm { |
| 279 | | #[serde(rename = "_csrf")] |
| 280 | | csrf_token: String, |
| 281 | | current: String, |
| 282 | | password: String, |
| 283 | | } |
| 284 | |
|
| 285 | | #[derive(Deserialize)] |
| 286 | | pub struct BookmarkForm { |
| 287 | | #[serde(rename = "_csrf")] |
| 288 | | csrf_token: String, |
| 289 | | #[serde(default)] |
| 290 | | default_bookmark: String, |
| 291 | | } |
| 292 | |
|
| 293 | |
|
| 294 | |
|
| 295 | 1× | pub async fn repositories( |
| 296 | 1× | State(app): State<Shared>, |
| 297 | 1× | viewer: Viewer, |
| 298 | 1× | headers: HeaderMap, |
| 299 | 1× | Form(f): Form<BookmarkForm>, |
| 300 | 1× | ) -> Result<Page<SettingsPage>, Error> { |
| 301 | 1× | let shell = Shell::new(&app, "/settings", &viewer); |
| 302 | 1× | let me = require(&viewer, &shell)?; |
| 303 | 1× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 304 | 1× | let scope = crate::repo_setup::BookmarkScope::Account(me.account.id); |
| 305 | 1× | let page = match crate::repo_setup::set_bookmark_setting(&app.db, scope, &f.default_bookmark).await { |
| 306 | | Ok(()) => { |
| 307 | 1× | accounts::audit(&app.db, Some(&me.account), "account.default_bookmark", &me.account.username, f.default_bookmark.trim()) |
| 308 | 1× | .await |
| 309 | 1× | .ok(); |
| 310 | 1× | SettingsPage::new(shell, me.account, &headers).with_hub(&app).await.notice("Saved: new repositories start with that bookmark.") |
| 311 | | } |
| 312 | 0× | Err(m) => SettingsPage::new(shell, me.account, &headers).with_hub(&app).await.error(&m), |
| 313 | | }; |
| 314 | 1× | Ok(Page(page)) |
| 315 | 1× | } |
| 316 | |
|
| 317 | 0× | pub async fn change_password( |
| 318 | 0× | State(app): State<Shared>, |
| 319 | 0× | viewer: Viewer, |
| 320 | 0× | headers: HeaderMap, |
| 321 | 0× | Form(f): Form<PasswordForm>, |
| 322 | 0× | ) -> Result<Response, Error> { |
| 323 | 0× | let shell = Shell::new(&app, "/settings", &viewer); |
| 324 | 0× | let me = require(&viewer, &shell)?; |
| 325 | 0× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 326 | 0× | if !auth::verify_password(&me.account.password_hash, &f.current) { |
| 327 | 0× | return Ok(Page(SettingsPage::new(shell, me.account, &headers).with_hub(&app).await.error("Your current password is wrong.")) |
| 328 | 0× | .into_response()); |
| 329 | 0× | } |
| 330 | 0× | if let Err(e) = auth::password_ok(&f.password) { |
| 331 | 0× | return Ok(Page(SettingsPage::new(shell, me.account, &headers).with_hub(&app).await.error(e)).into_response()); |
| 332 | 0× | } |
| 333 | 0× | let hash = auth::hash_password(&f.password).map_err(|e| Error::bad(shell.clone(), e.to_string()))?; |
| 334 | | |
| 335 | 0× | accounts::set_password(&app.db, me.account.id, &hash, &auth::random_hex(16)).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 336 | 0× | accounts::audit(&app.db, Some(&me.account), "password.changed", &me.account.username, "").await.ok(); |
| 337 | 0× | let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account); |
| 338 | 0× | Ok(super::session::signed_in(&app, &fresh, "/settings/security").await) |
| 339 | 0× | } |
| 340 | |
|
| 341 | | #[derive(Template)] |
| 342 | | #[template(path = "settings_security.html")] |
| 343 | | pub struct SecurityPage { |
| 344 | | shell: Shell, |
| 345 | | me: accounts::Account, |
| 346 | | notice: Option<String>, |
| 347 | | error: Option<String>, |
| 348 | | |
| 349 | | enrol: Option<(String, String, String)>, |
| 350 | | recovery: Vec<String>, |
| 351 | | |
| 352 | | connected: Vec<(&'static str, &'static str, Option<String>)>, |
| 353 | | |
| 354 | | sessions: Vec<SessionView>, |
| 355 | | |
| 356 | | phones: Vec<crate::db::approvals::Authenticator>, |
| 357 | | } |
| 358 | |
|
| 359 | |
|
| 360 | | pub struct SessionView { |
| 361 | | pub id: i64, |
| 362 | | pub current: bool, |
| 363 | | pub browser: String, |
| 364 | | pub address: String, |
| 365 | | pub seen_ms: i64, |
| 366 | | pub created_ms: i64, |
| 367 | | } |
| 368 | |
|
| 369 | |
|
| 370 | 22× | pub fn browser_of(agent: &str) -> String { |
| 371 | 303× | let has = |s: &str| agent.contains(s); |
| 372 | 22× | let browser = if has("Edg/") { |
| 373 | 1× | "Edge" |
| 374 | 21× | } else if has("OPR/") { |
| 375 | 0× | "Opera" |
| 376 | 21× | } else if has("Firefox/") { |
| 377 | 1× | "Firefox" |
| 378 | 20× | } else if has("Chrome/") || has("Chromium/") { |
| 379 | 1× | "Chrome" |
| 380 | 19× | } else if has("Safari/") { |
| 381 | 1× | "Safari" |
| 382 | 18× | } else if has("curl/") { |
| 383 | 0× | "curl" |
| 384 | | } else { |
| 385 | 18× | "" |
| 386 | | }; |
| 387 | 22× | let os = if has("Android") { |
| 388 | 0× | "Android" |
| 389 | 22× | } else if has("iPhone") || has("iPad") { |
| 390 | 1× | "iOS" |
| 391 | 21× | } else if has("Windows") { |
| 392 | 1× | "Windows" |
| 393 | 20× | } else if has("Mac OS X") || has("Macintosh") { |
| 394 | 1× | "macOS" |
| 395 | 19× | } else if has("CrOS") { |
| 396 | 0× | "ChromeOS" |
| 397 | 19× | } else if has("Linux") { |
| 398 | 1× | "Linux" |
| 399 | | } else { |
| 400 | 18× | "" |
| 401 | | }; |
| 402 | 22× | match (browser, os) { |
| 403 | 22× | ("", "") => "Unknown browser".into(), |
| 404 | 4× | (b, "") => b.into(), |
| 405 | 4× | ("", o) => format!("A browser on {o}"), |
| 406 | 4× | (b, o) => format!("{b} on {o}"), |
| 407 | | } |
| 408 | 22× | } |
| 409 | |
|
| 410 | 10× | async fn sessions_of(app: &Shared, me: &crate::auth::ViewerAccount) -> sqlx::Result<Vec<SessionView>> { |
| 411 | 10× | Ok(crate::db::sessions::of_account(&app.db, me.account.id, &me.account.session_salt) |
| 412 | 10× | .await? |
| 413 | 10× | .into_iter() |
| 414 | 10× | .map(|s| SessionView { |
| 415 | 14× | id: s.id, |
| 416 | 14× | current: s.id == me.session_id, |
| 417 | 14× | browser: browser_of(&s.agent), |
| 418 | 14× | address: s.address, |
| 419 | 14× | seen_ms: s.seen_ms, |
| 420 | 14× | created_ms: s.created_ms, |
| 421 | 14× | }) |
| 422 | 10× | .collect()) |
| 423 | 10× | } |
| 424 | |
|
| 425 | | #[derive(Deserialize)] |
| 426 | | pub struct SecurityQuery { |
| 427 | | notice: Option<String>, |
| 428 | | error: Option<String>, |
| 429 | | } |
| 430 | |
|
| 431 | 14× | pub async fn security(State(app): State<Shared>, viewer: Viewer, Query(q): Query<SecurityQuery>) -> Result<Page<SecurityPage>, Error> { |
| 432 | 14× | let shell = Shell::new(&app, "/settings/security", &viewer); |
| 433 | 14× | let me = require(&viewer, &shell)?; |
| 434 | 10× | let connected = connected_of(&app, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 435 | 10× | let sessions = sessions_of(&app, &me).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 436 | 10× | let phones = crate::db::approvals::authenticators(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 437 | 10× | Ok(Page(SecurityPage { |
| 438 | 10× | shell, |
| 439 | 10× | me: me.account, |
| 440 | 10× | notice: q.notice, |
| 441 | 10× | error: q.error, |
| 442 | 10× | enrol: None, |
| 443 | 10× | recovery: vec![], |
| 444 | 10× | connected, |
| 445 | 10× | sessions, |
| 446 | 10× | phones, |
| 447 | 10× | })) |
| 448 | 14× | } |
| 449 | |
|
| 450 | |
|
| 451 | 10× | pub async fn connected_of(app: &Shared, account_id: i64) -> sqlx::Result<Vec<(&'static str, &'static str, Option<String>)>> { |
| 452 | 10× | let links = crate::signin::links_of(&app.db, account_id).await?; |
| 453 | 10× | let mut out = vec![]; |
| 454 | 10× | for p in crate::signin::enabled(app).await { |
| 455 | 6× | out.push((p.id, p.name, links.iter().find(|l| l.provider == p.id).map(|l| l.login.clone()))); |
| 456 | | } |
| 457 | 10× | Ok(out) |
| 458 | 10× | } |
| 459 | |
|
| 460 | | #[derive(Deserialize)] |
| 461 | | pub struct TotpForm { |
| 462 | | #[serde(rename = "_csrf")] |
| 463 | | csrf_token: String, |
| 464 | | #[serde(default)] |
| 465 | | secret: String, |
| 466 | | #[serde(default)] |
| 467 | | code: String, |
| 468 | | #[serde(default)] |
| 469 | | password: String, |
| 470 | | } |
| 471 | |
|
| 472 | |
|
| 473 | 2× | pub async fn totp_begin(State(app): State<Shared>, viewer: Viewer, Form(f): Form<TotpForm>) -> Result<Page<SecurityPage>, Error> { |
| 474 | 2× | let shell = Shell::new(&app, "/settings/security", &viewer); |
| 475 | 2× | let me = require(&viewer, &shell)?; |
| 476 | 2× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 477 | 2× | let secret = totp::new_secret(); |
| 478 | 2× | let uri = totp::uri(&app.config.site.name, &me.account.username, &secret); |
| 479 | 2× | let qr = totp::qr_svg(&uri).unwrap_or_default(); |
| 480 | 2× | Ok(Page(SecurityPage { |
| 481 | 2× | shell, |
| 482 | 2× | me: me.account, |
| 483 | 2× | notice: None, |
| 484 | 2× | error: None, |
| 485 | 2× | enrol: Some((secret, uri, qr)), |
| 486 | 2× | recovery: vec![], |
| 487 | 2× | connected: vec![], |
| 488 | 2× | sessions: vec![], |
| 489 | 2× | phones: vec![], |
| 490 | 2× | })) |
| 491 | 2× | } |
| 492 | |
|
| 493 | |
|
| 494 | 2× | pub async fn totp_enable(State(app): State<Shared>, viewer: Viewer, Form(f): Form<TotpForm>) -> Result<Page<SecurityPage>, Error> { |
| 495 | 2× | let shell = Shell::new(&app, "/settings/security", &viewer); |
| 496 | 2× | let me = require(&viewer, &shell)?; |
| 497 | 2× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 498 | 2× | let now = (db::now_ms() / 1000) as u64; |
| 499 | 2× | if f.secret.is_empty() || !totp::verify(&f.secret, &f.code, now) { |
| 500 | 0× | let uri = totp::uri(&app.config.site.name, &me.account.username, &f.secret); |
| 501 | 0× | let qr = totp::qr_svg(&uri).unwrap_or_default(); |
| 502 | 0× | return Ok(Page(SecurityPage { |
| 503 | 0× | shell, |
| 504 | 0× | me: me.account, |
| 505 | 0× | notice: None, |
| 506 | 0× | error: Some("That code did not match; scan again and enter the current code.".into()), |
| 507 | 0× | enrol: Some((f.secret, uri, qr)), |
| 508 | 0× | recovery: vec![], |
| 509 | 0× | connected: vec![], |
| 510 | 0× | sessions: vec![], |
| 511 | 0× | phones: vec![], |
| 512 | 0× | })); |
| 513 | 2× | } |
| 514 | 2× | let (codes, stored) = totp::new_recovery_codes(); |
| 515 | 2× | accounts::set_totp(&app.db, me.account.id, Some(&f.secret), &stored).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 516 | 2× | accounts::audit(&app.db, Some(&me.account), "totp.enabled", &me.account.username, "").await.ok(); |
| 517 | 2× | let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account); |
| 518 | 2× | Ok(Page(SecurityPage { |
| 519 | 2× | shell, |
| 520 | 2× | me: fresh, |
| 521 | 2× | notice: Some("Two-factor authentication is on. Keep these recovery codes somewhere safe; each works once.".into()), |
| 522 | 2× | error: None, |
| 523 | 2× | enrol: None, |
| 524 | 2× | recovery: codes, |
| 525 | 2× | connected: vec![], |
| 526 | 2× | sessions: vec![], |
| 527 | 2× | phones: vec![], |
| 528 | 2× | })) |
| 529 | 2× | } |
| 530 | |
|
| 531 | 1× | pub async fn totp_disable(State(app): State<Shared>, viewer: Viewer, Form(f): Form<TotpForm>) -> Result<Page<SecurityPage>, Error> { |
| 532 | 1× | let shell = Shell::new(&app, "/settings/security", &viewer); |
| 533 | 1× | let me = require(&viewer, &shell)?; |
| 534 | 1× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 535 | 1× | if !auth::verify_password(&me.account.password_hash, &f.password) { |
| 536 | 0× | return Ok(Page(SecurityPage { |
| 537 | 0× | shell, |
| 538 | 0× | me: me.account, |
| 539 | 0× | notice: None, |
| 540 | 0× | error: Some("Your password is wrong.".into()), |
| 541 | 0× | enrol: None, |
| 542 | 0× | recovery: vec![], |
| 543 | 0× | connected: vec![], |
| 544 | 0× | sessions: vec![], |
| 545 | 0× | phones: vec![], |
| 546 | 0× | })); |
| 547 | 1× | } |
| 548 | 1× | accounts::set_totp(&app.db, me.account.id, None, "").await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 549 | 1× | accounts::audit(&app.db, Some(&me.account), "totp.disabled", &me.account.username, "").await.ok(); |
| 550 | | |
| 551 | 1× | for p in crate::db::approvals::authenticators(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))? { |
| 552 | 1× | crate::db::approvals::remove_authenticator(&app.db, me.account.id, p.token_id) |
| 553 | 1× | .await |
| 554 | 1× | .map_err(|e| Error::from_db(shell.clone(), e))?; |
| 555 | | } |
| 556 | 1× | let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account); |
| 557 | 1× | Ok(Page(SecurityPage { |
| 558 | 1× | shell, |
| 559 | 1× | me: fresh, |
| 560 | 1× | notice: Some("Two-factor authentication is off, and no phone approves for you now.".into()), |
| 561 | 1× | error: None, |
| 562 | 1× | enrol: None, |
| 563 | 1× | recovery: vec![], |
| 564 | 1× | connected: vec![], |
| 565 | 1× | sessions: vec![], |
| 566 | 1× | phones: vec![], |
| 567 | 1× | })) |
| 568 | 1× | } |
| 569 | |
|
| 570 | |
|
| 571 | |
|
| 572 | 1× | pub async fn sessions_reset(State(app): State<Shared>, viewer: Viewer, Form(f): Form<super::session::CsrfForm>) -> Result<Response, Error> { |
| 573 | 1× | let shell = Shell::new(&app, "/settings/security", &viewer); |
| 574 | 1× | let me = require(&viewer, &shell)?; |
| 575 | 1× | csrf(&viewer, &f.csrf, &shell)?; |
| 576 | 1× | accounts::set_session_salt(&app.db, me.account.id, &auth::random_hex(16)).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 577 | 1× | accounts::audit(&app.db, Some(&me.account), "sessions.reset", &me.account.username, "").await.ok(); |
| 578 | 1× | let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account); |
| 579 | 1× | Ok(super::session::signed_in(&app, &fresh, "/settings/security").await) |
| 580 | 1× | } |
| 581 | |
|
| 582 | |
|
| 583 | 1× | pub async fn session_end( |
| 584 | 1× | State(app): State<Shared>, |
| 585 | 1× | viewer: Viewer, |
| 586 | 1× | Path(id): Path<i64>, |
| 587 | 1× | Form(f): Form<super::session::CsrfForm>, |
| 588 | 1× | ) -> Result<Response, Error> { |
| 589 | 1× | let shell = Shell::new(&app, "/settings/security", &viewer); |
| 590 | 1× | let me = require(&viewer, &shell)?; |
| 591 | 1× | csrf(&viewer, &f.csrf, &shell)?; |
| 592 | 1× | let ended = crate::db::sessions::end(&app.db, me.account.id, id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 593 | 1× | if ended { |
| 594 | 1× | accounts::audit(&app.db, Some(&me.account), "session.ended", &me.account.username, &id.to_string()).await.ok(); |
| 595 | 0× | } |
| 596 | 1× | let to = if id == me.session_id { "/" } else { "/settings/security?notice=That+browser+is+signed+out." }; |
| 597 | 1× | Ok(Redirect::to(to).into_response()) |
| 598 | 1× | } |
| 599 | |
|
| 600 | |
|
| 601 | |
|
| 602 | 0× | pub async fn phone_remove( |
| 603 | 0× | State(app): State<Shared>, |
| 604 | 0× | viewer: Viewer, |
| 605 | 0× | Path(id): Path<i64>, |
| 606 | 0× | Form(f): Form<super::session::CsrfForm>, |
| 607 | 0× | ) -> Result<Response, Error> { |
| 608 | 0× | let shell = Shell::new(&app, "/settings/security", &viewer); |
| 609 | 0× | let me = require(&viewer, &shell)?; |
| 610 | 0× | csrf(&viewer, &f.csrf, &shell)?; |
| 611 | 0× | let removed = |
| 612 | 0× | crate::db::approvals::remove_authenticator(&app.db, me.account.id, id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 613 | 0× | if removed { |
| 614 | 0× | accounts::audit(&app.db, Some(&me.account), "2fa.phone_removed", &me.account.username, &id.to_string()).await.ok(); |
| 615 | 0× | } |
| 616 | 0× | Ok(Redirect::to("/settings/security?notice=That+phone+no+longer+approves+for+you.#phones").into_response()) |
| 617 | 0× | } |
| 618 | |
|
| 619 | |
|
| 620 | |
|
| 621 | | #[derive(Template)] |
| 622 | | #[template(path = "settings_keys.html")] |
| 623 | | pub struct KeysPage { |
| 624 | | shell: Shell, |
| 625 | | me: accounts::Account, |
| 626 | | keys: Vec<accounts::LinkedIdentity>, |
| 627 | | notice: Option<String>, |
| 628 | | error: Option<String>, |
| 629 | | |
| 630 | | pending: Option<(i64, String, String)>, |
| 631 | | } |
| 632 | |
|
| 633 | 9× | async fn keys_page( |
| 634 | 9× | app: &Shared, |
| 635 | 9× | shell: Shell, |
| 636 | 9× | me: accounts::Account, |
| 637 | 9× | notice: Option<String>, |
| 638 | 9× | error: Option<String>, |
| 639 | 9× | pending: Option<(i64, String, String)>, |
| 640 | 9× | ) -> Result<Page<KeysPage>, Error> { |
| 641 | 9× | let keys = accounts::identities_of(&app.db, me.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 642 | 9× | Ok(Page(KeysPage { shell, me, keys, notice, error, pending })) |
| 643 | 9× | } |
| 644 | |
|
| 645 | 3× | pub async fn keys(State(app): State<Shared>, viewer: Viewer) -> Result<Page<KeysPage>, Error> { |
| 646 | 3× | let shell = Shell::new(&app, "/settings/keys", &viewer); |
| 647 | 3× | let me = require(&viewer, &shell)?; |
| 648 | 3× | keys_page(&app, shell, me.account, None, None, None).await |
| 649 | 3× | } |
| 650 | |
|
| 651 | |
|
| 652 | |
|
| 653 | 3× | pub async fn keys_upload(State(app): State<Shared>, viewer: Viewer, mut multipart: Multipart) -> Result<Page<KeysPage>, Error> { |
| 654 | 3× | let shell = Shell::new(&app, "/settings/keys", &viewer); |
| 655 | 3× | let me = require(&viewer, &shell)?; |
| 656 | 3× | let mut token = String::new(); |
| 657 | 3× | let mut object: Vec<u8> = Vec::new(); |
| 658 | 9× | while let Ok(Some(field)) = multipart.next_field().await { |
| 659 | 6× | match field.name() { |
| 660 | 6× | Some("_csrf") => token = field.text().await.unwrap_or_default(), |
| 661 | 3× | Some("identity") => object = field.bytes().await.map(|b| b.to_vec()).unwrap_or_default(), |
| 662 | 0× | _ => {} |
| 663 | | } |
| 664 | | } |
| 665 | 3× | csrf(&viewer, &token, &shell)?; |
| 666 | 3× | let identity = match Identity::decode(&object) { |
| 667 | 3× | Ok(i) => i, |
| 668 | 0× | Err(e) => return keys_page(&app, shell, me.account, None, Some(format!("That is not an identity file: {e}")), None).await, |
| 669 | | }; |
| 670 | 3× | if identity.hash() == app.hub_key.key { |
| 671 | 1× | let msg = "That is this hub's own key, which only the hub holds. Upload your identity: after `oxy identity delegate add` with the hub's key, run `oxy identity export` in that checkout and upload the file it writes."; |
| 672 | 1× | return keys_page(&app, shell, me.account, None, Some(msg.into()), None).await; |
| 673 | 2× | } |
| 674 | 2× | let key = identity.hash().to_hex(); |
| 675 | 2× | if let Some(existing) = accounts::identity_by_key(&app.db, &key).await.map_err(|e| Error::from_db(shell.clone(), e))? { |
| 676 | 0× | let msg = if existing.account_id == me.account.id { |
| 677 | 0× | "That key is already linked to you. If you have delegated since (`oxy identity delegate add`), export again: a delegation makes a new version of your identity." |
| 678 | | } else { |
| 679 | 0× | "That key is linked to another account." |
| 680 | | }; |
| 681 | 0× | return keys_page(&app, shell, me.account, None, Some(msg.into()), None).await; |
| 682 | 2× | } |
| 683 | 2× | let bytes = auth::random_hex(32); |
| 684 | 2× | let id = accounts::create_challenge(&app.db, me.account.id, &bytes).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 685 | 2× | sqlx::query("UPDATE challenges SET object = $1 WHERE id = $2") |
| 686 | 2× | .bind(&object) |
| 687 | 2× | .bind(id) |
| 688 | 2× | .execute(&app.db) |
| 689 | 2× | .await |
| 690 | 2× | .map_err(|e| Error::from_db(shell.clone(), e))?; |
| 691 | 2× | keys_page(&app, shell, me.account, None, None, Some((id, bytes, identity.name))).await |
| 692 | 3× | } |
| 693 | |
|
| 694 | | #[derive(Deserialize)] |
| 695 | | pub struct KeyVerifyForm { |
| 696 | | #[serde(rename = "_csrf")] |
| 697 | | csrf_token: String, |
| 698 | | challenge: i64, |
| 699 | | signature: String, |
| 700 | | } |
| 701 | |
|
| 702 | 3× | pub async fn keys_verify(State(app): State<Shared>, viewer: Viewer, Form(f): Form<KeyVerifyForm>) -> Result<Page<KeysPage>, Error> { |
| 703 | 3× | let shell = Shell::new(&app, "/settings/keys", &viewer); |
| 704 | 3× | let me = require(&viewer, &shell)?; |
| 705 | 3× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 706 | 3× | let object: Option<Vec<u8>> = sqlx::query_scalar("SELECT object FROM challenges WHERE id = $1 AND account_id = $2") |
| 707 | 3× | .bind(f.challenge) |
| 708 | 3× | .bind(me.account.id) |
| 709 | 3× | .fetch_optional(&app.db) |
| 710 | 3× | .await |
| 711 | 3× | .map_err(|e| Error::from_db(shell.clone(), e))?; |
| 712 | 3× | let bytes = accounts::take_challenge(&app.db, me.account.id, f.challenge).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 713 | 3× | let (Some(object), Some(bytes)) = (object, bytes) else { |
| 714 | 1× | return keys_page(&app, shell, me.account, None, Some("That challenge has expired; upload the identity again.".into()), None).await; |
| 715 | | }; |
| 716 | 2× | let Ok(identity) = Identity::decode(&object) else { |
| 717 | 0× | return keys_page(&app, shell, me.account, None, Some("The stored identity is unreadable.".into()), None).await; |
| 718 | | }; |
| 719 | 2× | let sig_bytes = hex::decode(f.signature.trim()).unwrap_or_default(); |
| 720 | 2× | let sigs = Signature::decode_list(&sig_bytes).unwrap_or_default(); |
| 721 | 2× | let challenge = hex::decode(&bytes).unwrap_or_default(); |
| 722 | 2× | let ok = sigs.first().is_some_and(|sig| oxy_core::identity::verify_challenge(&identity, sig, &challenge).is_ok()); |
| 723 | 2× | if !ok { |
| 724 | | |
| 725 | | |
| 726 | 1× | let msg = match sigs.first() { |
| 727 | 1× | Some(sig) if sig.key != identity.hash() => format!( |
| 728 | | "That signature is by key {}, but the identity uploaded is {} ({}). Sign in a checkout whose `oxy identity export` gives that identity, without an `author.signer` set, or upload the identity that checkout exports.", |
| 729 | 1× | sig.key.short(12), |
| 730 | 1× | identity.hash().short(12), |
| 731 | | identity.name |
| 732 | | ), |
| 733 | 0× | _ => "The signature does not verify against that identity and challenge.".into(), |
| 734 | | }; |
| 735 | 1× | return keys_page(&app, shell, me.account, None, Some(msg), None).await; |
| 736 | 1× | } |
| 737 | 1× | let key = identity.hash().to_hex(); |
| 738 | 1× | accounts::link_identity(&app.db, me.account.id, &key, &identity.name, &identity.email, &object) |
| 739 | 1× | .await |
| 740 | 1× | .map_err(|e| Error::from_db(shell.clone(), e))?; |
| 741 | 1× | accounts::audit(&app.db, Some(&me.account), "identity.linked", &key, &identity.name).await.ok(); |
| 742 | 1× | keys_page(&app, shell, me.account, Some("Key linked. Changes signed with it are now yours on every page.".into()), None, None).await |
| 743 | 3× | } |
| 744 | |
|
| 745 | | #[derive(Deserialize)] |
| 746 | | pub struct KeyForm { |
| 747 | | #[serde(rename = "_csrf")] |
| 748 | | csrf_token: String, |
| 749 | | key: String, |
| 750 | | } |
| 751 | |
|
| 752 | 0× | pub async fn keys_unlink(State(app): State<Shared>, viewer: Viewer, Form(f): Form<KeyForm>) -> Result<Page<KeysPage>, Error> { |
| 753 | 0× | let shell = Shell::new(&app, "/settings/keys", &viewer); |
| 754 | 0× | let me = require(&viewer, &shell)?; |
| 755 | 0× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 756 | 0× | accounts::unlink_identity(&app.db, me.account.id, &f.key).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 757 | 0× | accounts::audit(&app.db, Some(&me.account), "identity.unlinked", &f.key, "").await.ok(); |
| 758 | 0× | keys_page(&app, shell, me.account, Some("Key unlinked.".into()), None, None).await |
| 759 | 0× | } |
| 760 | |
|
| 761 | |
|
| 762 | |
|
| 763 | | #[derive(Template)] |
| 764 | | #[template(path = "settings_tokens.html")] |
| 765 | | pub struct TokensPage { |
| 766 | | shell: Shell, |
| 767 | | scopes: &'static [(&'static str, &'static str)], |
| 768 | | me: accounts::Account, |
| 769 | | tokens: Vec<accounts::Token>, |
| 770 | | |
| 771 | | fresh: Option<String>, |
| 772 | | notice: Option<String>, |
| 773 | | error: Option<String>, |
| 774 | | } |
| 775 | |
|
| 776 | 50× | async fn tokens_page( |
| 777 | 50× | app: &Shared, |
| 778 | 50× | shell: Shell, |
| 779 | 50× | me: accounts::Account, |
| 780 | 50× | fresh: Option<String>, |
| 781 | 50× | notice: Option<String>, |
| 782 | 50× | error: Option<String>, |
| 783 | 50× | ) -> Result<Page<TokensPage>, Error> { |
| 784 | 50× | let tokens = accounts::tokens_of(&app.db, me.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 785 | 50× | Ok(Page(TokensPage { shell, scopes: SCOPES, me, tokens, fresh, notice, error })) |
| 786 | 50× | } |
| 787 | |
|
| 788 | 25× | pub async fn tokens(State(app): State<Shared>, viewer: Viewer) -> Result<Page<TokensPage>, Error> { |
| 789 | 25× | let shell = Shell::new(&app, "/settings/tokens", &viewer); |
| 790 | 25× | let me = require(&viewer, &shell)?; |
| 791 | 25× | tokens_page(&app, shell, me.account, None, None, None).await |
| 792 | 25× | } |
| 793 | |
|
| 794 | | #[derive(Deserialize)] |
| 795 | | pub struct TokenForm { |
| 796 | | #[serde(rename = "_csrf")] |
| 797 | | csrf_token: String, |
| 798 | | name: String, |
| 799 | | #[serde(default)] |
| 800 | | scopes: Vec<String>, |
| 801 | | #[serde(default)] |
| 802 | | repos: String, |
| 803 | | #[serde(default)] |
| 804 | | expires_days: String, |
| 805 | | |
| 806 | | #[serde(default)] |
| 807 | | agent: String, |
| 808 | | } |
| 809 | |
|
| 810 | |
|
| 811 | |
|
| 812 | | pub const SCOPES: &[(&str, &str)] = &[ |
| 813 | | ("repo:read", "read repositories you can see: clone, fetch, pull, and the read API"), |
| 814 | | ("repo:write", "push to repositories you can write to; also covers proposals, issues and checks"), |
| 815 | | ("repo:admin", "create repositories and change settings through the API"), |
| 816 | | ("proposals:write", "open, comment on and review proposals, without push access"), |
| 817 | | ("issues:write", "open, comment on and close issues, without push access"), |
| 818 | | ("checks:write", "report checks on states, for CI systems, without push access"), |
| 819 | | ("hooks:admin", "manage webhooks through the API"), |
| 820 | | ("user:read", "read your own profile through the API"), |
| 821 | | ]; |
| 822 | |
|
| 823 | 25× | pub async fn tokens_create( |
| 824 | 25× | State(app): State<Shared>, |
| 825 | 25× | viewer: Viewer, |
| 826 | 25× | axum_extra::extract::Form(f): axum_extra::extract::Form<TokenForm>, |
| 827 | 25× | ) -> Result<Page<TokensPage>, Error> { |
| 828 | 25× | let shell = Shell::new(&app, "/settings/tokens", &viewer); |
| 829 | 25× | let me = require(&viewer, &shell)?; |
| 830 | 25× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 831 | 25× | let name = f.name.trim(); |
| 832 | 25× | if name.is_empty() { |
| 833 | 0× | return tokens_page(&app, shell, me.account, None, None, Some("Give the token a name.".into())).await; |
| 834 | 25× | } |
| 835 | 92× | let scopes: Vec<&str> = f.scopes.iter().map(String::as_str).filter(|s| SCOPES.iter().any(|(k, _)| k == s)).collect(); |
| 836 | 25× | if scopes.is_empty() { |
| 837 | 0× | return tokens_page(&app, shell, me.account, None, None, Some("Pick at least one scope.".into())).await; |
| 838 | 25× | } |
| 839 | 25× | let expires_ms = f.expires_days.trim().parse::<i64>().ok().filter(|d| *d > 0).map(|d| db::now_ms() + d * 86_400_000); |
| 840 | 25× | let repos = f.repos.split(',').map(str::trim).filter(|r| !r.is_empty()).collect::<Vec<_>>().join(","); |
| 841 | 25× | let (secret, hash) = auth::new_token(); |
| 842 | 25× | accounts::create_token(&app.db, me.account.id, name, &hash, &scopes.join(","), &repos, expires_ms) |
| 843 | 25× | .await |
| 844 | 25× | .map_err(|e| Error::from_db(shell.clone(), e))?; |
| 845 | 25× | if !f.agent.is_empty() { |
| 846 | 0× | if let Ok(Some(t)) = accounts::token_by_hash(&app.db, &hash).await { |
| 847 | 0× | accounts::set_token_agent(&app.db, me.account.id, t.id, true).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 848 | 0× | } |
| 849 | 25× | } |
| 850 | 25× | accounts::audit(&app.db, Some(&me.account), "token.created", name, &scopes.join(",")).await.ok(); |
| 851 | 25× | tokens_page(&app, shell, me.account, Some(secret), Some("Copy the token now; it is not shown again.".into()), None).await |
| 852 | 25× | } |
| 853 | |
|
| 854 | |
|
| 855 | |
|
| 856 | 0× | pub async fn tokens_agent( |
| 857 | 0× | State(app): State<Shared>, |
| 858 | 0× | viewer: Viewer, |
| 859 | 0× | Path(id): Path<i64>, |
| 860 | 0× | Form(f): Form<super::session::CsrfForm>, |
| 861 | 0× | ) -> Result<Page<TokensPage>, Error> { |
| 862 | 0× | let shell = Shell::new(&app, "/settings/tokens", &viewer); |
| 863 | 0× | let me = require(&viewer, &shell)?; |
| 864 | 0× | csrf(&viewer, &f.csrf, &shell)?; |
| 865 | 0× | let tokens = accounts::tokens_of(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 866 | 0× | let Some(t) = tokens.iter().find(|t| t.id == id) else { |
| 867 | 0× | return tokens_page(&app, shell, me.account, None, None, Some("No such token.".into())).await; |
| 868 | | }; |
| 869 | 0× | accounts::set_token_agent(&app.db, me.account.id, id, !t.agent).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 870 | 0× | accounts::audit(&app.db, Some(&me.account), "token.agent", &t.name, if t.agent { "off" } else { "on" }).await.ok(); |
| 871 | 0× | let notice = if t.agent { |
| 872 | 0× | format!("{} is no longer marked as an agent's.", t.name) |
| 873 | | } else { |
| 874 | 0× | format!("{} is an agent's: you will hear what it does.", t.name) |
| 875 | | }; |
| 876 | 0× | tokens_page(&app, shell, me.account, None, Some(notice), None).await |
| 877 | 0× | } |
| 878 | |
|
| 879 | 0× | pub async fn tokens_delete( |
| 880 | 0× | State(app): State<Shared>, |
| 881 | 0× | viewer: Viewer, |
| 882 | 0× | Path(id): Path<i64>, |
| 883 | 0× | Form(f): Form<super::session::CsrfForm>, |
| 884 | 0× | ) -> Result<Page<TokensPage>, Error> { |
| 885 | 0× | let shell = Shell::new(&app, "/settings/tokens", &viewer); |
| 886 | 0× | let me = require(&viewer, &shell)?; |
| 887 | 0× | csrf(&viewer, &f.csrf, &shell)?; |
| 888 | 0× | accounts::delete_token(&app.db, me.account.id, id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 889 | 0× | accounts::audit(&app.db, Some(&me.account), "token.deleted", &id.to_string(), "").await.ok(); |
| 890 | 0× | tokens_page(&app, shell, me.account, None, Some("Token deleted.".into()), None).await |
| 891 | 0× | } |
| 892 | |
|
| 893 | | #[cfg(test)] |
| 894 | | mod tests { |
| 895 | | use super::browser_of; |
| 896 | |
|
| 897 | | #[test] |
| 898 | 1× | fn browsers_are_named_from_their_agent() { |
| 899 | 1× | let ff = "Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0"; |
| 900 | 1× | let chrome_mac = |
| 901 | 1× | "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0 Safari/537.36"; |
| 902 | 1× | let edge = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0 Safari/537.36 Edg/129.0"; |
| 903 | 1× | let iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Mobile/15E148 Safari/604.1"; |
| 904 | 1× | assert_eq!(browser_of(ff), "Firefox on Linux"); |
| 905 | 1× | assert_eq!(browser_of(chrome_mac), "Chrome on macOS"); |
| 906 | 1× | assert_eq!(browser_of(edge), "Edge on Windows"); |
| 907 | 1× | assert_eq!(browser_of(iphone), "Safari on iOS"); |
| 908 | 1× | assert_eq!(browser_of(""), "Unknown browser"); |
| 909 | 1× | } |
| 910 | | } |