OXYGENHUB
# 43e8ca33bc5d oxygenhub / crates / hub / src / web / mod.rs
22.6 KiB · Rust · last changed Help: getting started filled in for this hub, delegation, pipelines and stamps, the keyboard, and a glossary for people coming from GitHub 1 month ago source blame history raw
1
//! Pages (hub spec §6): the router, the shell every template extends, the
2
//! error page, viewer-aware lookups and askama filters. Handlers are thin:
3
//! they resolve names, call the view layer under the repository lock, and
4
//! render.
5
6
mod admin;
7
mod avatar;
8
pub mod edit;
9
pub mod filters;
10
pub mod flow;
11
mod forks;
12
pub mod help;
13
pub mod history;
14
mod home;
15
mod inbox;
16
pub mod issues;
17
mod orgs;
18
pub mod proposals;
19
mod refs;
20
pub mod releases;
21
mod repo;
22
mod repo_settings;
23
mod session;
24
mod settings;
25
mod statics;
26
27
use crate::auth::{self, Access, Role, Viewer};
28
use crate::repos::RepoError;
29
use crate::{db, Shared};
30
use askama::Template;
31
use axum::extract::DefaultBodyLimit;
32
use axum::http::{header, StatusCode};
33
use axum::response::{Html, IntoResponse, Redirect, Response};
34
use axum::routing::{any, get, post};
35
use axum::Router;
36
use tower_http::compression::CompressionLayer;
37
use tower_http::trace::TraceLayer;
38
39
pub fn router(app: Shared) -> Router {
40
    let push_limit = app.config.limits.push_body_limit.0 as usize;
41
    Router::new()
42
        .route("/", get(home::index))
43
        .route("/explore", get(home::explore))
44
        .route("/avatar/{name}", get(avatar::avatar))
45
        .route("/health", get(home::health))
46
        .route("/.well-known/oxyhub-key", get(home::hub_key))
47
        .route("/style.css", get(statics::style))
48
        .route("/favicon.svg", get(statics::favicon))
49
        .route("/favicon.ico", get(statics::favicon))
50
        .route("/static/{*path}", get(statics::asset))
51
        .route("/login", get(session::login_form).post(session::login))
52
        .route("/logout", post(session::logout))
53
        .route("/register", get(session::register_form).post(session::register))
54
        .route("/settings", get(settings::profile).post(settings::update_profile))
55
        .route("/settings/password", post(settings::change_password))
56
        .route("/settings/appearance", post(settings::appearance))
57
        .route("/settings/security", get(settings::security))
58
        .route("/settings/security/totp/begin", post(settings::totp_begin))
59
        .route("/settings/security/totp/enable", post(settings::totp_enable))
60
        .route("/settings/security/totp/disable", post(settings::totp_disable))
61
        .route("/settings/security/sessions", post(settings::sessions_reset))
62
        .route("/settings/keys", get(settings::keys))
63
        .route("/settings/keys/upload", post(settings::keys_upload))
64
        .route("/settings/keys/verify", post(settings::keys_verify))
65
        .route("/settings/keys/unlink", post(settings::keys_unlink))
66
        .route("/settings/tokens", get(settings::tokens).post(settings::tokens_create))
67
        .route("/settings/tokens/{id}/delete", post(settings::tokens_delete))
68
        .route("/new", get(repo_settings::new_form).post(repo_settings::create))
69
        .route("/orgs/new", get(orgs::new_form).post(orgs::create))
70
        .route("/orgs/{name}/settings", get(orgs::settings).post(orgs::update))
71
        .route("/orgs/{name}/settings/members", post(orgs::member))
72
        .route("/orgs/{name}/settings/teams", post(orgs::team))
73
        .route("/notifications", get(inbox::inbox))
74
        .route("/notifications/read", post(inbox::mark_read))
75
        .route("/settings/notifications", get(inbox::unsubscribe).post(inbox::prefs))
76
        .route("/search", get(inbox::search))
77
        .route("/admin", get(admin::index))
78
        .route("/admin/registration", post(admin::set_mode))
79
        .route("/admin/invite", post(admin::invite))
80
        .route("/admin/account", post(admin::account))
81
        .nest("/api/v1", crate::api::router())
82
        .route("/{owner}", get(home::owner))
83
        .route("/{owner}/{name}", get(repo::overview))
84
        .route("/{owner}/{name}/tree/{r}", get(repo::tree_root))
85
        .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree))
