Browse Source

unauthorized

pull/25/head
Alexey Velikiy 3 years ago
parent
commit
27a286be18
  1. 9
      server/src/api.rs
  2. 18
      server/src/api/auth.rs

9
server/src/api.rs

@ -13,7 +13,7 @@ use parking_lot::RwLock;
use std::sync::Arc; use std::sync::Arc;
#[derive(Serialize)] #[derive(Serialize)]
struct Options { pub struct Message {
message: String, message: String,
} }
@ -29,6 +29,10 @@ impl API {
} }
fn json<T: Serialize>(t: &T) -> Response<Body> { fn json<T: Serialize>(t: &T) -> Response<Body> {
API::json_with_code(t, StatusCode::OK)
}
fn json_with_code<T: Serialize>(t: &T, status_code: StatusCode) -> Response<Body> {
let j = warp::reply::json(t); let j = warp::reply::json(t);
let mut rs = j.into_response(); let mut rs = j.into_response();
let hs = rs.headers_mut(); let hs = rs.headers_mut();
@ -41,6 +45,7 @@ impl API {
"Access-Control-Allow-Headers", "Access-Control-Allow-Headers",
HeaderValue::from_static("*"), HeaderValue::from_static("*"),
); );
*rs.status_mut() = status_code;
rs rs
} }
@ -48,7 +53,7 @@ impl API {
let not_found = let not_found =
warp::any().map(|| warp::reply::with_status("Not found", StatusCode::NOT_FOUND)); warp::any().map(|| warp::reply::with_status("Not found", StatusCode::NOT_FOUND));
let options = warp::any().and(options()).map(|| { let options = warp::any().and(options()).map(|| {
API::json(&Options { API::json(&Message {
message: "ok".to_owned(), message: "ok".to_owned(),
}) })
}); });

18
server/src/api/auth.rs

@ -2,13 +2,13 @@ use hastic::services::user_service;
use warp::filters::method::post; use warp::filters::method::post;
use warp::http::HeaderValue; use warp::http::HeaderValue;
use warp::hyper::Body; use warp::hyper::{Body, StatusCode};
use warp::{http::Response, Filter}; use warp::{http::Response, Filter};
use warp::{Rejection, Reply}; use warp::{Rejection, Reply};
use serde::Serialize; use serde::Serialize;
use crate::api; use crate::api::{self, API};
use parking_lot::RwLock; use parking_lot::RwLock;
use std::sync::Arc; use std::sync::Arc;
@ -26,11 +26,15 @@ pub fn get_route(
.and(warp::body::json()) .and(warp::body::json())
.map(move |user: user_service::User| { .map(move |user: user_service::User| {
let us = user_service.write().login(&user); let us = user_service.write().login(&user);
match us { if let Some(token) = us {
Some(token) => api::API::json(&SigninResp { token }), return api::API::json(&SigninResp { token });
None => api::API::json(&SigninResp { } else {
token: "no token".to_string(), return api::API::json_with_code(
}), &api::Message {
message: "wrong login or password".to_owned(),
},
StatusCode::UNAUTHORIZED,
);
} }
}); });
} }

Loading…
Cancel
Save