Avoid panics (#392)

- Use `Result` as much as possible
- Display errors instead of panicking

TODO (maybe in another PR? this one is already quite big):
- Find a way to merge Ructe/ErrorPage types, so that we can have routes returning `Result<X, ErrorPage>` instead of panicking when we have an `Error`
- Display more details about the error, to make it easier to debug

(sorry, this isn't going to be fun to review, the diff is huge, but it is always the same changes)
This commit is contained in:
Baptiste Gelez
2018-12-29 09:36:07 +01:00
committed by GitHub
parent 4059a840be
commit 80a4dae8bd
50 changed files with 1879 additions and 1990 deletions
+40 -14
View File
@@ -1,15 +1,41 @@
use rocket::request::Form;
use rocket::{response::{self, Responder}, request::{Form, Request}};
use rocket_contrib::json::Json;
use serde_json;
use plume_common::utils::random_hex;
use plume_models::{
Error,
apps::App,
api_tokens::*,
db_conn::DbConn,
users::User,
};
#[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"
})).respond_to(req),
Error::Unauthorized => Json(json!({
"error": "You are not authorized to access this resource"
})).respond_to(req),
_ => Json(json!({
"error": "Server error"
})).respond_to(req)
}
}
}
#[derive(FromForm)]
pub struct OAuthRequest {
client_id: String,
@@ -20,38 +46,38 @@ pub struct OAuthRequest {
}
#[get("/oauth2?<query..>")]
pub fn oauth(query: Form<OAuthRequest>, conn: DbConn) -> Json<serde_json::Value> {
let app = App::find_by_client_id(&*conn, &query.client_id).expect("OAuth request from unknown client");
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 Some(user) = User::find_local(&*conn, &query.username) {
if let Ok(user) = User::find_local(&*conn, &query.username) {
if user.auth(&query.password) {
let token = ApiToken::insert(&*conn, NewApiToken {
app_id: app.id,
user_id: user.id,
value: random_hex(),
scopes: query.scopes.clone(),
});
Json(json!({
})?;
Ok(Json(json!({
"token": token.value
}))
})))
} else {
Json(json!({
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).unwrap().auth(&query.password);
Json(json!({
User::get(&*conn, 1)?.auth(&query.password);
Ok(Json(json!({
"error": "Invalid credentials"
}))
})))
}
} else {
Json(json!({
Ok(Json(json!({
"error": "Invalid client_secret"
}))
})))
}
}