Merge of dev-auth #1
160
src/main.rs
160
src/main.rs
@@ -11,8 +11,8 @@ use chrono::{DateTime, Days, Utc};
|
||||
#[cfg(target_os = "linux")]
|
||||
use daemonize::Daemonize;
|
||||
use futures;
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper::body::{Body, Incoming};
|
||||
use http_body_util::{BodyExt, Empty, Full};
|
||||
use hyper::body::{Body, Frame, Incoming, SizeHint};
|
||||
use hyper::header::{LOCATION, SET_COOKIE, COOKIE};
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::service::service_fn;
|
||||
@@ -23,15 +23,41 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{from_reader, Value};
|
||||
use sqlx::sqlite::SqlitePool;
|
||||
use std::collections::HashMap;
|
||||
use std::convert::Infallible;
|
||||
use std::env;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::str::FromStr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::SystemTime;
|
||||
use hyper::http::HeaderValue;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
// Some functions could return an empty body, will try using the following enum:
|
||||
enum ResponseBody {
|
||||
Full(Full<Bytes>),
|
||||
Empty,
|
||||
}
|
||||
|
||||
impl Body for ResponseBody {
|
||||
type Data = Bytes;
|
||||
type Error = Infallible;
|
||||
fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
|
||||
match &mut *self.get_mut() {
|
||||
Self::Full(incoming) => {
|
||||
Pin::new(incoming).poll_frame(cx)
|
||||
},
|
||||
Self::Empty => {
|
||||
Poll::Ready(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Player {
|
||||
id: i64,
|
||||
@@ -66,15 +92,16 @@ struct Settings {
|
||||
database_url: String,
|
||||
bind_address: String,
|
||||
}
|
||||
async fn service(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
|
||||
async fn service(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
match req.method() {
|
||||
&Method::GET => { get(req, db).await }
|
||||
&Method::POST => { post(req, db).await }
|
||||
_ => { Ok(Response::builder().status(StatusCode::IM_A_TEAPOT).body(Full::new(Bytes::new())).unwrap()) }
|
||||
_ => { Ok(Response::builder().status(StatusCode::IM_A_TEAPOT).body(ResponseBody::Empty).unwrap()) }
|
||||
}
|
||||
}
|
||||
|
||||
async fn get(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn get(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
let path = req.uri().path();
|
||||
if path.starts_with("/static") {
|
||||
get_file(path).await
|
||||
@@ -87,7 +114,7 @@ async fn get(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Respo
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_page(req: &Request<Incoming>, path: &str, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn get_page(req: &Request<Incoming>, path: &str, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
let mut routes = env::current_dir().expect("Could not get app directory (Required to get routes)");
|
||||
routes.push("routes.json");
|
||||
let file = File::open(routes).expect("Could not open routes file.");
|
||||
@@ -105,7 +132,7 @@ async fn get_page(req: &Request<Incoming>, path: &str, db: Arc<Mutex<SqlitePool>
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_file(mut path: &str) -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn get_file(mut path: &str) -> Result<Response<ResponseBody>, Error> {
|
||||
let mut file_path = env::current_dir().expect("Could not get app directory.");
|
||||
if path.starts_with(r"/") {
|
||||
path = path.strip_prefix(r"/").unwrap();
|
||||
@@ -122,23 +149,23 @@ async fn get_file(mut path: &str) -> Result<Response<Full<Bytes>>, Error> {
|
||||
"css" => "text/css",
|
||||
_ => ""
|
||||
};
|
||||
Ok(Response::builder().header("content-type", content_type).body(Full::new(Bytes::from(buf))).unwrap())
|
||||
Ok(Response::builder().header("content-type", content_type).body(ResponseBody::Full(Full::new(Bytes::from(buf)))).unwrap())
|
||||
}
|
||||
Err(_) => not_found().await
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_data(path: &str, req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn get_data(path: &str, req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
let pool = db.clone().lock().unwrap().clone();
|
||||
match path {
|
||||
"/data/players" => {
|
||||
let items = sqlx::query!(r#"SELECT * FROM players"#).fetch_all(&pool).await.unwrap();
|
||||
let players: Vec<Player> = items.iter().map(|x| Player { id: x.id, name: x.name.clone() }).collect();
|
||||
Ok(Response::new(Full::new(Bytes::from(serde_json::to_string(&players).unwrap()))))
|
||||
Ok(Response::new(ResponseBody::Full(Full::new(Bytes::from(serde_json::to_string(&players).unwrap())))))
|
||||
}
|
||||
"/data/votes" => {
|
||||
let votes = get_votes(req, db).await;
|
||||
Ok(Response::new(Full::new(Bytes::from(serde_json::to_string(&votes).unwrap()))))
|
||||
Ok(Response::new(ResponseBody::Full(Full::new(Bytes::from(serde_json::to_string(&votes).unwrap())))))
|
||||
}
|
||||
"/data/results" => {
|
||||
let votes = get_votes(req, db).await;
|
||||
@@ -169,7 +196,7 @@ async fn get_data(path: &str, req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>
|
||||
|
||||
let sorted_results = vec![plus_results, minus_results];
|
||||
|
||||
Ok(Response::new(Full::new(Bytes::from(serde_json::to_string(&sorted_results).unwrap()))))
|
||||
Ok(Response::new(ResponseBody::Full(Full::new(Bytes::from(serde_json::to_string(&sorted_results).unwrap())))))
|
||||
}
|
||||
_ => not_found().await
|
||||
}
|
||||
@@ -205,7 +232,7 @@ async fn get_votes(req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Vec<V
|
||||
}).collect()
|
||||
}
|
||||
|
||||
async fn get_admin(req: &Request<Incoming>, path: &str, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn get_admin(req: &Request<Incoming>, path: &str, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
let perm = is_authorised(req, db.clone()).await;
|
||||
if perm < 3 {
|
||||
return not_found().await;
|
||||
@@ -218,13 +245,16 @@ async fn get_admin(req: &Request<Incoming>, path: &str, db: Arc<Mutex<SqlitePool
|
||||
let users = sqlx::query!(r#"SELECT username, permissions FROM users"#).fetch_all(&pool).await.unwrap();
|
||||
let users: Vec<(String, i64)> = users.iter().map(|x| (x.username.clone(), x.permissions)).collect();
|
||||
let stringed = serde_json::to_string(&users).unwrap_or("".to_string());
|
||||
return Ok(Response::builder().body(Full::new(Bytes::from(stringed))).unwrap());
|
||||
return Ok(Response::builder().body(ResponseBody::Full(Full::new(Bytes::from(stringed)))).unwrap());
|
||||
}
|
||||
not_found().await
|
||||
}
|
||||
|
||||
async fn post(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn post(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
let path = req.uri().path();
|
||||
if path.starts_with("/admin") {
|
||||
return post_admin(req, db).await;
|
||||
}
|
||||
match path {
|
||||
"/vote" => {
|
||||
post_vote(req, db).await
|
||||
@@ -244,11 +274,11 @@ async fn post(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Resp
|
||||
}
|
||||
}
|
||||
|
||||
async fn post_vote(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn post_vote(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
let body = req.into_body().collect().await?;
|
||||
let data: Result<Vote, serde_json::Error> = from_reader(body.aggregate().reader());
|
||||
if data.is_err() {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap());
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::Empty).unwrap());
|
||||
}
|
||||
let vote = data.unwrap();
|
||||
let timestamp: DateTime<Utc> = DateTime::from(SystemTime::now());
|
||||
@@ -265,20 +295,37 @@ async fn post_vote(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result
|
||||
vote.minus_reason,
|
||||
formatted).execute(&mut *conn).await;
|
||||
if result.is_err() {
|
||||
return Ok(Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(Full::new(Bytes::from("Internet Error"))).unwrap());
|
||||
return Ok(Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(ResponseBody::Empty).unwrap());
|
||||
}
|
||||
Ok(Response::builder().body(Full::new(Bytes::new())).unwrap())
|
||||
Ok(Response::builder().body(ResponseBody::Full(Full::new(Bytes::new()))).unwrap())
|
||||
}
|
||||
|
||||
async fn login(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn post_admin(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
let perm = is_authorised(&req, db.clone()).await;
|
||||
if perm < 3 {
|
||||
return get_page(&req, "/unauthorised", db).await;
|
||||
}
|
||||
let path = req.uri().path();
|
||||
match path {
|
||||
"/admin/post/user" => {
|
||||
req_json::<User>(req).await;
|
||||
},
|
||||
"/admin/post/vote" => {},
|
||||
"/admin/post/player" => {},
|
||||
_ => {}
|
||||
}
|
||||
not_found().await
|
||||
}
|
||||
|
||||
async fn login(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
let body = req.into_body().collect().await;
|
||||
let data: Result<Login, serde_json::Error> = from_reader(body?.aggregate().reader());
|
||||
if data.is_err() {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap());
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::Empty).unwrap());
|
||||
}
|
||||
let data = data.unwrap();
|
||||
if !check_username(&data.username) {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap());
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::Full(Full::new(Bytes::from("Bad Request")))).unwrap());
|
||||
}
|
||||
let pool = db.clone().lock().unwrap().clone();
|
||||
let result = sqlx::query!(r#"SELECT * FROM users WHERE username=?1"#, data.username).fetch_optional(&pool).await;
|
||||
@@ -295,58 +342,57 @@ async fn login(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Res
|
||||
.header(SET_COOKIE,
|
||||
format!("token={}; Expires={}; Secure; HttpOnly; SameSite=Strict", user.token, date.to_rfc2822()))
|
||||
.header(SET_COOKIE, format!("logged=true; Expires={}; Secure; SameSite=Strict", date.to_rfc2822()))
|
||||
.body(Full::new(Bytes::from("Ok")))
|
||||
.body(ResponseBody::Full(Full::new(Bytes::from("Ok"))))
|
||||
.unwrap())
|
||||
}
|
||||
Err(_) => {
|
||||
Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap())
|
||||
Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::Empty).unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap())
|
||||
Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::Empty).unwrap())
|
||||
}
|
||||
Err(_) => { Ok(Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(Full::new(Bytes::from("Server Error"))).unwrap()) }
|
||||
Err(_) => { Ok(Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(ResponseBody::Empty).unwrap()) }
|
||||
}
|
||||
}
|
||||
|
||||
async fn register(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
let body = req.into_body().collect().await;
|
||||
let data: Result<Login, serde_json::Error> = from_reader(body?.aggregate().reader());
|
||||
if data.is_err() {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap());
|
||||
async fn register(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<ResponseBody>, Error> {
|
||||
match req_json::<Login>(req).await {
|
||||
None => Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::Empty).unwrap()),
|
||||
Some(login) => {
|
||||
if !check_username(&login.username) {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::Empty).unwrap());
|
||||
}
|
||||
let data = data.unwrap();
|
||||
if !check_username(&data.username) {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap());
|
||||
}
|
||||
if !check_password(&data.password) {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap());
|
||||
if !check_password(&login.password) {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::Empty).unwrap());
|
||||
}
|
||||
let pool = db.clone().lock().unwrap().clone();
|
||||
let mut conn = pool.acquire().await.unwrap();
|
||||
let exists = sqlx::query!(r#"SELECT id FROM users WHERE username=?1"#, data.username).fetch_optional(&mut *conn).await;
|
||||
let exists = sqlx::query!(r#"SELECT id FROM users WHERE username=?1"#, login.username).fetch_optional(&mut *conn).await;
|
||||
if exists.unwrap().is_some() {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap());
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::Empty).unwrap());
|
||||
}
|
||||
let argon2 = Argon2::default();
|
||||
let hash = argon2.hash_password(data.password.as_bytes(), &SaltString::generate(&mut OsRng)).unwrap().to_string();
|
||||
let hash = argon2.hash_password(login.password.as_bytes(), &SaltString::generate(&mut OsRng)).unwrap().to_string();
|
||||
let token = Alphanumeric.sample_string(&mut OsRng, 256);
|
||||
let result = sqlx::query!(r#"INSERT INTO users ( username, saltyhash, permissions, token) VALUES ( ?1, ?2, ?3, ?4 )"#, data.username, hash, 0, token).execute(&mut *conn).await;
|
||||
let result = sqlx::query!(r#"INSERT INTO users ( username, saltyhash, permissions, token) VALUES ( ?1, ?2, ?3, ?4 )"#, login.username, hash, 0, token).execute(&mut *conn).await;
|
||||
match result {
|
||||
Ok(_) => Ok(Response::builder().body(Full::new(Bytes::from(""))).unwrap()),
|
||||
Err(_) => { Ok(Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(Full::new(Bytes::from("Server Error"))).unwrap()) }
|
||||
Ok(_) => Ok(Response::builder().body(ResponseBody::Full(Full::new(Bytes::new()))).unwrap()),
|
||||
Err(_) => { Ok(Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(ResponseBody::Empty).unwrap()) }
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn logout() -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn logout() -> Result<Response<ResponseBody>, Error> {
|
||||
let date: DateTime<Utc> = DateTime::from(SystemTime::now());
|
||||
Ok(Response::builder()
|
||||
//.status(StatusCode::SEE_OTHER)
|
||||
//.header(LOCATION, "/")
|
||||
.header(SET_COOKIE, format!("token=''; Expires={}; Secure; HttpOnly; SameSite=Strict", date.to_rfc2822()))
|
||||
.header(SET_COOKIE, format!("logged=false; Expires={}; Secure; HttpOnly; SameSite=Strict", date.to_rfc2822()))
|
||||
.body(Full::new(Bytes::from(""))).unwrap())
|
||||
.body(ResponseBody::Empty).unwrap())
|
||||
}
|
||||
|
||||
async fn is_authorised(req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> i64 {
|
||||
@@ -366,13 +412,8 @@ async fn is_authorised(req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> i
|
||||
let pool = db.clone().lock().unwrap().clone();
|
||||
let user = sqlx::query!(r#"SELECT permissions FROM users WHERE token=?1"#, token).fetch_optional(&pool).await;
|
||||
match user {
|
||||
Ok(user) => {
|
||||
match user {
|
||||
Some(user) => user.permissions,
|
||||
None => 0
|
||||
}
|
||||
},
|
||||
Err(_) => 0
|
||||
Ok(Some(user)) => user.permissions,
|
||||
_ => 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -410,13 +451,24 @@ fn check_password(password: &String) -> bool {
|
||||
up && num && sym
|
||||
}
|
||||
|
||||
async fn not_found() -> Result<Response<Full<Bytes>>, Error> {
|
||||
async fn not_found() -> Result<Response<ResponseBody>, Error> {
|
||||
let mut file_path = env::current_dir().expect("Could not get app directory.");
|
||||
file_path.push("static/html/404.html");
|
||||
let mut file = File::open(file_path).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
file.read_to_end(&mut buf).unwrap();
|
||||
Ok(Response::builder().status(StatusCode::NOT_FOUND).body(Full::new(Bytes::from(buf))).unwrap())
|
||||
Ok(Response::builder().status(StatusCode::NOT_FOUND).body(ResponseBody::Full(Full::new(Bytes::from(buf)))).unwrap())
|
||||
}
|
||||
|
||||
async fn req_json<T>(req: Request<Incoming>) -> Option<T>
|
||||
where
|
||||
T: DeserializeOwned
|
||||
{
|
||||
let body = req.into_body().collect().await.unwrap();
|
||||
match from_reader(body.aggregate().reader()) {
|
||||
Ok(val) => Some(val),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_settings() -> Settings {
|
||||
|
||||
@@ -4,12 +4,14 @@ async function run() {
|
||||
let usersDiv = document.getElementById("users");
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
let item = document.createElement("div");
|
||||
let username = document.createElement("p");
|
||||
let permissions = document.createElement("p");
|
||||
username.textContent = users[i][0];
|
||||
permissions.textContent = users[i][1];
|
||||
let username = document.createElement("input");
|
||||
let permissions = document.createElement("input");
|
||||
let edit = document.createElement("button");
|
||||
edit.textContent = "Edit";
|
||||
username.value = users[i][0];
|
||||
permissions.value = users[i][1];
|
||||
item.style.display = "flex";
|
||||
item.append(username, permissions);
|
||||
item.append(username, permissions, edit);
|
||||
usersDiv.appendChild(item);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user