| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 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 history; |
| 13 |
mod home; |
| 14 |
mod inbox; |
| 15 |
pub mod issues; |
| 16 |
mod orgs; |
| 17 |
pub mod proposals; |
| 18 |
mod refs; |
| 19 |
pub mod releases; |
| 20 |
mod repo; |
| 21 |
mod repo_settings; |
| 22 |
mod resolve; |
| 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("/{owner}/{name}/compare/{spec}", get(history::compare)) |
| 91 |
.route("/{owner}/{name}/bookmarks", get(refs::bookmarks)) |
| 92 |
.route("/{owner}/{name}/tags", get(refs::tags)) |
| 93 |
.route("/{owner}/{name}/conflicts", get(refs::conflicts)) |
| 94 |
.route("/{owner}/{name}/trust", get(refs::trust)) |
| 95 |
.route("/{owner}/{name}/pushes", get(refs::pushes)) |
| 96 |
.route("/{owner}/{name}/fork", get(forks::form).post(forks::create)) |
| 97 |
.route("/{owner}/{name}/forks", get(forks::list)) |
| 98 |
.route("/{owner}/{name}/settings", get(repo_settings::settings).post(repo_settings::update)) |
| 99 |
.route("/{owner}/{name}/settings/collaborators", post(repo_settings::collaborator)) |
| 100 |
.route("/{owner}/{name}/settings/delete", post(repo_settings::delete)) |
| 101 |
.route("/{owner}/{name}/settings/requirements", post(repo_settings::requirements)) |
| 102 |
.route("/{owner}/{name}/proposals", get(proposals::list)) |
| 103 |
.route("/{owner}/{name}/proposals/new", get(proposals::new_form).post(proposals::create)) |
| 104 |
.route("/{owner}/{name}/proposal/{number}", get(proposals::show)) |
| 105 |
.route("/{owner}/{name}/proposal/{number}/comment", post(proposals::comment)) |
| 106 |
.route("/{owner}/{name}/proposal/{number}/comment/{id}/resolve", post(proposals::resolve_comment)) |
| 107 |
.route("/{owner}/{name}/proposal/{number}/review", post(proposals::review)) |
| 108 |
.route("/{owner}/{name}/proposal/{number}/edit", post(proposals::edit)) |
| 109 |
.route("/{owner}/{name}/proposal/{number}/state", post(proposals::state)) |
| 110 |
.route("/{owner}/{name}/proposal/{number}/land", post(proposals::land)) |
| 111 |
.route("/{owner}/{name}/proposal/{number}/labels", post(proposals::set_labels)) |
| 112 |
.route("/{owner}/{name}/proposal/{number}/events", get(proposals::events)) |
| 113 |
.route("/{owner}/{name}/settings/hooks", post(repo_settings::hooks)) |
| 114 |
.route("/{owner}/{name}/settings/hooks/{id}/deliveries", get(repo_settings::deliveries)) |
| 115 |
.route("/{owner}/{name}/settings/hooks/{id}/redeliver/{delivery}", post(repo_settings::redeliver)) |
| 116 |
.route("/{owner}/{name}/settings/checks", post(repo_settings::required_checks)) |
| 117 |
.route("/{owner}/{name}/watch", post(issues::watch)) |
| 118 |
.route("/{owner}/{name}/star", post(issues::star)) |
| 119 |
.route("/{owner}/{name}/edit/{r}", post(edit::save)) |
| 120 |
.route("/{owner}/{name}/edit/{r}/{*path}", get(edit::edit_form)) |
| 121 |
.route("/{owner}/{name}/resolve/{bookmark}/{*path}", get(resolve::form).post(resolve::save)) |
| 122 |
.route("/{owner}/{name}/newfile/{r}", get(edit::new_form)) |
| 123 |
.route("/{owner}/{name}/flow", get(flow::runs)) |
| 124 |
.route("/{owner}/{name}/flow/{id}", get(flow::run)) |
| 125 |
.route("/{owner}/{name}/flow/{id}/live", get(flow::live)) |
| 126 |
.route("/{owner}/{name}/releases", get(releases::list)) |
| 127 |
.route("/{owner}/{name}/releases/new", get(releases::new_form).post(releases::create)) |
| 128 |
.route("/{owner}/{name}/releases/tag/{*tag}", get(releases::show)) |
| 129 |
.route("/{owner}/{name}/releases/edit/{id}", post(releases::edit)) |
| 130 |
.route( |
| 131 |
"/{owner}/{name}/releases/upload/{id}", |
| 132 |
post(releases::upload).layer(DefaultBodyLimit::max(app.config.limits.asset_limit.0 as usize + (1 << 20))), |
| 133 |
) |
| 134 |
.route("/{owner}/{name}/asset/{id}/{file}", get(releases::download)) |
| 135 |
.route("/{owner}/{name}/archive", get(releases::source_archive)) |
| 136 |
.route("/{owner}/{name}/search", get(repo::code_search)) |
| 137 |
.route("/{owner}/{name}/info/{*rest}", any(git_info)) |
| 138 |
.route("/{owner}/{name}/HEAD", get(git_head)) |
| 139 |
.route("/{owner}/{name}/objects/{*rest}", get(git_objects)) |
| 140 |
.route("/{owner}/{name}/git-upload-pack", post(git_upload_pack)) |
| 141 |
.route("/{owner}/{name}/git-receive-pack", post(git_receive_pack)) |
| 142 |
.route("/{owner}/{name}/settings/mirror", post(repo_settings::mirror)) |
| 143 |
.route("/{owner}/{name}/issues", get(issues::list)) |
| 144 |
.route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create)) |
| 145 |
.route("/{owner}/{name}/issue/{number}", get(issues::show)) |
| 146 |
.route("/{owner}/{name}/issue/{number}/comment", post(issues::comment)) |
| 147 |
.route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment)) |
| 148 |
.route("/{owner}/{name}/issue/{number}/edit", post(issues::edit)) |
| 149 |
.route("/{owner}/{name}/issue/{number}/state", post(issues::state)) |
| 150 |
.route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels)) |
| 151 |
.route("/{owner}/{name}/issue/{number}/assign", post(issues::assign)) |
| 152 |
.route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone)) |
| 153 |
.route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe)) |
| 154 |
.route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label)) |
| 155 |
.route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone)) |
| 156 |
.route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit))) |
| 157 |
.fallback(not_found) |
| 158 |
.layer(axum::middleware::from_fn_with_state(app.clone(), same_origin)) |
| 159 |
.layer(CompressionLayer::new()) |
| 160 |
.layer(TraceLayer::new_for_http()) |
| 161 |
.with_state(app) |
| 162 |
} |
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
async fn git_info( |
| 167 |
st: axum::extract::State<Shared>, |
| 168 |
axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>, |
| 169 |
m: axum::http::Method, |
| 170 |
q: axum::extract::RawQuery, |
| 171 |
h: axum::http::HeaderMap, |
| 172 |
b: axum::body::Bytes, |
| 173 |
) -> Response { |
| 174 |
crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await |
| 175 |
} |
| 176 |
|
| 177 |
async fn git_head( |
| 178 |
st: axum::extract::State<Shared>, |
| 179 |
axum::extract::Path((o, n)): axum::extract::Path<(String, String)>, |
| 180 |
m: axum::http::Method, |
| 181 |
q: axum::extract::RawQuery, |
| 182 |
h: axum::http::HeaderMap, |
| 183 |
b: axum::body::Bytes, |
| 184 |
) -> Response { |
| 185 |
crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await |
| 186 |
} |
| 187 |
|
| 188 |
async fn git_objects( |
| 189 |
st: axum::extract::State<Shared>, |
| 190 |
axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>, |
| 191 |
m: axum::http::Method, |
| 192 |
q: axum::extract::RawQuery, |
| 193 |
h: axum::http::HeaderMap, |
| 194 |
b: axum::body::Bytes, |
| 195 |
) -> Response { |
| 196 |
crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await |
| 197 |
} |
| 198 |
|
| 199 |
async fn git_upload_pack( |
| 200 |
st: axum::extract::State<Shared>, |
| 201 |
axum::extract::Path((o, n)): axum::extract::Path<(String, String)>, |
| 202 |
m: axum::http::Method, |
| 203 |
q: axum::extract::RawQuery, |
| 204 |
h: axum::http::HeaderMap, |
| 205 |
b: axum::body::Bytes, |
| 206 |
) -> Response { |
| 207 |
crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await |
| 208 |
} |
| 209 |
|
| 210 |
async fn git_receive_pack( |
| 211 |
st: axum::extract::State<Shared>, |
| 212 |
axum::extract::Path((o, n)): axum::extract::Path<(String, String)>, |
| 213 |
m: axum::http::Method, |
| 214 |
q: axum::extract::RawQuery, |
| 215 |
h: axum::http::HeaderMap, |
| 216 |
b: axum::body::Bytes, |
| 217 |
) -> Response { |
| 218 |
crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await |
| 219 |
} |
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
async fn same_origin( |
| 225 |
axum::extract::State(app): axum::extract::State<Shared>, |
| 226 |
req: axum::extract::Request, |
| 227 |
next: axum::middleware::Next, |
| 228 |
) -> Response { |
| 229 |
if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD { |
| 230 |
let headers = req.headers(); |
| 231 |
if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") { |
| 232 |
return (StatusCode::FORBIDDEN, "cross-site request refused").into_response(); |
| 233 |
} |
| 234 |
if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) { |
| 235 |
let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase(); |
| 236 |
let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase()); |
| 237 |
let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str()); |
| 238 |
if !ok && origin != "null" { |
| 239 |
return (StatusCode::FORBIDDEN, "cross-site request refused").into_response(); |
| 240 |
} |
| 241 |
} |
| 242 |
} |
| 243 |
next.run(req).await |
| 244 |
} |
| 245 |
|
| 246 |
|
| 247 |
#[derive(Clone, Debug)] |
| 248 |
pub struct Shell { |
| 249 |
pub site: String, |
| 250 |
pub base_url: String, |
| 251 |
pub path: String, |
| 252 |
pub version: &'static str, |
| 253 |
|
| 254 |
pub user: Option<String>, |
| 255 |
pub is_admin: bool, |
| 256 |
pub csrf: String, |
| 257 |
pub unread: i64, |
| 258 |
} |
| 259 |
|
| 260 |
impl Shell { |
| 261 |
pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell { |
| 262 |
Shell { |
| 263 |
site: app.config.site.name.clone(), |
| 264 |
base_url: app.config.base_url().to_string(), |
| 265 |
path: path.to_string(), |
| 266 |
version: env!("CARGO_PKG_VERSION"), |
| 267 |
user: viewer.account().map(|a| a.username.clone()), |
| 268 |
is_admin: viewer.is_admin(), |
| 269 |
csrf: viewer.csrf().to_string(), |
| 270 |
unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0), |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
pub fn anonymous(app: &Shared, path: &str) -> Shell { |
| 275 |
Shell::new(app, path, &Viewer(None)) |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
|
| 280 |
#[derive(Clone, Debug)] |
| 281 |
pub struct RepoShell { |
| 282 |
pub owner: String, |
| 283 |
pub name: String, |
| 284 |
pub url: String, |
| 285 |
pub description: String, |
| 286 |
pub default_bookmark: String, |
| 287 |
pub visibility: String, |
| 288 |
pub tab: &'static str, |
| 289 |
pub clone_url: String, |
| 290 |
|
| 291 |
pub role: Option<Role>, |
| 292 |
|
| 293 |
pub open_issues: i64, |
| 294 |
pub open_proposals: i64, |
| 295 |
} |
| 296 |
|
| 297 |
impl RepoShell { |
| 298 |
pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell { |
| 299 |
RepoShell { |
| 300 |
owner: row.owner.clone(), |
| 301 |
name: row.name.clone(), |
| 302 |
url: format!("/{}/{}", row.owner, row.name), |
| 303 |
description: row.description.clone(), |
| 304 |
default_bookmark: row.default_bookmark.clone(), |
| 305 |
visibility: row.visibility.clone(), |
| 306 |
tab, |
| 307 |
clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name), |
| 308 |
role: None, |
| 309 |
open_issues: row.open_issues, |
| 310 |
open_proposals: row.open_proposals, |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
pub fn with_role(mut self, role: Role) -> RepoShell { |
| 315 |
self.role = Some(role); |
| 316 |
self |
| 317 |
} |
| 318 |
|
| 319 |
pub fn can(&self, access: Access) -> bool { |
| 320 |
auth::roles::allows(self.role, access) |
| 321 |
} |
| 322 |
|
| 323 |
pub fn can_maintain(&self) -> bool { |
| 324 |
self.can(Access::Maintain) |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
#[derive(Clone, Debug)] |
| 332 |
pub struct Pager { |
| 333 |
pub page: usize, |
| 334 |
pub pages: usize, |
| 335 |
pub total: usize, |
| 336 |
|
| 337 |
query: String, |
| 338 |
} |
| 339 |
|
| 340 |
impl Pager { |
| 341 |
pub const PER_PAGE: usize = 25; |
| 342 |
|
| 343 |
|
| 344 |
pub fn new(total: usize, page: Option<usize>, query: &[(&str, &str)]) -> Pager { |
| 345 |
let pages = total.div_ceil(Self::PER_PAGE).max(1); |
| 346 |
let page = page.unwrap_or(1).clamp(1, pages); |
| 347 |
let query = query |
| 348 |
.iter() |
| 349 |
.filter(|(_, v)| !v.is_empty()) |
| 350 |
.map(|(k, v)| format!("{k}={}", settings::urlencode(v).replace('/', "%2F"))) |
| 351 |
.collect::<Vec<_>>() |
| 352 |
.join("&"); |
| 353 |
Pager { page, pages, total, query } |
| 354 |
} |
| 355 |
|
| 356 |
|
| 357 |
pub fn slice<T>(&self, all: Vec<T>) -> Vec<T> { |
| 358 |
all.into_iter().skip((self.page - 1) * Self::PER_PAGE).take(Self::PER_PAGE).collect() |
| 359 |
} |
| 360 |
|
| 361 |
pub fn url(&self, page: usize) -> String { |
| 362 |
if self.query.is_empty() { |
| 363 |
format!("?page={page}") |
| 364 |
} else { |
| 365 |
format!("?{}&page={page}", self.query) |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
|
| 370 |
pub fn sorted(&self, sort: &str) -> String { |
| 371 |
let rest: Vec<&str> = self.query.split('&').filter(|p| !p.is_empty() && !p.starts_with("sort=")).collect(); |
| 372 |
let mut q = rest.join("&"); |
| 373 |
if !q.is_empty() { |
| 374 |
q.push('&'); |
| 375 |
} |
| 376 |
format!("?{q}sort={sort}") |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
pub struct Page<T: Template>(pub T); |
| 381 |
|
| 382 |
impl<T: Template> IntoResponse for Page<T> { |
| 383 |
fn into_response(self) -> Response { |
| 384 |
match self.0.render() { |
| 385 |
Ok(s) => Html(s).into_response(), |
| 386 |
Err(e) => { |
| 387 |
tracing::error!("template: {e}"); |
| 388 |
(StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response() |
| 389 |
} |
| 390 |
} |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
#[derive(Template)] |
| 395 |
#[template(path = "error.html")] |
| 396 |
struct ErrorPage { |
| 397 |
shell: Shell, |
| 398 |
status: u16, |
| 399 |
title: String, |
| 400 |
detail: String, |
| 401 |
} |
| 402 |
|
| 403 |
|
| 404 |
#[derive(Debug)] |
| 405 |
pub struct Error { |
| 406 |
pub status: StatusCode, |
| 407 |
pub detail: String, |
| 408 |
shell: Option<Box<Shell>>, |
| 409 |
redirect: Option<String>, |
| 410 |
} |
| 411 |
|
| 412 |
impl Error { |
| 413 |
pub fn redirect(to: String) -> Error { |
| 414 |
Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) } |
| 415 |
} |
| 416 |
|
| 417 |
pub fn not_found(shell: Shell) -> Error { |
| 418 |
Error { |
| 419 |
status: StatusCode::NOT_FOUND, |
| 420 |
detail: "There is nothing at this address.".into(), |
| 421 |
shell: Some(Box::new(shell)), |
| 422 |
redirect: None, |
| 423 |
} |
| 424 |
} |
| 425 |
|
| 426 |
pub fn bad(shell: Shell, detail: impl Into<String>) -> Error { |
| 427 |
Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None } |
| 428 |
} |
| 429 |
|
| 430 |
pub fn from_repo(shell: Shell, e: RepoError) -> Error { |
| 431 |
match e { |
| 432 |
RepoError::NotFound => Error::not_found(shell), |
| 433 |
RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => { |
| 434 |
Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None } |
| 435 |
} |
| 436 |
other => { |
| 437 |
Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None } |
| 438 |
} |
| 439 |
} |
| 440 |
} |
| 441 |
|
| 442 |
pub fn from_db(shell: Shell, e: sqlx::Error) -> Error { |
| 443 |
Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None } |
| 444 |
} |
| 445 |
} |
| 446 |
|
| 447 |
impl IntoResponse for Error { |
| 448 |
fn into_response(self) -> Response { |
| 449 |
if let Some(to) = self.redirect { |
| 450 |
return Redirect::to(&to).into_response(); |
| 451 |
} |
| 452 |
let title = match self.status { |
| 453 |
StatusCode::NOT_FOUND => "Not found", |
| 454 |
StatusCode::BAD_REQUEST => "Bad request", |
| 455 |
_ => "Something went wrong", |
| 456 |
}; |
| 457 |
if self.status.is_server_error() { |
| 458 |
tracing::error!("{}", self.detail); |
| 459 |
} |
| 460 |
let shell = self.shell.map(|b| *b).unwrap_or(Shell { |
| 461 |
site: "Oxygenhub".into(), |
| 462 |
base_url: String::new(), |
| 463 |
path: String::new(), |
| 464 |
version: "", |
| 465 |
user: None, |
| 466 |
is_admin: false, |
| 467 |
csrf: String::new(), |
| 468 |
unread: 0, |
| 469 |
}); |
| 470 |
let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail }; |
| 471 |
match page.render() { |
| 472 |
Ok(s) => (self.status, Html(s)).into_response(), |
| 473 |
Err(_) => (self.status, title).into_response(), |
| 474 |
} |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response { |
| 479 |
Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response() |
| 480 |
} |
| 481 |
|
| 482 |
|
| 483 |
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response { |
| 484 |
let mime = mime_of(name); |
| 485 |
let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" }; |
| 486 |
( |
| 487 |
[ |
| 488 |
(header::CONTENT_TYPE, mime.to_string()), |
| 489 |
(header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))), |
| 490 |
(header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()), |
| 491 |
], |
| 492 |
bytes, |
| 493 |
) |
| 494 |
.into_response() |
| 495 |
} |
| 496 |
|
| 497 |
pub fn mime_of(name: &str) -> &'static str { |
| 498 |
match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() { |
| 499 |
Some("png") => "image/png", |
| 500 |
Some("jpg" | "jpeg") => "image/jpeg", |
| 501 |
Some("gif") => "image/gif", |
| 502 |
Some("webp") => "image/webp", |
| 503 |
Some("svg") => "image/svg+xml", |
| 504 |
Some("pdf") => "application/pdf", |
| 505 |
Some( |
| 506 |
"txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh", |
| 507 |
) => "text/plain; charset=utf-8", |
| 508 |
_ => "application/octet-stream", |
| 509 |
} |
| 510 |
} |
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
pub async fn lookup_role( |
| 516 |
app: &Shared, |
| 517 |
shell: &Shell, |
| 518 |
viewer: &Viewer, |
| 519 |
owner: &str, |
| 520 |
name: &str, |
| 521 |
access: Access, |
| 522 |
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> { |
| 523 |
let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?; |
| 524 |
let row = db::repos::get(&app.db, owner, name) |
| 525 |
.await |
| 526 |
.map_err(|e| Error::from_db(shell.clone(), e))? |
| 527 |
.ok_or_else(|| Error::not_found(shell.clone()))?; |
| 528 |
let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 529 |
if !auth::roles::allows(role, access) { |
| 530 |
return Err(Error::not_found(shell.clone())); |
| 531 |
} |
| 532 |
Ok((repo, row, role.unwrap_or(Role::Read))) |
| 533 |
} |
| 534 |
|
| 535 |
|
| 536 |
pub async fn lookup( |
| 537 |
app: &Shared, |
| 538 |
shell: &Shell, |
| 539 |
viewer: &Viewer, |
| 540 |
owner: &str, |
| 541 |
name: &str, |
| 542 |
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> { |
| 543 |
lookup_role(app, shell, viewer, owner, name, Access::Read).await |
| 544 |
} |
| 545 |
|
| 546 |
|
| 547 |
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) { |
| 548 |
if changes.is_empty() { |
| 549 |
return; |
| 550 |
} |
| 551 |
let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return }; |
| 552 |
let map: std::collections::HashMap<String, String> = links.into_iter().collect(); |
| 553 |
for c in changes.iter_mut() { |
| 554 |
if let Some(u) = map.get(&c.author.key) { |
| 555 |
c.author.account = Some(u.clone()); |
| 556 |
} |
| 557 |
} |
| 558 |
} |