Add an endpoint for creating an access token for a GitHub login

This commit is contained in:
Nathan Sobo 2021-12-21 13:05:32 -07:00
parent 323e1f7367
commit 61b806e485
3 changed files with 21 additions and 2 deletions

View file

@ -1,9 +1,12 @@
use crate::{AppState, Request, RequestExt as _};
use crate::{auth, AppState, Request, RequestExt as _};
use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
pub fn add_routes(app: &mut tide::Server<Arc<AppState>>) {
app.at("/users/:github_login").get(get_user);
app.at("/users/:github_login/access_tokens")
.post(create_access_token);
}
async fn get_user(request: Request) -> tide::Result {
@ -20,6 +23,21 @@ async fn get_user(request: Request) -> tide::Result {
.build())
}
async fn create_access_token(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"))?;
let token = auth::create_access_token(request.db(), user.id).await?;
Ok(tide::Response::builder(200)
.body(json!({"user_id": user.id, "access_token": token}))
.build())
}
#[async_trait]
pub trait RequestExt {
async fn require_token(&self) -> tide::Result<()>;