2022-04-21 19:12:16 +02:00
|
|
|
use crate::schema;
|
|
|
|
use crate::schema::DbConn;
|
2022-03-29 19:32:21 +02:00
|
|
|
use crate::AppConfig;
|
2022-04-21 19:12:16 +02:00
|
|
|
use chrono::Utc;
|
2022-03-29 19:32:21 +02:00
|
|
|
use jsonwebtoken::decode;
|
2022-04-21 19:12:16 +02:00
|
|
|
use jsonwebtoken::encode;
|
2022-03-29 19:32:21 +02:00
|
|
|
use jsonwebtoken::DecodingKey;
|
|
|
|
use jsonwebtoken::Validation;
|
2022-04-21 19:12:16 +02:00
|
|
|
use jsonwebtoken::{EncodingKey, Header};
|
|
|
|
use rocket::http::Status;
|
|
|
|
use rocket::request::Outcome;
|
2022-04-21 19:44:42 +02:00
|
|
|
use rocket::request::{FromRequest, Request};
|
2022-04-21 19:12:16 +02:00
|
|
|
use rocket::serde::json::{json, Json, Value};
|
2022-03-29 19:32:21 +02:00
|
|
|
use rocket::State;
|
2022-04-21 19:12:16 +02:00
|
|
|
use serde::{Deserialize, Serialize};
|
2022-03-29 19:32:21 +02:00
|
|
|
use std::borrow::Cow;
|
2022-04-21 19:12:16 +02:00
|
|
|
use validator::ValidateArgs;
|
2022-03-29 19:32:21 +02:00
|
|
|
|
|
|
|
#[derive(Debug, Responder)]
|
|
|
|
pub enum ApiResponseVariant {
|
|
|
|
Status(Status),
|
2022-04-21 19:12:16 +02:00
|
|
|
// Redirect(Redirect),
|
2022-03-29 19:32:21 +02:00
|
|
|
Value(Value),
|
2022-04-21 19:12:16 +02:00
|
|
|
// Flash(Flash<Redirect>)
|
2022-03-29 19:32:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
struct ApiResponse {
|
|
|
|
result: Cow<'static, str>,
|
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
2022-04-21 19:12:16 +02:00
|
|
|
message: Option<Cow<'static, str>>,
|
2022-03-29 19:32:21 +02:00
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
2022-04-21 19:12:16 +02:00
|
|
|
jwt: Option<Cow<'static, str>>,
|
2022-04-29 22:40:10 +02:00
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
|
|
gamenights: Option<Vec<schema::GameNight>>,
|
2022-03-29 19:32:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ApiResponse {
|
|
|
|
const SUCCES_RESULT: Cow<'static, str> = Cow::Borrowed("Ok");
|
|
|
|
const FAILURE_RESULT: Cow<'static, str> = Cow::Borrowed("Failure");
|
|
|
|
|
|
|
|
const SUCCES: Self = Self {
|
|
|
|
result: Self::SUCCES_RESULT,
|
|
|
|
message: None,
|
2022-04-21 19:12:16 +02:00
|
|
|
jwt: None,
|
2022-04-29 22:40:10 +02:00
|
|
|
gamenights: None,
|
2022-03-29 19:32:21 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
fn error(message: String) -> Self {
|
2022-04-21 19:12:16 +02:00
|
|
|
Self {
|
2022-03-29 19:32:21 +02:00
|
|
|
result: Self::FAILURE_RESULT,
|
|
|
|
message: Some(Cow::Owned(message)),
|
2022-04-21 19:12:16 +02:00
|
|
|
jwt: None,
|
2022-04-29 22:40:10 +02:00
|
|
|
gamenights: None,
|
2022-03-29 19:32:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn login_response(jwt: String) -> Self {
|
|
|
|
Self {
|
|
|
|
result: Self::SUCCES_RESULT,
|
|
|
|
message: None,
|
2022-04-21 19:12:16 +02:00
|
|
|
jwt: Some(Cow::Owned(jwt)),
|
2022-04-29 22:40:10 +02:00
|
|
|
gamenights: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn gamenight_response(gamenights: Vec<schema::GameNight>) -> Self {
|
|
|
|
Self {
|
|
|
|
result: Self::SUCCES_RESULT,
|
|
|
|
message: None,
|
|
|
|
jwt: None,
|
|
|
|
gamenights: Some(gamenights),
|
2022-03-29 19:32:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum ApiError {
|
|
|
|
RequestError(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
const AUTH_HEADER: &str = "Authorization";
|
|
|
|
const BEARER: &str = "Bearer ";
|
|
|
|
|
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for schema::User {
|
|
|
|
type Error = ApiError;
|
|
|
|
|
|
|
|
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
|
|
|
let header = match req.headers().get_one(AUTH_HEADER) {
|
|
|
|
Some(header) => header,
|
2022-04-21 19:12:16 +02:00
|
|
|
None => {
|
2022-04-21 21:35:14 +02:00
|
|
|
return Outcome::Forward(())
|
2022-04-21 19:12:16 +02:00
|
|
|
}
|
2022-03-29 19:32:21 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
if !header.starts_with(BEARER) {
|
2022-04-21 21:35:14 +02:00
|
|
|
return Outcome::Forward(());
|
2022-03-29 19:32:21 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
let app_config = req.guard::<&State<AppConfig>>().await.unwrap().inner();
|
|
|
|
let jwt = header.trim_start_matches(BEARER).to_owned();
|
2022-04-21 19:12:16 +02:00
|
|
|
let token = match decode::<Claims>(
|
|
|
|
&jwt,
|
|
|
|
&DecodingKey::from_secret(app_config.jwt_secret.as_bytes()),
|
|
|
|
&Validation::default(),
|
|
|
|
) {
|
2022-03-29 19:32:21 +02:00
|
|
|
Ok(token) => token,
|
2022-04-21 21:35:14 +02:00
|
|
|
Err(_) => {
|
|
|
|
return Outcome::Forward(())
|
2022-04-21 19:12:16 +02:00
|
|
|
}
|
2022-03-29 19:32:21 +02:00
|
|
|
};
|
|
|
|
let id = token.claims.uid;
|
2022-04-21 19:12:16 +02:00
|
|
|
|
2022-03-29 19:32:21 +02:00
|
|
|
let conn = req.guard::<DbConn>().await.unwrap();
|
2022-04-21 19:12:16 +02:00
|
|
|
return Outcome::Success(schema::get_user(conn, id).await);
|
2022-03-29 19:32:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/gamenights")]
|
2022-04-21 21:35:14 +02:00
|
|
|
pub async fn gamenights(conn: DbConn, _user: schema::User) -> ApiResponseVariant {
|
|
|
|
let gamenights = schema::get_all_gamenights(conn).await;
|
2022-04-29 22:40:10 +02:00
|
|
|
ApiResponseVariant::Value(json!(ApiResponse::gamenight_response(gamenights)))
|
2022-04-21 21:35:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/gamenights", rank = 2)]
|
|
|
|
pub async fn gamenights_unauthorized() -> ApiResponseVariant {
|
|
|
|
ApiResponseVariant::Status(Status::Unauthorized)
|
2022-03-29 19:32:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[post("/gamenight", format = "application/json", data = "<gamenight_json>")]
|
2022-04-21 19:12:16 +02:00
|
|
|
pub async fn gamenight_post_json(
|
|
|
|
conn: DbConn,
|
2022-04-29 22:40:10 +02:00
|
|
|
_user: schema::User,
|
2022-04-21 19:12:16 +02:00
|
|
|
gamenight_json: Json<schema::GameNightNoId>,
|
|
|
|
) -> ApiResponseVariant {
|
2022-04-29 22:40:10 +02:00
|
|
|
match schema::insert_gamenight(conn, gamenight_json.into_inner()).await {
|
|
|
|
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
|
|
|
|
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
|
2022-03-29 19:32:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-29 22:40:10 +02:00
|
|
|
#[post("/gamenight", rank = 2)]
|
|
|
|
pub async fn gamenight_post_json_unauthorized() -> ApiResponseVariant {
|
|
|
|
ApiResponseVariant::Status(Status::Unauthorized)
|
|
|
|
}
|
|
|
|
|
2022-03-29 19:32:21 +02:00
|
|
|
#[post("/register", format = "application/json", data = "<register_json>")]
|
2022-04-21 19:12:16 +02:00
|
|
|
pub async fn register_post_json(
|
|
|
|
conn: DbConn,
|
|
|
|
register_json: Json<schema::Register>,
|
|
|
|
) -> ApiResponseVariant {
|
2022-04-21 13:30:44 +02:00
|
|
|
let register = register_json.into_inner();
|
|
|
|
let register_clone = register.clone();
|
2022-04-21 19:12:16 +02:00
|
|
|
match conn
|
|
|
|
.run(move |c| register_clone.validate_args((c, c)))
|
|
|
|
.await
|
|
|
|
{
|
2022-04-21 13:30:44 +02:00
|
|
|
Ok(()) => (),
|
2022-04-21 19:12:16 +02:00
|
|
|
Err(error) => {
|
|
|
|
return ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
|
|
|
|
}
|
2022-04-21 13:30:44 +02:00
|
|
|
}
|
2022-04-21 19:12:16 +02:00
|
|
|
|
2022-04-21 13:30:44 +02:00
|
|
|
match schema::insert_user(conn, register).await {
|
2022-03-29 19:32:21 +02:00
|
|
|
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
|
2022-04-21 19:12:16 +02:00
|
|
|
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
|
2022-03-29 19:32:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
|
|
struct Claims {
|
|
|
|
exp: i64,
|
|
|
|
uid: i32,
|
|
|
|
role: schema::Role,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[post("/login", format = "application/json", data = "<login_json>")]
|
2022-04-21 19:12:16 +02:00
|
|
|
pub async fn login_post_json(
|
|
|
|
conn: DbConn,
|
|
|
|
config: &State<AppConfig>,
|
|
|
|
login_json: Json<schema::Login>,
|
|
|
|
) -> ApiResponseVariant {
|
2022-03-29 19:32:21 +02:00
|
|
|
match schema::login(conn, login_json.into_inner()).await {
|
|
|
|
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
|
|
|
|
Ok(login_result) => {
|
2022-04-21 19:12:16 +02:00
|
|
|
if !login_result.result {
|
|
|
|
return ApiResponseVariant::Value(json!(ApiResponse::error(String::from(
|
|
|
|
"username and password didn't match"
|
|
|
|
))));
|
|
|
|
}
|
|
|
|
|
2022-03-29 19:32:21 +02:00
|
|
|
let my_claims = Claims {
|
|
|
|
exp: Utc::now().timestamp() + chrono::Duration::days(7).num_seconds(),
|
|
|
|
uid: login_result.id.unwrap(),
|
2022-04-21 19:12:16 +02:00
|
|
|
role: login_result.role.unwrap(),
|
2022-03-29 19:32:21 +02:00
|
|
|
};
|
2022-04-21 19:12:16 +02:00
|
|
|
|
2022-03-29 19:32:21 +02:00
|
|
|
let secret = &config.inner().jwt_secret;
|
2022-04-21 19:12:16 +02:00
|
|
|
match encode(
|
|
|
|
&Header::default(),
|
|
|
|
&my_claims,
|
|
|
|
&EncodingKey::from_secret(secret.as_bytes()),
|
|
|
|
) {
|
2022-03-29 19:32:21 +02:00
|
|
|
Ok(token) => ApiResponseVariant::Value(json!(ApiResponse::login_response(token))),
|
2022-04-21 19:12:16 +02:00
|
|
|
Err(error) => {
|
|
|
|
ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
|
|
|
|
}
|
2022-03-29 19:32:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-04-21 19:12:16 +02:00
|
|
|
}
|