Compare commits

...

14 Commits

Author SHA1 Message Date
Aravinth Manivannan 0c6199494b
feat: install gitea webhook security deps and load gitea webhook module
ci/woodpecker/push/woodpecker Pipeline was successful Details
2022-12-28 04:39:13 +05:30
Aravinth Manivannan 745b1eb0d5
feat: define gitea webhook routes 2022-12-28 04:38:57 +05:30
Aravinth Manivannan 8b19a8cac5
chore: reuse app context's http client in conductor obj 2022-12-28 04:38:24 +05:30
Aravinth Manivannan 3d11bfdcfc
feat: add gitea webhook template list REST API view 2022-12-28 04:37:42 +05:30
Aravinth Manivannan 0e5db5c7a9
feat: add gitea webhook template inspect web view 2022-12-28 04:37:09 +05:30
Aravinth Manivannan b6d53c9937
feat: add gitea webhook template list web view 2022-12-28 04:36:54 +05:30
Aravinth Manivannan e97712312f
fix: web: favicon alt-text crowding 2022-12-28 04:36:39 +05:30
Aravinth Manivannan 70e4650876
feat: add gitea webhook template and web view 2022-12-28 04:35:57 +05:30
Aravinth Manivannan e423ccc0ee
feat: REST API: list all webhooks created by user 2022-12-28 03:42:44 +05:30
Aravinth Manivannan 5d4977f421
feat: db: list all webhooks created by user 2022-12-28 03:42:00 +05:30
Aravinth Manivannan 201032fd07
feat: REST API: add and view webhooks 2022-12-28 03:22:23 +05:30
Aravinth Manivannan bce25be282
feat: db: get webhook with owner's username 2022-12-28 03:21:42 +05:30
Aravinth Manivannan 51e3924d71
feat: db: get site details from repository URL 2022-12-27 20:15:15 +05:30
Aravinth Manivannan f26075b881
feat: register new gitea webhooks 2022-12-20 07:11:21 +05:30
24 changed files with 1470 additions and 10 deletions

3
Cargo.lock generated
View File