86
        .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file))
87
        .route("/{owner}/{name}/last/{r}", get(repo::last_changes))
88
        .route("/{owner}/{name}/changes/{r}", get(history::history))
89
        .route("/{owner}/{name}/change/{hash}", get(history::change))
90
        .route("/help", get(help::help))
91
        .route("/{owner}/{name}/compare", get(history::compare_index))
92
        .route("/{owner}/{name}/compare/{spec}", get(history::compare))
93
        .route("/{owner}/{name}/bookmarks", get(refs::bookmarks))
94
        .route("/{owner}/{name}/tags", get(refs::tags))
95
        .route("/{owner}/{name}/conflicts", get(refs::conflicts))
96
        .route("/{owner}/{name}/trust", get(refs::trust))
97
        .route("/{owner}/{name}/pushes", get(refs::pushes))
98
        .route("/{owner}/{name}/fork", get(forks::form).post(forks::create))
99
        .route("/{owner}/{name}/forks", get(forks::list))
100
        .route("/{owner}/{name}/settings", get(repo_settings::settings).post(repo_settings::update))
101
        .route("/{owner}/{name}/settings/collaborators", post(repo_settings::collaborator))
102
        .route("/{owner}/{name}/settings/delete", post(repo_settings::delete))
103
        .route("/{owner}/{name}/settings/requirements", post(repo_settings::requirements))
104
        .route("/{owner}/{name}/proposals", get(proposals::list))
105
        .route("/{owner}/{name}/proposals/new", get(proposals::new_form).post(proposals::create))
106
        .route("/{owner}/{name}/proposal/{number}", get(proposals::show))
107
        .route("/{owner}/{name}/proposal/{number}/comment", post(proposals::comment))
108
        .route("/{owner}/{name}/proposal/{number}/comment/{id}/resolve", post(proposals::resolve_comment))
109
        .route("/{owner}/{name}/proposal/{number}/review", post(proposals::review))
110
        .route("/{owner}/{name}/proposal/{number}/edit", post(proposals::edit))
111
        .route("/{owner}/{name}/proposal/{number}/state", post(proposals::state))
112
        .route("/{owner}/{name}/proposal/{number}/land", post(proposals::land))
113
        .route("/{owner}/{name}/proposal/{number}/labels", post(proposals::set_labels))
114
        .route("/{owner}/{name}/proposal/{number}/events", get(proposals::events))
115
        .route("/{owner}/{name}/settings/hooks", post(repo_settings::hooks))
116
        .route("/{owner}/{name}/settings/hooks/{id}/deliveries", get(repo_settings::deliveries))
117
        .route("/{owner}/{name}/settings/hooks/{id}/redeliver/{delivery}", post(repo_settings::redeliver))
118
        .route("/{owner}/{name}/settings/checks", post(repo_settings::required_checks))
119
        .route("/{owner}/{name}/watch", post(issues::watch))
120
        .route("/{owner}/{name}/star", post(issues::star))
121
        .route("/{owner}/{name}/edit/{r}", post(edit::save))
122
        .route("/{owner}/{name}/edit/{r}/{*path}", get(edit::edit_form))
123
        .route("/{owner}/{name}/newfile/{r}", get(edit::new_form))
124
        .route("/{owner}/{name}/flow", get(flow::runs))
125
        .route("/{owner}/{name}/flow/{id}", get(flow::run))
126
        .route("/{owner}/{name}/flow/{id}/live", get(flow::live))
127
        .route("/{owner}/{name}/releases", get(releases::list))
128
        .route("/{owner}/{name}/releases/new", get(releases::new_form).post(releases::create))
129
        .route("/{owner}/{name}/releases/tag/{*tag}", get(releases::show))
130
        .route("/{owner}/{name}/releases/edit/{id}", post(releases::edit))
131
        .route(
132
            "/{owner}/{name}/releases/upload/{id}",
133
            post(releases::upload).layer(DefaultBodyLimit::max(app.config.limits.asset_limit.0 as usize + (1 << 20))),
134
        )
