added auth

This commit is contained in:
Alex 2022-08-27 17:59:43 -04:00
parent 34bc843476
commit cf1982a2bd
Signed by: technically
GPG Key ID: 46E0A080F69E83F1

View File

@ -1,5 +1,5 @@
use serde; use serde;
use worker::*; use worker::{kv::KvStore, *};
#[event(fetch)] #[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> { pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
@ -16,8 +16,23 @@ pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Respo
created_at: String, created_at: String,
} }
async fn check_endpoint_auth(token: &String, kv: KvStore) -> bool {
// Check if the token provided by the endpoint is valid.
match kv.get("authorized_tokens").cache_ttl(300).text().await.unwrap() {
Some(t) => t.split(",")
.any(|authorized_token| authorized_token == token),
None => false,
}
}
router router
.get_async("/asterisk/:hostname", |_req, ctx| async move { .get_async("/asterisk/:hostname/:token", |_req, ctx| async move {
if let Some(token) = ctx.param("token") {
if !check_endpoint_auth(token, ctx.kv("GONK_NODES")?).await {
return Response::error("Unauthorized", 401);
}
}
if let Some(hostname) = ctx.param("hostname") { if let Some(hostname) = ctx.param("hostname") {
let kv = ctx.kv("GONK_NODES")?; let kv = ctx.kv("GONK_NODES")?;
@ -31,7 +46,12 @@ pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Respo
} }
Response::error("Bad Request", 400) Response::error("Bad Request", 400)
}) })
.get_async("/pjsip/:hostname", |_req, ctx| async move { .get_async("/pjsip/:hostname/:token", |_req, ctx| async move {
if let Some(token) = ctx.param("token") {
if !check_endpoint_auth(token, ctx.kv("GONK_NODES")?).await {
return Response::error("Unauthorized", 401);
}
}
if let Some(hostname) = ctx.param("hostname") { if let Some(hostname) = ctx.param("hostname") {
let kv = ctx.kv("GONK_NODES")?; let kv = ctx.kv("GONK_NODES")?;