Plume/src/api/mod.rs

82 lines
2.1 KiB
Rust
Raw Normal View History

#![warn(clippy::too_many_arguments)]
2019-03-20 17:56:17 +01:00
use rocket::{
request::{Form, Request},
response::{self, Responder},
};
use rocket_contrib::json::Json;
use plume_common::utils::random_hex;
2021-01-30 13:44:29 +01:00
use plume_models::{api_tokens::*, apps::App, db_conn::DbConn, users::User, Error};
type Api<T> = Result<Json<T>, ApiError>;
#[derive(Debug)]
pub struct ApiError(Error);
impl From<Error> for ApiError {
fn from(err: Error) -> ApiError {
ApiError(err)
}
}
impl<'r> Responder<'r> for ApiError {
2020-01-21 07:02:03 +01:00
fn respond_to(self, req: &Request<'_>) -> response::Result<'r> {
match self.0 {
Error::NotFound => Json(json!({
"error": "Not found"
2019-03-20 17:56:17 +01:00
}))
.respond_to(req),
Error::Unauthorized => Json(json!({
"error": "You are not authorized to access this resource"
2019-03-20 17:56:17 +01:00
}))
.respond_to(req),
_ => Json(json!({
"error": "Server error"
2019-03-20 17:56:17 +01:00
}))
.respond_to(req),
}
}
}
#[derive(FromForm)]
pub struct OAuthRequest {
client_id: String,
client_secret: String,
password: String,
username: String,
scopes: String,
}
#[get("/oauth2?<query..>")]
2021-01-30 13:44:29 +01:00
pub fn oauth(query: Form<OAuthRequest>, conn: DbConn) -> Result<Json<serde_json::Value>, ApiError> {
let app = App::find_by_client_id(&conn, &query.client_id)?;
if app.client_secret == query.client_secret {
2021-01-30 13:44:29 +01:00
if let Ok(user) = User::login(&conn, &query.username, &query.password) {
let token = ApiToken::insert(
2021-01-30 13:44:29 +01:00
&conn,
NewApiToken {
app_id: app.id,
user_id: user.id,
value: random_hex(),
scopes: query.scopes.clone(),
},
)?;
Ok(Json(json!({
"token": token.value
})))
} else {
Ok(Json(json!({
"error": "Invalid credentials"
})))
}
} else {
Ok(Json(json!({
"error": "Invalid client_secret"
})))
}
}
2018-10-21 18:22:27 +02:00
pub mod apps;
pub mod authorization;
2018-09-19 16:49:34 +02:00
pub mod posts;