135
        .route("/{owner}/{name}/asset/{id}/{file}", get(releases::download))
136
        .route("/{owner}/{name}/archive", get(releases::source_archive))
137
        .route("/{owner}/{name}/search", get(repo::code_search))
138
        .route("/{owner}/{name}/info/{*rest}", any(git_info))
139
        .route("/{owner}/{name}/HEAD", get(git_head))
140
        .route("/{owner}/{name}/objects/{*rest}", get(git_objects))
141
        .route("/{owner}/{name}/git-upload-pack", post(git_upload_pack))
142
        .route("/{owner}/{name}/git-receive-pack", post(git_receive_pack))
143
        .route("/{owner}/{name}/settings/mirror", post(repo_settings::mirror))
144
        .route("/{owner}/{name}/issues", get(issues::list))
145
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
146
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
147
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
148
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
149
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
150
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
151
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
152
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
153
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
154
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
155
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
156
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
157
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
158
        .fallback(not_found)
159
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
160
        .layer(CompressionLayer::new())
161
        .layer(TraceLayer::new_for_http())
162
        .with_state(app)
163
}
164
165
// Git's smart HTTP paths under `/{owner}/{name}.git/`, forwarded to the
166
// mirror (hub spec §14).
167
async fn git_info(
168
    st: axum::extract::State<Shared>,
169
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
170
    m: axum::http::Method,
171
    q: axum::extract::RawQuery,
172
    h: axum::http::HeaderMap,
173
    b: axum::body::Bytes,
174
) -> Response {
175
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await
176
}
177
178
async fn git_head(
179
    st: axum::extract::State<Shared>,
180
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
181
    m: axum::http::Method,
182
    q: axum::extract::RawQuery,
183
    h: axum::http::HeaderMap,
184
    b: axum::body::Bytes,
185
) -> Response {
186
    crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await
187
}
188
189
async fn git_objects(
190
    st: axum::extract::State<Shared>,
191
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
192
    m: axum::http::Method,
193
    q: axum::extract::RawQuery,
194
    h: axum::http::HeaderMap,
195
    b: axum::body::Bytes,
196
) -> Response {
197
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await
198
}
199
200
async fn git_upload_pack(
201
    st: axum::extract::State<Shared>,
202
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
203
    m: axum::http::Method,
204
    q: axum::extract::RawQuery,
205
    h: axum::http::HeaderMap,
206
    b: axum::body::Bytes,
207
) -> Response {
208
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await
209
}
210
211
async fn git_receive_pack(
212
    st: axum::extract::State<Shared>,
213
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
214
    m: axum::http::Method,
215
    q: axum::extract::RawQuery,
216
    h: axum::http::HeaderMap,
217
    b: axum::body::Bytes,
218
) -> Response {
219
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await
220
}
221
222
/// Cross-site form posts are refused (hub spec §15.2): a browser that
223
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
224
/// API clients send neither.
225
async fn same_origin(
226
    axum::extract::State(app): axum::extract::State<Shared>,
227
    req: axum::extract::Request,
228
    next: axum::middleware::Next,
229
) -> Response {
230
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
231
        let headers = req.headers();
232
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
233
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
234
        }
235
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
236
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
237
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
238
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
239
            if !ok && origin != "null" {
240
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
241
            }
242
        }
243
    }
244
    next.run(req).await
245
}
246
247
/// What every page's chrome needs.
248
#[derive(Clone, Debug)]
249
pub struct Shell {
250
    pub site: String,
251
    pub base_url: String,
252
    pub path: String,
253
    pub version: &'static str,
254
    /// The signed-in username, if any.
255
    pub user: Option<String>,
256
    pub is_admin: bool,
257
    pub csrf: String,
258
    pub unread: i64,
259
}
260
261
impl Shell {
262
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
263
        Shell {
264
            site: app.config.site.name.clone(),
265
            base_url: app.config.base_url().to_string(),
266
            path: path.to_string(),
267
            version: env!("CARGO_PKG_VERSION"),
268
            user: viewer.account().map(|a| a.username.clone()),
269
            is_admin: viewer.is_admin(),
270
            csrf: viewer.csrf().to_string(),
271
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
272
        }
273
    }
