Add the fetching of user JSON by github login with a token header
This commit is contained in:
parent
f4b9772ec2
commit
323e1f7367
3 changed files with 47 additions and 0 deletions
43
crates/server/src/api.rs
Normal file
43
crates/server/src/api.rs
Normal file
|
@ -0,0 +1,43 @@
|
|||
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"))
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue