Plume/src/api/mod.rs

91 lines
2.5 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 serde_json;
use plume_common::utils::random_hex;
2019-03-20 17:56:17 +01:00
use plume_models::{api_tokens::*, apps::App, db_conn::DbConn, users::User, Error};
#[derive(Debug)]
pub struct ApiError(Error);
impl From<Error> for ApiError {
fn from(err: Error) -> ApiError {
ApiError(err)
}
}
impl<'r> Responder<'r> for ApiError {
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..>")]
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 {
if let Ok(user) = User::find_by_fqn(&*conn, &query.username) {
if user.auth(&query.password) {
2019-03-20 17:56:17 +01:00
let token = ApiToken::insert(
&*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 {
// Making fake password verification to avoid different
// response times that would make it possible to know
// if a username is registered or not.
User::get(&*conn, 1)?.auth(&query.password);
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;