274
275
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
276
        Shell::new(app, path, &Viewer(None))
277
    }
278
}
279
280
/// The repository chrome: tabs and counts.
281
#[derive(Clone, Debug)]
282
pub struct RepoShell {
283
    pub owner: String,
284
    pub name: String,
285
    pub url: String,
286
    pub description: String,
287
    pub default_bookmark: String,
288
    pub visibility: String,
289
    pub tab: &'static str,
290
    pub clone_url: String,
291
    /// The viewer's role, for showing settings and write actions.
292
    pub role: Option<Role>,
293
    /// Open issues and proposals, shown on their tabs.
294
    pub open_issues: i64,
295
    pub open_proposals: i64,
296
}
297
298
impl RepoShell {
299
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
300
        RepoShell {
301
            owner: row.owner.clone(),
302
            name: row.name.clone(),
303
            url: format!("/{}/{}", row.owner, row.name),
304
            description: row.description.clone(),
305
            default_bookmark: row.default_bookmark.clone(),
306
            visibility: row.visibility.clone(),
307
            tab,
308
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
309
            role: None,
310
            open_issues: row.open_issues,
311
            open_proposals: row.open_proposals,
312
        }
313
    }
314
315
    pub fn with_role(mut self, role: Role) -> RepoShell {
316
        self.role = Some(role);
317
        self
318
    }
319
320
    pub fn can(&self, access: Access) -> bool {
321
        auth::roles::allows(self.role, access)
322
    }
323
324
    pub fn can_maintain(&self) -> bool {
325
        self.can(Access::Maintain)
326
    }
327
}
328
329
/// Render a template as an HTML response.
330
/// One page of a long list: which page, how many, and links that keep
331
/// the rest of the query.
332
#[derive(Clone, Debug)]
333
pub struct Pager {
334
    pub page: usize,
335
    pub pages: usize,
336
    pub total: usize,
337
    /// The query without `page`, each pair encoded, joined with `&`.
338
    query: String,
339
}
340
341
impl Pager {
342
    pub const PER_PAGE: usize = 25;
343
344
    /// `page` counts from 1; out-of-range pages clamp to the last.
345
    pub fn new(total: usize, page: Option<usize>, query: &[(&str, &str)]) -> Pager {
346
        let pages = total.div_ceil(Self::PER_PAGE).max(1);
347
        let page = page.unwrap_or(1).clamp(1, pages);
348
        let query = query
349
            .iter()
350
            .filter(|(_, v)| !v.is_empty())
351
            .map(|(k, v)| format!("{k}={}", settings::urlencode(v).replace('/', "%2F")))
352
            .collect::<Vec<_>>()
353
            .join("&");
354
        Pager { page, pages, total, query }
355
    }
356
357
    /// This page's items.
358
    pub fn slice<T>(&self, all: Vec<T>) -> Vec<T> {
359
        all.into_iter().skip((self.page - 1) * Self::PER_PAGE).take(Self::PER_PAGE).collect()
360
    }
361
362
    pub fn url(&self, page: usize) -> String {
363
        if self.query.is_empty() {
364
            format!("?page={page}")
365
        } else {
366
            format!("?{}&page={page}", self.query)
367
        }
368
    }
369
370
    /// The same query with another sort, back on page one.
371
    pub fn sorted(&self, sort: &str) -> String {
372
        let rest: Vec<&str> = self.query.split('&').filter(|p| !p.is_empty() && !p.starts_with("sort=")).collect();
373
        let mut q = rest.join("&");
374
        if !q.is_empty() {
375
            q.push('&');
376
        }
377
        format!("?{q}sort={sort}")
378
    }
379
}
380
381
pub struct Page<T: Template>(pub T);
382
383
impl<T: Template> IntoResponse for Page<T> {
384
    fn into_response(self) -> Response {
385
        match self.0.render() {
386
            Ok(s) => Html(s).into_response(),
387
            Err(e) => {
388
                tracing::error!("template: {e}");
389
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
390
            }
391
        }
392
    }
393
}
394
395
#[derive(Template)]
396
#[template(path = "error.html")]
397
struct ErrorPage {
398
    shell: Shell,
399
    status: u16,
400
    title: String,
401
    detail: String,
402
}
403
404
/// A page-level failure, rendered inside the shell, or a redirect.
405
#[derive(Debug)]
406
pub struct Error {
407
    pub status: StatusCode,
408
    pub detail: String,
409
    shell: Option<Box<Shell>>,
410
    redirect: Option<String>,
411
}
412
413
impl Error {
414
    pub fn redirect(to: String) -> Error {
415
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
416
    }
417
418
    pub fn not_found(shell: Shell) -> Error {
419
        Error {
420
            status: StatusCode::NOT_FOUND,
421
            detail: "There is nothing at this address.".into(),
422
            shell: Some(Box::new(shell)),
423
            redirect: None,
424
        }
425
    }
426
427
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
428
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
429
    }
