Sam Jeston
History
60 lines·
1.4 KB
·Rust
| 1 | use std::ops::Deref; |
| 2 | use std::sync::Arc; |
| 3 | |
| 4 | use crate::config::Config; |
| 5 | use crate::db::{self, Db, Repo, User}; |
| 6 | |
| 7 | pub struct Inner { |
| 8 | pub config: Config, |
| 9 | pub db: Db, |
| 10 | } |
| 11 | |
| 12 | /// Shared application state for the web and SSH servers. |
| 13 | #[derive(Clone)] |
| 14 | pub struct AppState(Arc<Inner>); |
| 15 | |
| 16 | impl AppState { |
| 17 | pub fn new(config: Config, db: Db) -> Self { |
| 18 | AppState(Arc::new(Inner { config, db })) |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | impl Deref for AppState { |
| 23 | type Target = Inner; |
| 24 | fn deref(&self) -> &Inner { |
| 25 | &self.0 |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | /// What a user may do with a repository. |
| 30 | #[derive(Debug, Clone, Copy, Default)] |
| 31 | pub struct Access { |
| 32 | pub read: bool, |
| 33 | pub write: bool, |
| 34 | pub admin: bool, |
| 35 | } |
| 36 | |
| 37 | impl AppState { |
| 38 | pub async fn access(&self, repo: &Repo, user: Option<&User>) -> Result<Access, sqlx::Error> { |
| 39 | let Some(user) = user else { |
| 40 | return Ok(Access { |
| 41 | read: !repo.is_private, |
| 42 | write: false, |
| 43 | admin: false, |
| 44 | }); |
| 45 | }; |
| 46 | if user.is_admin || user.id == repo.owner_id { |
| 47 | return Ok(Access { |
| 48 | read: true, |
| 49 | write: true, |
| 50 | admin: true, |
| 51 | }); |
| 52 | } |
| 53 | let collaborator = db::is_collaborator(&self.db, repo.id, user.id).await?; |
| 54 | Ok(Access { |
| 55 | read: collaborator || !repo.is_private, |
| 56 | write: collaborator, |
| 57 | admin: false, |
| 58 | }) |
| 59 | } |
| 60 | } |