moved from mono repo

This commit is contained in:
realaravinth
2021-03-09 15:58:54 +05:30
commit 2c54518e12
13 changed files with 913 additions and 0 deletions

49
src/data.rs Normal file
View File

@@ -0,0 +1,49 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use argon2_creds::{Config, ConfigBuilder, PasswordPolicy};
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use crate::SETTINGS;
#[derive(Clone)]
pub struct Data {
pub db: PgPool,
pub creds: Config,
}
impl Data {
#[cfg(not(tarpaulin_include))]
pub async fn new() -> Self {
let db = PgPoolOptions::new()
.max_connections(SETTINGS.database.pool)
.connect(&SETTINGS.database.url)
.await
.expect("Unable to form database pool");
let creds = ConfigBuilder::default()
.username_case_mapped(false)
.profanity(true)
.blacklist(false)
.password_policy(PasswordPolicy::default())
.build()
.unwrap();
Data { creds, db }
}
}

139
src/errors.rs Normal file
View File

@@ -0,0 +1,139 @@
use std::io::{Error as IOError, ErrorKind as IOErrorKind};
use actix_web::{
dev::HttpResponseBuilder,
error::ResponseError,
http::{header, StatusCode},
HttpResponse,
};
use argon2_creds::errors::CredsError;
use derive_more::{Display, Error};
use log::debug;
use serde::Serialize;
// use validator::ValidationErrors;
use std::convert::From;
#[derive(Debug, Display, Clone, PartialEq, Error)]
#[cfg(not(tarpaulin_include))]
pub enum ServiceError {
#[display(fmt = "internal server error")]
InternalServerError,
#[display(fmt = "The value you entered for email is not an email")] //405j
NotAnEmail,
#[display(fmt = "File not found")]
FileNotFound,
#[display(fmt = "File exists")]
FileExists,
#[display(fmt = "Permission denied")]
PermissionDenied,
#[display(fmt = "Invalid credentials")]
InvalidCredentials,
#[display(fmt = "Authorization required")]
AuthorizationRequired,
/// when the value passed contains profainity
#[display(fmt = "Can't allow profanity in usernames")]
ProfainityError,
/// when the value passed contains blacklisted words
/// see [blacklist](https://github.com/shuttlecraft/The-Big-Username-Blacklist)
#[display(fmt = "Username contains blacklisted words")]
BlacklistError,
/// when the value passed contains characters not present
/// in [UsernameCaseMapped](https://tools.ietf.org/html/rfc8265#page-7)
/// profile
#[display(fmt = "username_case_mapped violation")]
UsernameCaseMappedError,
/// when the value passed contains profainity
#[display(fmt = "Username not available")]
UsernameTaken,
/// when a question is already answered
#[display(fmt = "Already answered")]
AlreadyAnswered,
}
#[derive(Serialize)]
#[cfg(not(tarpaulin_include))]
struct ErrorToResponse {
error: String,
}
impl ResponseError for ServiceError {
fn error_response(&self) -> HttpResponse {
HttpResponseBuilder::new(self.status_code())
.set_header(header::CONTENT_TYPE, "application/json; charset=UTF-8")
.json(ErrorToResponse {
error: self.to_string(),
})
}
fn status_code(&self) -> StatusCode {
match *self {
ServiceError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::NotAnEmail => StatusCode::BAD_REQUEST,
ServiceError::FileNotFound => StatusCode::NOT_FOUND,
ServiceError::FileExists => StatusCode::METHOD_NOT_ALLOWED,
ServiceError::PermissionDenied => StatusCode::UNAUTHORIZED,
ServiceError::InvalidCredentials => StatusCode::UNAUTHORIZED,
ServiceError::AuthorizationRequired => StatusCode::UNAUTHORIZED,
ServiceError::ProfainityError => StatusCode::BAD_REQUEST,
ServiceError::BlacklistError => StatusCode::BAD_REQUEST,
ServiceError::UsernameCaseMappedError => StatusCode::BAD_REQUEST,
ServiceError::UsernameTaken => StatusCode::BAD_REQUEST,
ServiceError::AlreadyAnswered => StatusCode::BAD_REQUEST,
}
}
}
impl From<IOError> for ServiceError {
fn from(e: IOError) -> ServiceError {
debug!("{:?}", &e);
match e.kind() {
IOErrorKind::NotFound => ServiceError::FileNotFound,
IOErrorKind::PermissionDenied => ServiceError::PermissionDenied,
IOErrorKind::AlreadyExists => ServiceError::FileExists,
_ => ServiceError::InternalServerError,
}
}
}
impl From<CredsError> for ServiceError {
fn from(e: CredsError) -> ServiceError {
debug!("{:?}", &e);
match e {
CredsError::UsernameCaseMappedError => ServiceError::UsernameCaseMappedError,
CredsError::ProfainityError => ServiceError::ProfainityError,
CredsError::BlacklistError => ServiceError::BlacklistError,
CredsError::NotAnEmail => ServiceError::NotAnEmail,
CredsError::Argon2Error(_) => ServiceError::InternalServerError,
_ => ServiceError::InternalServerError,
}
}
}
// impl From<ValidationErrors> for ServiceError {
// fn from(_: ValidationErrors) -> ServiceError {
// ServiceError::NotAnEmail
// }
// }
//
impl From<sqlx::Error> for ServiceError {
fn from(e: sqlx::Error) -> Self {
use sqlx::error::Error;
use std::borrow::Cow;
debug!("{:?}", &e);
if let Error::Database(err) = e {
if err.code() == Some(Cow::from("23505")) {
return ServiceError::UsernameTaken;
}
}
ServiceError::InternalServerError
}
}
pub type ServiceResult<V> = std::result::Result<V, ServiceError>;