430
431
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
432
        match e {
433
            RepoError::NotFound => Error::not_found(shell),
434
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
435
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
436
            }
437
            other => {
438
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
439
            }
440
        }
441
    }
442
443
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
444
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
445
    }
446
}
447
448
impl IntoResponse for Error {
449
    fn into_response(self) -> Response {
450
        if let Some(to) = self.redirect {
451
            return Redirect::to(&to).into_response();
452
        }
453
        let title = match self.status {
454
            StatusCode::NOT_FOUND => "Not found",
455
            StatusCode::BAD_REQUEST => "Bad request",
456
            _ => "Something went wrong",
457
        };
458
        if self.status.is_server_error() {
459
            tracing::error!("{}", self.detail);
460
        }
461
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
462
            site: "Oxygenhub".into(),
463
            base_url: String::new(),
464
            path: String::new(),
465
            version: "",
466
            user: None,
467
            is_admin: false,
468
            csrf: String::new(),
469
            unread: 0,
470
        });
471
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
472
        match page.render() {
473
            Ok(s) => (self.status, Html(s)).into_response(),
474
            Err(_) => (self.status, title).into_response(),
475
        }
476
    }
477
}
478
479
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
480
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
481
}
482
483
/// A raw file response with a safe content type (hub spec §15.2).
484
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
485
    let mime = mime_of(name);
486
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
487
    (
488
        [
489
            (header::CONTENT_TYPE, mime.to_string()),
490
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
491
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
492
        ],
493
        bytes,
494
    )
495
        .into_response()
496
}
497
498
pub fn mime_of(name: &str) -> &'static str {
499
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
500
        Some("png") => "image/png",
501
        Some("jpg" | "jpeg") => "image/jpeg",
502
        Some("gif") => "image/gif",
503
        Some("webp") => "image/webp",
504
        Some("svg") => "image/svg+xml",
505
        Some("pdf") => "application/pdf",
506
        Some(
507
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
508
        ) => "text/plain; charset=utf-8",
509
        _ => "application/octet-stream",
510
    }
511
}
512
513
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
514
/// a repository the viewer may not see does not exist for them (hub spec
515
/// §4.4). Returns the viewer's role too.
516
pub async fn lookup_role(
517
    app: &Shared,
518
    shell: &Shell,
519
    viewer: &Viewer,
520
    owner: &str,
521
    name: &str,
522
    access: Access,
523
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
524
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
525
    let row = db::repos::get(&app.db, owner, name)
526
        .await
527
        .map_err(|e| Error::from_db(shell.clone(), e))?
528
        .ok_or_else(|| Error::not_found(shell.clone()))?;
529
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
530
    if !auth::roles::allows(role, access) {
531
        return Err(Error::not_found(shell.clone()));
532
    }
533
    Ok((repo, row, role.unwrap_or(Role::Read)))
534
}
535
536
/// `lookup_role` for reading.
537
pub async fn lookup(
538
    app: &Shared,
539
    shell: &Shell,
540
    viewer: &Viewer,
541
    owner: &str,
542
    name: &str,
543
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
544
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
545
}
546
547
/// Fill `account` on change authors whose key is linked to an account.
548
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
549
    if changes.is_empty() {
550
        return;
551
    }
552
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
553
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
554
    for c in changes.iter_mut() {
555
        if let Some(u) = map.get(&c.author.key) {
556
            c.author.account = Some(u.clone());
557
        }
558
    }
559
}