@ -1449,6 +1449,8 @@ dependencies = [
"derive_more",
"futures",
"git2",
"hex",
"hmac",
"lazy_static",
"libconductor",
"libconfig",
@ -1464,6 +1466,7 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml",
"sha2",
"sqlx",
"tera",
"tokio",

View File

@ -53,6 +53,9 @@ toml = "0.5.9"
serde_yaml = "0.9.14"
uuid = { version = "1.2.2", features = ["serde"] }
reqwest = { version = "0.11.13", features = ["json"] }
sha2 = "0.10.6"
hmac = "0.12.1"
hex= "0.4.3"
[dependencies.cache-buster]
git = "https://github.com/realaravinth/cache-buster"

View File

@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS librepages_gitea_webhooks (
gitea_webhook_secret VARCHAR(40) NOT NULL UNIQUE,
gitea_url VARCHAR(3000) NOT NULL,
auth_token VARCHAR(40) NOT NULL UNIQUE,
ID SERIAL PRIMARY KEY NOT NULL,
owned_by INTEGER NOT NULL references librepages_users(ID) ON DELETE CASCADE
);
CREATE UNIQUE INDEX librepages_gitea_webhook_auth_token_index ON librepages_gitea_webhooks(auth_token);
CREATE TABLE IF NOT EXISTS librepages_gitea_webhook_site_mapping (
site_id INTEGER NOT NULL references librepages_sites(ID) ON DELETE CASCADE,
gitea_webhook_id INTEGER NOT NULL references librepages_gitea_webhooks(ID) ON DELETE CASCADE,
UNIQUE(site_id, gitea_webhook_id)
);

View File

@ -98,6 +98,38 @@
},
"query": "SELECT name, password FROM librepages_users WHERE name = ($1)"
},
"278dafae8343ee7b15b7014707a769e6d8f5042478c001d3dbe6cdad919f4546": {
"describe": {
"columns": [
{
"name": "gitea_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "auth_token",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "gitea_webhook_secret",
"ordinal": 2,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT\n gitea_url, auth_token, gitea_webhook_secret\n FROM\n librepages_gitea_webhooks\n WHERE\n owned_by = (SELECT ID FROM librepages_users WHERE name = $1);\n "
},
"279b5ae27935279b06d2799eef2da6a316324a05d23ba7a729c608c70168c496": {
"describe": {
"columns": [],
@ -189,6 +221,56 @@
},
"query": "SELECT repo_url, branch, hostname, owned_by, site_secret\n FROM librepages_sites\n WHERE pub_id = $1\n AND\n owned_by = (SELECT ID from librepages_users WHERE name = $2)\n AND\n deleted = false;\n "
},
"4445ff3226af3b5a24b255c5bb012c99b222cc7bd6dda80f232809ed273fc712": {
"describe": {
"columns": [
{
"name": "repo_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "site_secret",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "branch",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "hostname",
"ordinal": 3,
"type_info": "Varchar"
},
{
"name": "owned_by",
"ordinal": 4,
"type_info": "Int4"
},
{
"name": "pub_id",
"ordinal": 5,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
false,
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT repo_url, site_secret, branch, hostname, owned_by, pub_id\n FROM librepages_sites\n WHERE repo_url = $1\n AND deleted = false;\n "
},
"53f3c21c06c8d1c218537dfa9183fd0604aaf28200d8aa12e97db4ac317df39e": {
"describe": {
"columns": [
@ -370,6 +452,71 @@
},
"query": "SELECT\n time,\n pub_id\n FROM\n librepages_site_deploy_events\n WHERE\n site = (SELECT ID FROM librepages_sites WHERE hostname = $1)\n AND\n event_type = (SELECT ID FROM librepages_deploy_event_type WHERE name = $2)\n AND\n time = (\n SELECT MAX(time) \n FROM\n librepages_site_deploy_events\n WHERE\n site = (SELECT ID FROM librepages_sites WHERE hostname = $1)\n )\n "
},
"78d6aacc46441d72e42bc8d74f36f98056b442dd0e624757b1f25db29610cb08": {
"describe": {
"columns": [
{
"name": "gitea_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "auth_token",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "gitea_webhook_secret",
"ordinal": 2,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
false
],
"parameters": {
"Left": [
"Text",
"Text"
]
}
},
"query": "SELECT\n gitea_url, auth_token, gitea_webhook_secret\n FROM\n librepages_gitea_webhooks\n WHERE\n auth_token = $1\n AND\n owned_by = (SELECT ID FROM librepages_users WHERE name = $2);\n "
},
"7d2b7a4a57b9b031d15db57116807355e9e03b7bf9b0cff0958bfebe4bc1d1be": {
"describe": {
"columns": [
{
"name": "gitea_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "auth_token",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "gitea_webhook_secret",
"ordinal": 2,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT gitea_url, auth_token, gitea_webhook_secret\n FROM librepages_gitea_webhooks\n WHERE auth_token = $1\n "
},
"8735b654bc261571e6a5908d55a8217474c76bdff7f3cbcc71500a0fe13249db": {
"describe": {
"columns": [
@ -390,6 +537,26 @@
},
"query": "SELECT EXISTS (SELECT 1 from librepages_users WHERE email = $1)"
},
"90907d6cb4ca3b485f7b583584fb5821a950362679d061e490545c76634c211e": {
"describe": {
"columns": [
{
"name": "exists",
"ordinal": 0,
"type_info": "Bool"
}
],
"nullable": [
null
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT EXISTS (SELECT 1 from librepages_sites WHERE repo_url = $1)"
},
"924e756de5544cece865a10a7e136ecc6126e3a603947264cc7899387c18c819": {
"describe": {
"columns": [],
@ -466,6 +633,21 @@
},
"query": "SELECT EXISTS (SELECT 1 from librepages_users WHERE name = $1)"
},
"cd2347774ea740deae59e031a398adfc0b5c2942e556faa676fbd161297a81a6": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Text"
]
}
},
"query": "INSERT INTO librepages_gitea_webhooks\n (gitea_url , auth_token, gitea_webhook_secret, owned_by) VALUES ($1, $2, $3, \n (SELECT ID FROM librepages_users WHERE name = $4)\n )"
},
"ced69a08729ffb906e8971dbdce6a8d4197bc9bb8ccd7c58b3a88eb7be73fc2e": {
"describe": {
"columns": [
@ -563,5 +745,18 @@
}
},
"query": "INSERT INTO librepages_users\n (name , password, email) VALUES ($1, $2, $3)"
},
"fdcad0cd77ae37ed74cc7c92f20f9d95d851af5f9c9e6e4c34c39abf4a1d0f14": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Text",
"Text"
]
}
},
"query": "INSERT INTO librepages_gitea_webhook_site_mapping\n (site_id, gitea_webhook_id) VALUES (\n (SELECT ID FROM librepages_sites WHERE repo_url = $1),\n (SELECT ID FROM librepages_gitea_webhooks WHERE auth_token = $2)\n ) ON CONFLICT (site_id, gitea_webhook_id) DO NOTHING;"
}
}

190
src/api/v1/gitea.rs Normal file
View File

@ -0,0 +1,190 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use actix_identity::Identity;
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use tracing::info;
use url::Url;
use super::get_auth_middleware;
use crate::{errors::*, AppCtx};
pub mod routes {
use crate::ctx::Ctx;
pub struct Gitea {
pub add_webhook: &'static str,
pub view_webhook: &'static str,
pub list_webhooks: &'static str,
pub webhook: &'static str,
}
impl Gitea {
pub const fn new() -> Self {
Self {
add_webhook: "/api/v1/gitea/webhook/add",
list_webhooks: "/api/v1/gitea/webhook/add",
view_webhook: "/api/v1/gitea/webhook/view/{auth_token}",
webhook: "/api/v1/gitea/webhook/event/new",
}
}
pub fn get_view(&self, auth_token: &str) -> String {
self.view_webhook.replace("{auth_token}", auth_token)
}
pub fn get_webhook_url(&self, ctx: &Ctx, auth_token: &str) -> String {
format!(
"https://{}{}?auth={auth_token}",
&ctx.settings.server.domain, self.webhook
)
}
}
}
#[derive(Serialize, Deserialize)]
pub struct AddWebhook {
pub gitea_url: Url,
}
#[actix_web_codegen_const_routes::post(
path = "crate::V1_API_ROUTES.gitea.add_webhook",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Add webhook" skip(id, ctx, payload))]
async fn add_webhook(
ctx: AppCtx,
id: Identity,
payload: web::Json<AddWebhook>,
) -> ServiceResult<impl Responder> {
info!(
"Adding webhook for Gitea instance: {}",
payload.gitea_url.as_str()
);
let owner = id.identity().unwrap();
let payload = payload.into_inner();
let hook = ctx.db.new_webhook(payload.gitea_url, &owner).await?;
Ok(HttpResponse::Ok().json(hook))
}
#[actix_web_codegen_const_routes::get(
path = "crate::V1_API_ROUTES.gitea.list_webhooks",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Delete webhook" skip(id, ctx))]
async fn list_webhooks(ctx: AppCtx, id: Identity) -> ServiceResult<impl Responder> {
let owner = id.identity().unwrap();
info!("Getting all webhooks created by {}", owner);
let hooks = ctx.db.list_all_webhooks_with_owner(&owner).await?;
Ok(HttpResponse::Ok().json(hooks))
}
#[actix_web_codegen_const_routes::get(
path = "crate::V1_API_ROUTES.gitea.view_webhook",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Delete webhook" skip(id, ctx, path))]
async fn view_webhook(
ctx: AppCtx,
id: Identity,
path: web::Path<String>,
) -> ServiceResult<impl Responder> {
let path = path.into_inner();
let owner = id.identity().unwrap();
info!("Gitting webhook webhook for Gitea instance: {}", path,);
let hook = ctx.db.get_webhook_with_owner(&path, &owner).await?;
Ok(HttpResponse::Ok().json(hook))
}
#[derive(Serialize, Deserialize)]
struct Auth {
auth: String,
}
#[actix_web_codegen_const_routes::post(path = "crate::V1_API_ROUTES.gitea.webhook")]
#[tracing::instrument(name = "Update ", skip(body, ctx, req, q))]
async fn webhook(
ctx: AppCtx,
body: web::Bytes,
req: HttpRequest,
q: web::Query<Auth>,
) -> ServiceResult<impl Responder> {
ctx.process_webhook(&body, &req, &q.auth).await?;
Ok(HttpResponse::Ok())
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(add_webhook);
cfg.service(view_webhook);
cfg.service(list_webhooks);
cfg.service(webhook);
}
#[cfg(test)]
mod tests {
use actix_web::{http::StatusCode, test};
use crate::db::GiteaWebhook;
use crate::tests;
use crate::*;
use super::*;
#[actix_rt::test]
async fn test_api_gitea_webhook() {
const NAME: &str = "apigiteawebhookuser";
const PASSWORD: &str = "longpasswordasdfa2";
const EMAIL: &str = "apigiteawebhookuser@a.com";
let (_dir, ctx) = tests::get_ctx().await;
let _ = ctx.delete_user(NAME, PASSWORD).await;
let (_, signin_resp) = ctx.register_and_signin(NAME, EMAIL, PASSWORD).await;
let cookies = get_cookie!(signin_resp);
let app = get_app!(ctx).await;
let payload = AddWebhook {
gitea_url: Url::parse("https://git.batnsense.net").unwrap(),
};
let add_webhook_resp = test::call_service(
&app,
post_request!(&payload, V1_API_ROUTES.gitea.add_webhook)
.cookie(cookies.clone())
.to_request(),
)
.await;
check_status!(add_webhook_resp, StatusCode::OK);
let response: GiteaWebhook = actix_web::test::read_body_json(add_webhook_resp).await;
assert_eq!(response.gitea_url, payload.gitea_url);
let view_webhook_resp = get_request!(
&app,
&V1_API_ROUTES.gitea.get_view(&response.auth_token),
cookies.clone()
);
check_status!(view_webhook_resp, StatusCode::OK);
let hook: GiteaWebhook = actix_web::test::read_body_json(view_webhook_resp).await;
assert_eq!(hook, response);
let list_all_webhooks_resp =
get_request!(&app, &V1_API_ROUTES.gitea.list_webhooks, cookies.clone());
check_status!(list_all_webhooks_resp, StatusCode::OK);
let hooks: Vec<GiteaWebhook> =
actix_web::test::read_body_json(list_all_webhooks_resp).await;
assert_eq!(vec![hook], hooks);
}
}

View File

@ -20,6 +20,7 @@ use serde::Deserialize;
pub mod account;
pub mod auth;
pub mod gitea;
pub mod meta;
pub mod pages;
pub mod routes;
@ -30,6 +31,7 @@ pub fn services(cfg: &mut ServiceConfig) {
auth::services(cfg);
account::services(cfg);
meta::services(cfg);
gitea::services(cfg);
pages::services(cfg);
}

View File

@ -19,6 +19,7 @@ use actix_auth_middleware::GetLoginRoute;
use crate::serve::routes::Serve;
use super::gitea::routes::Gitea;
use super::meta::routes::Meta;
use super::pages::routes::Deploy;
@ -92,6 +93,7 @@ pub struct Routes {
pub account: Account,
/// Meta routes
pub meta: Meta,
pub gitea: Gitea,
pub deploy: Deploy,
pub serve: Serve,
}
@ -103,6 +105,7 @@ impl Routes {
auth: Auth::new(),
account: Account::new(),
meta: Meta::new(),
gitea: Gitea::new(),
deploy: Deploy::new(),
serve: Serve::new(),
}

View File

@ -30,11 +30,13 @@ pub struct Conductor {
}
impl Conductor {
pub fn new(settings: Settings) -> Self {
Self {
client: Client::new(),
settings,
}
pub fn new(settings: Settings, client: Option<Client>) -> Self {
let client = if let Some(client) = client {
client
} else {
Client::new()
};
Self { client, settings }
}
async fn tx(&self, e: &EventType) -> ServiceResult<()> {
for c in self.settings.conductors.iter() {
@ -79,7 +81,7 @@ mod tests {
#[actix_rt::test]
pub async fn test_conductor() {
let settings = Settings::new().unwrap();
let c = Conductor::new(settings.clone());
let c = Conductor::new(settings.clone(), None);
c.delete_site("example.org".into()).await.unwrap();
let page = Page {
secret: "foo".into(),

200
src/ctx/api/v1/gitea.rs Normal file
View File

@ -0,0 +1,200 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use actix_web::web;
use actix_web::HttpRequest;
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use tracing::{info, warn};
use crate::ctx::Ctx;
use crate::errors::ServiceResult;
type HmacSha256 = Hmac<Sha256>;
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct CommitPerson {
name: String,
email: String,
username: String,
}
#[derive(Serialize, Deserialize, Default, Debug, Clone, Eq, PartialEq)]
pub struct Commit {
id: String,
message: String,
url: String,
author: CommitPerson,
committer: CommitPerson,
verification: serde_json::Value,
timestamp: String,
added: serde_json::Value,
removed: serde_json::Value,
modified: serde_json::Value,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct Person {
id: usize,
login: String,
full_name: String,
email: String,
avatar_url: String,
language: String,
is_admin: bool,
last_login: String,
created: String,
restricted: bool,
active: bool,
prohibit_login: bool,
location: String,
website: String,
description: String,
visibility: String,
followers_count: usize,
following_count: usize,
starred_repos_count: usize,
username: String,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct Permissions {
admin: bool,
push: bool,
pull: bool,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct InternalTracker {
enable_time_tracker: bool,
allow_only_contributors_to_track_time: bool,
enable_issue_dependencies: bool,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct Repository {
id: usize,
owner: Person,
name: String,
full_name: String,
description: String,
empty: bool,
private: bool,
fork: bool,
template: bool,
parent: Option<serde_json::Value>,
mirror: bool,
size: usize,
html_url: String,
ssh_url: String,
clone_url: String,
original_url: String,
website: String,
stars_count: usize,
forks_count: usize,
watchers_count: usize,
open_issues_count: usize,
open_pr_counter: usize,
release_counter: usize,
default_branch: String,
archived: bool,
created_at: String,
updated_at: String,
permissions: Permissions,
has_issues: bool,
internal_tracker: InternalTracker,
has_wiki: bool,
has_pull_requests: bool,
has_projects: bool,
ignore_whitespace_conflicts: bool,
allow_merge_commits: bool,
allow_rebase: bool,
allow_rebase_explicit: bool,
allow_squash_merge: bool,
default_merge_style: String,
avatar_url: String,
internal: bool,
mirror_interval: String,
mirror_updated: String,
repo_transfer: Option<serde_json::Value>,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct WebhookPayload {
#[serde(rename(serialize = "ref", deserialize = "ref"))]
reference: String,
before: String,
after: String,
compare_url: String,
repository: Repository,
pusher: Person,
sender: Person,
}
impl Ctx {
pub async fn process_webhook(
&self,
body: &web::Bytes,
req: &HttpRequest,
auth_token: &str,
) -> ServiceResult<()> {
let headers = req.headers();
let _uuid = headers.get("X-Gitea-Delivery").unwrap();
let sig = headers.get("X-Gitea-Signature").unwrap();
let sig = hex::decode(sig).unwrap();
let event_type = headers.get("X-Gitea-Event").unwrap();
let payload: WebhookPayload = serde_json::from_slice(&body).unwrap();
let hook = self.db.get_webhook(auth_token).await?;
for url in [
&payload.repository.html_url,
&payload.repository.ssh_url,
&payload.repository.clone_url,
] {
if self.db.site_with_repository_exists(url).await? {
let mut mac = HmacSha256::new_from_slice(hook.gitea_webhook_secret.as_bytes())
.expect("HMAC can take key of any size");
mac.update(&body);
mac.verify_slice(&sig[..]).unwrap();
let site = self.db.get_site_from_repo_url(url).await?;
if payload.reference.contains(&site.branch) {
info!(
"[webhook][forgejo/gitea] received update {:?} from {url} repository on deployed branch",
event_type
);
self.update_site(&site.site_secret, Some(site.branch))
.await?;
} else {
info!(
"[webhook][forgejo/gitea] received update {:?} from {url} repository on non-deployed branch {}",
event_type,
payload.reference
);
}
return Ok(());
}
}
warn!(
"[webhook][forgejo/gitea] stray update from {} repository",
payload.repository.html_url
);
Ok(())
}
}

View File

@ -16,6 +16,7 @@
*/
pub mod account;
pub mod auth;
pub mod gitea;
pub mod pages;
#[cfg(test)]

View File

@ -20,6 +20,7 @@ use std::thread;
use crate::db::*;
use crate::settings::Settings;
use argon2_creds::{Config as ArgonConfig, ConfigBuilder as ArgonConfigBuilder, PasswordPolicy};
use reqwest::Client;
use tracing::info;
pub mod api;
@ -35,6 +36,7 @@ pub struct Ctx {
pub conductor: Conductor,
/// credential-procession policy
pub creds: ArgonConfig,
client: Client,
}
impl Ctx {
@ -52,7 +54,8 @@ impl Ctx {
pub async fn new(settings: Settings) -> Arc<Self> {
let creds = Self::get_creds();
let c = creds.clone();
let conductor = Conductor::new(settings.clone());
let client = Client::default();
let conductor = Conductor::new(settings.clone(), Some(client.clone()));
#[allow(unused_variables)]
let init = thread::spawn(move || {
@ -67,6 +70,7 @@ impl Ctx {
Arc::new(Self {
settings,
client,
db,
creds,
conductor,

249
src/db.rs
View File

@ -23,9 +23,11 @@ use sqlx::types::time::OffsetDateTime;
use sqlx::ConnectOptions;
use sqlx::PgPool;
use tracing::error;
use url::Url;
use uuid::Uuid;
use crate::errors::*;
use crate::utils;
/// Connect to databse
pub enum ConnectionOptions {
@ -274,6 +276,53 @@ impl Database {
Ok(())
}
pub async fn get_site_from_repo_url(&self, repo_url: &str) -> ServiceResult<Site> {
struct S {
repo_url: String,
branch: String,
hostname: String,
owned_by: i32,
site_secret: String,
pub_id: Uuid,
}
let site = sqlx::query_as!(
S,
"SELECT repo_url, site_secret, branch, hostname, owned_by, pub_id
FROM librepages_sites
WHERE repo_url = $1
AND deleted = false;
",
repo_url,
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebsiteNotFound))?;
struct Owner {
name: String,
}
let owner = sqlx::query_as!(
Owner,
"SELECT name FROM librepages_users WHERE ID = $1",
site.owned_by
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebsiteNotFound))?;
let site = Site {
site_secret: site.site_secret,
branch: site.branch,
hostname: site.hostname,
owner: owner.name,
repo_url: site.repo_url,
pub_id: site.pub_id,
};
Ok(site)
}
pub async fn get_site_from_pub_id(&self, pub_id: Uuid, owner: String) -> ServiceResult<Site> {
struct S {
repo_url: String,
@ -431,6 +480,24 @@ impl Database {
Ok(resp)
}
/// check if site with repository exists
pub async fn site_with_repository_exists(&self, url: &str) -> ServiceResult<bool> {
let res = sqlx::query!(
"SELECT EXISTS (SELECT 1 from librepages_sites WHERE repo_url = $1)",
url,
)
.fetch_one(&self.pool)
.await
.map_err(map_register_err)?;
let mut resp = false;
if let Some(x) = res.exists {
resp = x;
}
Ok(resp)
}
/// check if event type exists
async fn event_type_exists(&self, event: &Event) -> ServiceResult<bool> {
let res = sqlx::query!(
@ -622,7 +689,114 @@ impl Database {
}
Ok(events)
}
/// register a new webhook
pub async fn new_webhook(&self, gitea_url: Url, owner: &str) -> ServiceResult<GiteaWebhook> {
let hook = GiteaWebhook::new(gitea_url);
sqlx::query!(
"INSERT INTO librepages_gitea_webhooks
(gitea_url , auth_token, gitea_webhook_secret, owned_by) VALUES ($1, $2, $3,
(SELECT ID FROM librepages_users WHERE name = $4)
)",
hook.gitea_url.as_str(),
&hook.auth_token,
&hook.gitea_webhook_secret,
owner,
)
.execute(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::AccountNotFound))?;
Ok(hook)
}
pub async fn list_all_webhooks_with_owner(
&self,
owner: &str,
) -> ServiceResult<Vec<GiteaWebhook>> {
let mut db_hooks = sqlx::query_as!(
InnerGiteaWebhook,
"SELECT
gitea_url, auth_token, gitea_webhook_secret
FROM
librepages_gitea_webhooks
WHERE
owned_by = (SELECT ID FROM librepages_users WHERE name = $1);
",
owner
)
.fetch_all(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebhookNotFound))?;
let mut hooks = Vec::with_capacity(db_hooks.len());
for hook in db_hooks.drain(0..) {
hooks.push(hook.to_webhook()?)
}
Ok(hooks)
}
pub async fn get_webhook_with_owner(
&self,
auth_token: &str,
owner: &str,
) -> ServiceResult<GiteaWebhook> {
let h = sqlx::query_as!(
InnerGiteaWebhook,
"SELECT
gitea_url, auth_token, gitea_webhook_secret
FROM
librepages_gitea_webhooks
WHERE
auth_token = $1
AND
owned_by = (SELECT ID FROM librepages_users WHERE name = $2);
",
auth_token,
owner
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebhookNotFound))?;
h.to_webhook()
}
pub async fn get_webhook(&self, auth_token: &str) -> ServiceResult<GiteaWebhook> {
let h = sqlx::query_as!(
InnerGiteaWebhook,
"SELECT gitea_url, auth_token, gitea_webhook_secret
FROM librepages_gitea_webhooks
WHERE auth_token = $1
",
auth_token,
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebhookNotFound))?;
h.to_webhook()
}
/// register a webhook against a site
pub async fn webhook_link_site(&self, auth_token: &str, repo_url: &Url) -> ServiceResult<()> {
sqlx::query!(
"INSERT INTO librepages_gitea_webhook_site_mapping
(site_id, gitea_webhook_id) VALUES (
(SELECT ID FROM librepages_sites WHERE repo_url = $1),
(SELECT ID FROM librepages_gitea_webhooks WHERE auth_token = $2)
) ON CONFLICT (site_id, gitea_webhook_id) DO NOTHING;",
repo_url.as_str(),
auth_token
)
.execute(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebhookNotFound))?;
Ok(())
}
}
struct InnerSite {
site_secret: String,
repo_url: String,
@ -732,6 +906,39 @@ pub struct LibrePagesEvent {
pub id: Uuid,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct GiteaWebhook {
pub gitea_url: Url,
pub gitea_webhook_secret: String,
pub auth_token: String,
}
impl GiteaWebhook {
fn new(gitea_url: Url) -> Self {
Self {
gitea_url,
gitea_webhook_secret: utils::get_random(40),
auth_token: utils::get_random(40),
}
}
}
struct InnerGiteaWebhook {
gitea_url: String,
auth_token: String,
gitea_webhook_secret: String,
}
impl InnerGiteaWebhook {
fn to_webhook(self) -> ServiceResult<GiteaWebhook> {
Ok(GiteaWebhook {
gitea_url: Url::parse(&self.gitea_url)?,
auth_token: self.auth_token,
gitea_webhook_secret: self.gitea_webhook_secret,
})
}
}
fn now_unix_time_stamp() -> OffsetDateTime {
OffsetDateTime::now_utc()
}
@ -951,7 +1158,7 @@ mod tests {
let site = Site {
site_secret: "foobar".into(),
repo_url: "https://git.batsense.net/LibrePages/librepages.git".into(),
repo_url: "https://git.test_db_sites.example.org/LibrePages/librepages.git".into(),
branch: "librepages".into(),
hostname: "db_works.tests.librepages.librepages.org".into(),
pub_id: Uuid::new_v4(),
@ -960,12 +1167,20 @@ mod tests {
// test if hostname exists. Should be false
assert!(!db.hostname_exists(&site.hostname).await.unwrap());
assert!(!db
.site_with_repository_exists(&site.repo_url)
.await
.unwrap());
// testing adding site
db.add_site(&site).await.unwrap();
// test if hostname exists. Should be true
assert!(db.hostname_exists(&site.hostname).await.unwrap());
assert!(db
.site_with_repository_exists(&site.repo_url)
.await
.unwrap());
// get site
let db_site = db.get_site(p.username, &site.hostname).await.unwrap();
@ -977,6 +1192,12 @@ mod tests {
db.get_site_from_secret(&site.site_secret).await.unwrap()
);
// get site by repo_url
assert_eq!(
db_site,
db.get_site_from_repo_url(&site.repo_url).await.unwrap()
);
// list all sites owned by user
let db_sites = db.list_all_sites(p.username).await.unwrap();
assert_eq!(db_sites.len(), 1);
@ -1023,6 +1244,32 @@ mod tests {
);
assert_eq!(latest_update_event_id_from_db.id, latest_update_event_id);
// add webhook
let gitea_url = Url::parse("https://example.org").unwrap();
let hook = db.new_webhook(gitea_url, NAME).await.unwrap();
assert_eq!(hook, db.get_webhook(&hook.auth_token).await.unwrap());
assert_eq!(
vec![hook.clone()],
db.list_all_webhooks_with_owner(NAME).await.unwrap()
);
assert_eq!(
hook,
db.get_webhook_with_owner(&hook.auth_token, NAME)
.await
.unwrap()
);
assert_eq!(
db.get_webhook(&hook.gitea_webhook_secret).await.err(),
Some(ServiceError::WebhookNotFound)
);
db.webhook_link_site(&hook.auth_token, &Url::parse(&site.repo_url).unwrap())
.await
.unwrap();
db.webhook_link_site(&hook.auth_token, &Url::parse(&site.repo_url).unwrap())
.await
.unwrap();
// delete site
db.delete_site(p.username, &site.hostname).await.unwrap();

View File

@ -178,6 +178,10 @@ pub enum ServiceError {
#[display(fmt = "Passwords don't match")]
/// passwords don't match
PasswordsDontMatch,
/// Webhook not found
#[display(fmt = "Webhook not found")]
WebhookNotFound,
}
impl From<ParseError> for ServiceError {
@ -252,6 +256,7 @@ impl ResponseError for ServiceError {
ServiceError::ClosedForRegistration => StatusCode::FORBIDDEN, //FORBIDDEN,
ServiceError::NotAnEmail => StatusCode::BAD_REQUEST, //BADREQUEST,
ServiceError::WrongPassword => StatusCode::UNAUTHORIZED, //UNAUTHORIZED,
ServiceError::WebhookNotFound => StatusCode::NOT_FOUND, //NOT FOUND,
}
}
}

193
src/pages/dash/gitea/add.rs Normal file
View File

@ -0,0 +1,193 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use actix_identity::Identity;
use actix_web::http::header::ContentType;
use tera::Context;
use tracing::info;
use super::get_auth_middleware;
use crate::api::v1::gitea::AddWebhook;
use crate::pages::errors::*;
use crate::settings::Settings;
use crate::AppCtx;
pub use super::*;
pub const DASH_GITEA_WEBHOOK_ADD: TemplateFile =
TemplateFile::new("dash_gitea_webhook_add", "pages/dash/gitea/add.html");
pub struct Add {
ctx: RefCell<Context>,
}
impl CtxError for Add {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
impl Add {
pub fn new(settings: &Settings) -> Self {
let ctx = RefCell::new(context(settings));
Self { ctx }
}
pub fn render(&self) -> String {
TEMPLATES
.render(DASH_GITEA_WEBHOOK_ADD.name, &self.ctx.borrow())
.unwrap()
}
}
#[actix_web_codegen_const_routes::get(
path = "PAGES.dash.gitea_webhook.add",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Dashboard add gitea webhook webpage", skip(ctx))]
pub async fn get_add_gitea_webhook(ctx: AppCtx) -> PageResult<impl Responder, Add> {
let add = Add::new(&ctx.settings).render();
let html = ContentType::html();
Ok(HttpResponse::Ok().content_type(html).body(add))
}
#[actix_web_codegen_const_routes::post(
path = "PAGES.dash.gitea_webhook.add",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(
name = "Post Dashboard add Gitea webhook webpage",
skip(ctx, id, payload)
)]
pub async fn post_add_gitea_webhook(
ctx: AppCtx,
id: Identity,
payload: web::Form<AddWebhook>,
) -> PageResult<impl Responder, Add> {
let owner = id.identity().unwrap();
let payload = payload.into_inner();
info!(
"Adding webhook for Gitea instance: {}",
payload.gitea_url.as_str()
);
let hook = ctx
.db
.new_webhook(payload.gitea_url, &owner)
.await
.map_err(|e| PageError::new(Add::new(&ctx.settings), e))?;
Ok(HttpResponse::Found()
.append_header((
http::header::LOCATION,
PAGES.dash.gitea_webhook.get_view(&hook.auth_token),
))
.finish())
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(get_add_gitea_webhook);
cfg.service(post_add_gitea_webhook);
}
#[cfg(test)]
mod tests {
use actix_web::http::StatusCode;
use actix_web::test;
use url::Url;
use crate::api::v1::gitea::AddWebhook;
use crate::ctx::ArcCtx;
use crate::tests;
use crate::*;
use super::PAGES;
#[actix_rt::test]
async fn postgres_dashboadr_add_gitea_webhook_works() {
let (_, ctx) = tests::get_ctx().await;
dashboadr_add_gitea_webhook_works(ctx.clone()).await;
}
async fn dashboadr_add_gitea_webhook_works(ctx: ArcCtx) {
const NAME: &str = "testdashwebhookgiteaadduser";
const EMAIL: &str = "testdashwebhookgiteaadduser@foo.com";
const PASSWORD: &str = "longpassword";
let _ = ctx.delete_user(NAME, PASSWORD).await;
let (_, signin_resp) = ctx.register_and_signin(NAME, EMAIL, PASSWORD).await;
let cookies = get_cookie!(signin_resp);
let app = get_app!(ctx.clone()).await;
let resp = get_request!(&app, PAGES.dash.gitea_webhook.add, cookies.clone());
assert_eq!(resp.status(), StatusCode::OK);
let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
assert!(res.contains("Add Gitea Webhook"));
let payload = AddWebhook {
gitea_url: Url::parse("https://git.batsense.net").unwrap(),
};
let add_webhook = test::call_service(
&app,
post_request!(&payload, PAGES.dash.gitea_webhook.add, FORM)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(add_webhook.status(), StatusCode::FOUND);
let mut hooks = ctx.db.list_all_webhooks_with_owner(NAME).await.unwrap();
let hook = hooks.pop().unwrap();
// let mut event = ctx.db.list(&site.hostname).await.unwrap();
// let event = event.pop().unwrap();
let headers = add_webhook.headers();
let view_webhook_url = PAGES.dash.gitea_webhook.get_view(&hook.auth_token);
assert_eq!(
headers.get(actix_web::http::header::LOCATION).unwrap(),
&view_webhook_url
);
// list webhooks
let resp = get_request!(&app, PAGES.dash.gitea_webhook.list, cookies.clone());
assert_eq!(resp.status(), StatusCode::OK);
let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
assert!(res.contains(&hook.gitea_url.as_str()));
// view webhook
let resp = get_request!(&app, &view_webhook_url, cookies.clone());
assert_eq!(resp.status(), StatusCode::OK);
let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
assert!(res.contains("****"));
assert!(res.contains(
&crate::V1_API_ROUTES
.gitea
.get_webhook_url(&ctx, &hook.auth_token)
));
let show_gitea_webhook_secret =
format!("{view_webhook_url}?show_gitea_webhook_secret=true");
let resp = get_request!(&app, &show_gitea_webhook_secret, cookies.clone());
assert_eq!(resp.status(), StatusCode::OK);
let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
assert!(res.contains(&hook.gitea_webhook_secret));
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use actix_identity::Identity;
use actix_web::http::header::ContentType;
use serde::{Deserialize, Serialize};
use tera::Context;
use super::get_auth_middleware;
use crate::errors::ServiceResult;
use crate::pages::errors::*;
use crate::settings::Settings;
use crate::AppCtx;
pub use super::*;
pub const DASH_GITEA_WEBHOOK_LIST: TemplateFile =
TemplateFile::new("dash_gitea_webhook_list", "pages/dash/gitea/list.html");
pub struct List {
ctx: RefCell<Context>,
}
impl CtxError for List {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
impl List {
pub fn new(settings: &Settings, hooks: Option<&[TemplateGiteaWebhook]>) -> Self {
let ctx = RefCell::new(context(settings));
if let Some(hooks) = hooks {
ctx.borrow_mut().insert(PAYLOAD_KEY, hooks);
}
Self { ctx }
}
pub fn render(&self) -> String {
TEMPLATES
.render(DASH_GITEA_WEBHOOK_LIST.name, &self.ctx.borrow())
.unwrap()
}
}
async fn get_webhook_data(ctx: &AppCtx, id: &Identity) -> ServiceResult<Vec<TemplateGiteaWebhook>> {
let db_hooks = ctx
.db
.list_all_webhooks_with_owner(&id.identity().unwrap())
.await?;
let mut hooks = Vec::with_capacity(db_hooks.len());
for hook in db_hooks {
hooks.push(TemplateGiteaWebhook::new(ctx, hook));
}
Ok(hooks)
}
#[actix_web_codegen_const_routes::get(
path = "PAGES.dash.gitea_webhook.list",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "List all Gitea webhooks", skip(ctx, id))]
pub async fn list_hooks(ctx: AppCtx, id: Identity) -> PageResult<impl Responder, List> {
let sites = get_webhook_data(&ctx, &id)
.await
.map_err(|e| PageError::new(List::new(&ctx.settings, None), e))?;
let home = List::new(&ctx.settings, Some(&sites)).render();
let html = ContentType::html();
Ok(HttpResponse::Ok().content_type(html).body(home))
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(list_hooks);
}

View File

@ -0,0 +1,69 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use actix_web::*;
use serde::{Deserialize, Serialize};
use super::get_auth_middleware;
pub use super::home::TemplateSite;
pub use super::{context, Footer, TemplateFile, PAGES, PAYLOAD_KEY, TEMPLATES};
use crate::ctx::Ctx;
use crate::db::GiteaWebhook;
pub mod add;
pub mod list;
pub mod view;
pub fn register_templates(t: &mut tera::Tera) {
add::DASH_GITEA_WEBHOOK_ADD
.register(t)
.expect(add::DASH_GITEA_WEBHOOK_ADD.name);
list::DASH_GITEA_WEBHOOK_LIST
.register(t)
.expect(list::DASH_GITEA_WEBHOOK_LIST.name);
view::DASH_GITEA_WEBHOOK_VIEW
.register(t)
.expect(view::DASH_GITEA_WEBHOOK_VIEW.name);
}
pub fn services(cfg: &mut web::ServiceConfig) {
add::services(cfg);
list::services(cfg);
view::services(cfg);
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct TemplateGiteaWebhook {
pub webhook: GiteaWebhook,
pub view: String,
pub url: String,
}
impl TemplateGiteaWebhook {
pub fn new(ctx: &Ctx, hook: GiteaWebhook) -> Self {
let view = PAGES.dash.gitea_webhook.get_view(&hook.auth_token);
let url = crate::V1_API_ROUTES
.gitea
.get_webhook_url(ctx, &hook.auth_token);
Self {
webhook: hook,
view,
url,
}
}
}

View File

@ -0,0 +1,111 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use actix_identity::Identity;
use actix_web::http::header::ContentType;
use serde::{Deserialize, Serialize};
use tera::Context;
use uuid::Uuid;
use super::get_auth_middleware;
use crate::db::Site;
use crate::pages::dash::TemplateSiteEvent;
use crate::pages::errors::*;
use crate::settings::Settings;
use crate::AppCtx;
pub use super::*;
pub const DASH_GITEA_WEBHOOK_VIEW: TemplateFile =
TemplateFile::new("dash_gitea_webhook_view", "pages/dash/gitea/view.html");
const SHOW_GITEA_WEBHOOK_SECRET_KEY: &str = "show_gitea_webhook_secret";
pub struct View {
ctx: RefCell<Context>,
}
impl CtxError for View {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
impl View {
pub fn new(settings: &Settings, payload: Option<TemplateGiteaWebhook>) -> Self {
let ctx = RefCell::new(context(settings));
if let Some(payload) = payload {
ctx.borrow_mut().insert(PAYLOAD_KEY, &payload);
}
Self { ctx }
}
pub fn show_gitea_webhook_secret(&mut self) {
self.ctx
.borrow_mut()
.insert(SHOW_GITEA_WEBHOOK_SECRET_KEY, &true);
}
pub fn render(&self) -> String {
TEMPLATES
.render(DASH_GITEA_WEBHOOK_VIEW.name, &self.ctx.borrow())
.unwrap()
}
}
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct ViewOptions {
show_gitea_webhook_secret: Option<bool>,
}
#[actix_web_codegen_const_routes::get(
path = "PAGES.dash.gitea_webhook.view",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Dashboard Gitea webhook webpage", skip(ctx, id))]
pub async fn get_view_site(
ctx: AppCtx,
id: Identity,
path: web::Path<String>,
query: web::Query<ViewOptions>,
) -> PageResult<impl Responder, View> {
let auth_token = path.into_inner();
let owner = id.identity().unwrap();
let hook = ctx
.db
.get_webhook_with_owner(&auth_token, &owner)
.await
.map_err(|e| PageError::new(View::new(&ctx.settings, None), e))?;
let payload = TemplateGiteaWebhook::new(&ctx, hook);
let mut page = View::new(&ctx.settings, Some(payload));
if let Some(true) = query.show_gitea_webhook_secret {
page.show_gitea_webhook_secret();
}
let add = page.render();
let html = ContentType::html();
Ok(HttpResponse::Ok().content_type(html).body(add))
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(get_view_site);
}

View File

@ -24,6 +24,7 @@ pub use super::{context, Footer, TemplateFile, PAGES, PAYLOAD_KEY, TEMPLATES};
use crate::db::Event;
use crate::db::LibrePagesEvent;
pub mod gitea;
pub mod home;
pub mod sites;
@ -49,9 +50,11 @@ impl From<LibrePagesEvent> for TemplateSiteEvent {
pub fn register_templates(t: &mut tera::Tera) {
home::DASH_HOME.register(t).expect(home::DASH_HOME.name);
sites::register_templates(t);
gitea::register_templates(t);
}
pub fn services(cfg: &mut web::ServiceConfig) {
home::services(cfg);
sites::services(cfg);
gitea::services(cfg);
}

View File

@ -72,6 +72,7 @@ pub struct Dash {
/// home route
pub home: &'static str,
pub site: DashSite,
pub gitea_webhook: GiteaWebhook,
}
impl Dash {
@ -79,7 +80,37 @@ impl Dash {
pub const fn new() -> Dash {
let home = "/dash";
let site = DashSite::new();
Dash { home, site }
let gitea_webhook = GiteaWebhook::new();
Dash {
home,
site,
gitea_webhook,
}
}
}
#[derive(Serialize)]
/// Dashboard GiteaWebhook routes
pub struct GiteaWebhook {
/// add gitea webhook route
pub add: &'static str,
/// view gitea webhook route
pub view: &'static str,
/// list gitea webhooks route
pub list: &'static str,
}
impl GiteaWebhook {
/// create new instance of GiteaWebhook route
pub const fn new() -> GiteaWebhook {
let add = "/dash/gitea/webhook/add";
let list = "/dash/gitea/webhook/list";
let view = "/dash/gitea/webhook/view/{auth_token}";
GiteaWebhook { add, view, list }
}
pub fn get_view(&self, auth_token: &str) -> String {
self.view.replace("{auth_token}", auth_token)
}
}

View File

@ -16,6 +16,11 @@
<div class="nav__link-container">
<a class="nav__link" rel="noreferrer" href="{{ page.dash.site.add }}">New Site</a>
</div>
<div class="nav__link-container">
<a class="nav__link" rel="noreferrer" href="{{ page.dash.gitea_webhook.list }}">Webhooks</a>
</div>
<div class="nav__link-container">
<a class="nav__link" rel="noreferrer" href="{{ page.auth.logout }}">Log out</a>
</div>

View File

@ -0,0 +1,23 @@
{% extends 'base' %}{% block title %} Add Gitea Webhook{% endblock title %} {% block nav
%} {% include "auth_nav" %} {% endblock nav %} {% block main %}
<main class="sites__main">
<div class="add-site__container">
<form class="auth-form" action="{{ page.dash.gitea_webhook.add }}" method="POST">
<label class="auth-form__label" for="gitea_url">
Gitea instance URL
<input
type="url"
name="gitea_url"
id="gitea_url"
class="auth-form__input"
/>
</label>
<div class="auth-form__action-container">
<button class="auth-form__submit" type="submit">Add Webhook</button>
</div>
</form>
</div>
</main>
{% endblock main %}

View File

@ -0,0 +1,33 @@
{% extends 'base' %}{% block title %} Gitea Webhooks{% endblock title %} {% block nav
%} {% include "auth_nav" %} {% endblock nav %} {% block main %}
<main class="sites__main">
<div class="sites__collection">
<div class="sites__actions">
<a class="sites__actions__new-site" href="{{ page.dash.gitea_webhook.add }}">
<button>Add New Gitea Webhook</button>
</a>
</div>
{% if payload|length > 0 %}
{% for hook in payload %}
<a href="{{ hook.view }}" class="site__container">
<div class="site__info--head">
<img
class="site__container--preview"
src="{{ hook.webhook.gitea_url }}/favicon.ico"
alt="Webhook icon"
/>
<div class="site__info--column">
<p><b>{{ hook.webhook.gitea_url }}</b></p>
<p>Gitea instance {{ hook.webhook.gitea_url }}</p>
</div>
</div>
</a>
{% endfor %}
{% else %}
<p class="sites__banner">Nothing to show, click <a href="{{page.dash.gitea_webhook.add}}">here</a> to add new Gitea webhook!</p>
{% endif %}
</div>
</main>
{% endblock main %}

View File

@ -0,0 +1,32 @@
{% extends 'base' %}{% block title %} {{ payload.webhook.gitea_url }}{% endblock title %} {% block nav
%} {% include "auth_nav" %} {% endblock nav %} {% block main %}
<main class="sites__main">
<div class="add-site__container">
<section>
<table>
<tr>
<th>Webhook URL</th>
<td>{{ payload.url }}</td>
</tr>
<tr>
<th>Secret</th>
<td>
{% if show_gitea_webhook_secret %}
{{ payload.webhook.gitea_webhook_secret }} <a href="{{ payload.view }}">Hide</a>
{% else %}
****
<a href="{{ payload.view }}?show_gitea_webhook_secret=true">
Show
</a>
{% endif %}
</td>
</tr>
</table>
</section>
</div>
</main>
{% endblock main %}

View File

@ -15,7 +15,7 @@
<img
class="site__container--preview"
src="{{ deployment.site.hostname }}/favicon.ico"
alt="{{ deployment.site.hostname }}'s favicon"
alt="Website icon"
/>
<div class="site__info--column">
<p><b>{{ deployment.site.hostname }}</b></p>