82
src/main.rs Normal file
View File

@@ -0,0 +1,82 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{
error::InternalError, http::StatusCode, middleware, web::JsonConfig, App, HttpServer,
};
use lazy_static::lazy_static;
mod data;
mod errors;
//mod routes;
mod settings;
pub use data::Data;
pub use settings::Settings;
lazy_static! {
pub static ref SETTINGS: Settings = Settings::new().unwrap();
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// use routes::services;
// let data = Data::new().await;
pretty_env_logger::init();
// sqlx::migrate!("./migrations/").run(&data.db).await.unwrap();
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.wrap(get_identity_service())
.wrap(middleware::Compress::default())
// .data(data.clone())
.wrap(middleware::NormalizePath::new(
middleware::normalize::TrailingSlash::Trim,
))
.app_data(get_json_err())
//.configure(services)
})
.bind(SETTINGS.server.get_ip())
.unwrap()
.run()
.await
}
#[cfg(not(tarpaulin_include))]
fn get_json_err() -> JsonConfig {
JsonConfig::default().error_handler(|err, _| {
//debug!("JSON deserialization error: {:?}", &err);
InternalError::new(err, StatusCode::BAD_REQUEST).into()
})
}
#[cfg(not(tarpaulin_include))]
fn get_identity_service() -> IdentityService<CookieIdentityPolicy> {
let cookie_secret = &SETTINGS.server.cookie_secret;
IdentityService::new(
CookieIdentityPolicy::new(cookie_secret.as_bytes())
.name("Authorization")
//TODO change cookie age
.max_age(216000)
.domain(&SETTINGS.server.domain)
.secure(false),
)
}

248
src/routes.rs Normal file
View File

