mirror of
https://github.com/zed-industries/zed.git
synced 2025-02-05 02:20:10 +00:00
44 lines
1.2 KiB
Rust
44 lines
1.2 KiB
Rust
|
use crate::{AppState, Request, RequestExt as _};
|
||
|
use async_trait::async_trait;
|
||
|
use std::sync::Arc;
|
||
|
|
||
|
pub fn add_routes(app: &mut tide::Server<Arc<AppState>>) {
|
||
|
app.at("/users/:github_login").get(get_user);
|
||
|
}
|
||
|
|
||
|
async fn get_user(request: Request) -> tide::Result {
|
||
|
request.require_token().await?;
|
||
|
|
||
|
let user = request
|
||
|
.db()
|
||
|
.get_user_by_github_login(request.param("github_login")?)
|
||
|
.await?
|
||
|
.ok_or_else(|| surf::Error::from_str(404, "user not found"))?;
|
||
|
|
||
|
Ok(tide::Response::builder(200)
|
||
|
.body(tide::Body::from_json(&user)?)
|
||
|
.build())
|
||
|
}
|
||
|
|
||
|
#[async_trait]
|
||
|
pub trait RequestExt {
|
||
|
async fn require_token(&self) -> tide::Result<()>;
|
||
|
}
|
||
|
|
||
|
#[async_trait]
|
||
|
impl RequestExt for Request {
|
||
|
async fn require_token(&self) -> tide::Result<()> {
|
||
|
let token = self
|
||
|
.header("Authorization")
|
||
|
.and_then(|header| header.get(0))
|
||
|
.and_then(|header| header.as_str().strip_prefix("token "))
|
||
|
.ok_or_else(|| surf::Error::from_str(403, "invalid authorization header"))?;
|
||
|
|
||
|
if token == self.state().config.api_token {
|
||
|
Ok(())
|
||
|
} else {
|
||
|
Err(tide::Error::from_str(403, "invalid authorization token"))
|
||
|
}
|
||
|
}
|
||
|
}
|