@@ -0,0 +1,248 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use actix_identity::Identity;
use actix_web::{
get, post,
web::{self, Path as WebPath, ServiceConfig},
HttpResponse, Responder,
};
use log::debug;
use serde::{Deserialize, Serialize};
use crate::errors::*;
use crate::Data;
#[derive(Clone, Debug, Deserialize, Serialize)]
struct SomeData {
pub a: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Creds {
pub username: String,
pub password: String,
}
#[post("/api/signup")]
async fn signup(payload: web::Json<Creds>, data: web::Data<Data>) -> ServiceResult<impl Responder> {
let username = data.creds.username(&payload.username)?;
let hash = data.creds.password(&payload.password)?;
sqlx::query!(
"INSERT INTO users (name , password) VALUES ($1, $2)",
username,
hash
)
.execute(&data.db)
.await?;
Ok(HttpResponse::Ok())
}
struct Password {
password: String,
}
#[post("/api/signin")]
async fn signin(
id: Identity,
payload: web::Json<Creds>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
use argon2_creds::Config;
let rec = sqlx::query_as!(
Password,
"SELECT password FROM users WHERE name = ($1)",
&payload.username
)
.fetch_one(&data.db)
.await?;
if Config::verify(&rec.password, &payload.password)? {
debug!("remembered {}", payload.username);
id.remember(payload.into_inner().username);
return Ok(HttpResponse::Ok());
} else {
return Err(ServiceError::InvalidCredentials);
}
}
#[get("/api/signout")]
async fn signout(id: Identity) -> impl Responder {
if let Some(_) = id.identity() {
id.forget();
}
HttpResponse::Ok()
}
#[get("/questions/{id}")]
async fn get_question(
//session: Session,
id: Identity,
path: WebPath<(u32,)>,
) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
Ok(HttpResponse::Ok().body(format!("User detail: {}", path.into_inner().0)))
}
struct LevelScore {
level: i32,
points: i32,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Answer {
answer: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct AnswerDatabaseFetch {
answer: String,
points: i32,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct AnswerVerifyResp {
correct: bool,
points: i32,
}
#[post("/api/answer/verify/{id}")]
async fn verify_answer(
//session: Session,
payload: web::Json<Answer>,
data: web::Data<Data>,
id: Identity,
path: WebPath<(u32,)>,
) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let name = id.identity().unwrap();
let rec = sqlx::query_as!(
LevelScore,
"SELECT level, points FROM users WHERE name = ($1)",
&name
)
.fetch_one(&data.db)
.await?;
let current = path.into_inner().0 as i32;
if rec.level == current {
// TODO
// check answer
let answer = sqlx::query_as!(
AnswerDatabaseFetch,
"SELECT answer, points FROM answers WHERE question_num = ($1)",
&current
)
.fetch_one(&data.db)
.await?;
let resp;
// TODO all answers lowercase?
if payload.answer.trim().to_lowercase() == answer.answer {
let points = rec.points + answer.points;
resp = AnswerVerifyResp {
correct: true,
points,
};
sqlx::query!(
"UPDATE users SET points = $1, level = $2 WHERE name = $3",
points,
rec.level + 1,
name
)
.execute(&data.db)
.await?;
} else {
resp = AnswerVerifyResp {
correct: false,
points: rec.points,
};
}
return Ok(HttpResponse::Ok().json(resp));
} else if rec.level > current {
return Err(ServiceError::AlreadyAnswered);
} else {
return Err(ServiceError::AuthorizationRequired);
}
}
#[get("/api/score")]
async fn score(
//session: Session,
// payload: web::Json<SomeData>,
data: web::Data<Data>,
id: Identity,
) -> ServiceResult<impl Responder> {
debug!("{:?}", id.identity());
is_authenticated(&id)?;
let recs = sqlx::query_as!(
Leader,
"SELECT name, points FROM users ORDER BY points DESC"
)
.fetch_all(&data.db)
.await?;
Ok(HttpResponse::Ok().json(recs))
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Leader {
name: String,
points: i32,
}
#[get("/api/leaderboard")]
async fn leaderboard(
//session: Session,
// payload: web::Json<SomeData>,
data: web::Data<Data>,
id: Identity,
) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let recs = sqlx::query_as!(
Leader,
"SELECT name, points FROM users ORDER BY points DESC"
)
.fetch_all(&data.db)
.await?;
debug!("{:?}", &recs);
Ok(HttpResponse::Ok().json(recs))
}
pub fn services(cfg: &mut ServiceConfig) {
cfg.service(get_question);
cfg.service(verify_answer);
cfg.service(score);
cfg.service(leaderboard);
cfg.service(signout);
cfg.service(signin);
cfg.service(signup);
}
fn is_authenticated(id: &Identity) -> ServiceResult<bool> {
debug!("{:?}", id.identity());
// access request identity
if let Some(_) = id.identity() {
Ok(true)
} else {
Err(ServiceError::AuthorizationRequired)
}
}

153
src/settings.rs Normal file
View File

@@ -0,0 +1,153 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::env;
use config::{Config, ConfigError, Environment, File};
use log::debug;
use serde::Deserialize;
use url::Url;
#[derive(Debug, Clone, Deserialize)]
pub struct Server {
// TODO yet to be configured
pub allow_registration: bool,
pub port: u32,
pub domain: String,
pub cookie_secret: String,
pub ip: String,
}
impl Server {
pub fn get_ip(&self) -> String {
format!("{}:{}", self.ip, self.port)
}
}
#[derive(Debug, Clone, Deserialize)]
struct DatabaseBuilder {
pub port: u32,
pub hostname: String,
pub username: String,
pub password: String,
pub name: String,
pub url: String,
}
impl DatabaseBuilder {
fn extract_database_url(url: &Url) -> Self {
// if url.scheme() != "postgres" || url.scheme() != "postgresql" {
// panic!("URL must be postgres://url, url found: {}", url.scheme());
// } else {
debug!("Databse name: {}", url.path());
let mut path = url.path().split("/");
path.next();
let name = path.next().expect("no database name").to_string();
DatabaseBuilder {
port: url.port().expect("Enter database port").into(),
hostname: url.host().expect("Enter database host").to_string(),
username: url.username().into(),
url: url.to_string(),
password: url.password().expect("Enter database password").into(),
name,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Database {
pub url: String,
pub pool: u32,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Settings {
pub debug: bool,
pub database: Database,
pub server: Server,
}
#[cfg(not(tarpaulin_include))]
impl Settings {
pub fn new() -> Result<Self, ConfigError> {
let mut s = Config::new();
// setting default values
#[cfg(test)]
s.set_default("database.pool", 2.to_string())
.expect("Couldn't get the number of CPUs");
// merging default config from file
s.merge(File::with_name("./config/default.toml"))?;
// TODO change PLACEHOLDER to app name
s.merge(Environment::with_prefix("WEBHUNT"))?;
match env::var("PORT") {
Ok(val) => {
s.set("server.port", val).unwrap();
}
Err(e) => println!("couldn't interpret PORT: {}", e),
}
match env::var("DATABASE_URL") {
Ok(val) => {
let url = Url::parse(&val).expect("couldn't parse Database URL");
let database_conf = DatabaseBuilder::extract_database_url(&url);
set_from_database_url(&mut s, &database_conf);
}
Err(e) => println!("couldn't interpret DATABASE_URL: {}", e),
}
set_database_url(&mut s);
s.try_into()
}
}
fn set_from_database_url(s: &mut Config, database_conf: &DatabaseBuilder) {
s.set("database.username", database_conf.username.clone())
.expect("Couldn't set database username");
s.set("database.password", database_conf.password.clone())
.expect("Couldn't access database password");
s.set("database.hostname", database_conf.hostname.clone())
.expect("Couldn't access database hostname");
s.set("database.port", database_conf.port as i64)
.expect("Couldn't access database port");
s.set("database.name", database_conf.name.clone())
.expect("Couldn't access database name");
}
fn set_database_url(s: &mut Config) {
s.set(
"database.url",
format!(
r"postgres://{}:{}@{}:{}/{}",
s.get::<String>("database.username")
.expect("Couldn't access database username"),
s.get::<String>("database.password")
.expect("Couldn't access database password"),
s.get::<String>("database.hostname")
.expect("Couldn't access database hostname"),
s.get::<String>("database.port")
.expect("Couldn't access database port"),
s.get::<String>("database.name")
.expect("Couldn't access database name")
),
)
.expect("Couldn't set databse url");
}