Merge of dev-auth #1
17
routes.json
17
routes.json
@@ -1,8 +1,11 @@
|
|||||||
{
|
{
|
||||||
"/": "static/html/index.html",
|
"/": {"file": "static/html/index.html", "permission": 0},
|
||||||
"/results": "static/html/results.html",
|
"/results": {"file": "static/html/results.html", "permission": 1},
|
||||||
"/archives": "static/html/archives.html",
|
"/archives": {"file": "static/html/archives.html", "permission": 2},
|
||||||
"/favicon.ico": "static/img/favicon.ico",
|
"/favicon.ico": {"file": "static/img/favicon.ico", "permission": 0},
|
||||||
"/login": "static/html/login.html",
|
"/login": {"file": "static/html/login.html", "permission": 0},
|
||||||
"/register": "static/html/register.html"
|
"/register": {"file": "static/html/register.html", "permission": 0},
|
||||||
}
|
"/logout": {"file": "static/html/logout.html", "permission": 0},
|
||||||
|
"/unauthorised": {"file": "static/html/unauthorised.html", "permission": 0},
|
||||||
|
"/admin" : {"file": "static/html/admin.html", "permission": 3}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
{
|
{
|
||||||
"database_url": "sqlite:vote.db",
|
"database_url": "sqlite:vote.db",
|
||||||
"bind_address": "127.0.0.1:8080"
|
"bind_address": "127.0.0.1:8000"
|
||||||
}
|
}
|
||||||
|
|||||||
86
src/main.rs
86
src/main.rs
@@ -13,7 +13,7 @@ use daemonize::Daemonize;
|
|||||||
use futures;
|
use futures;
|
||||||
use http_body_util::{BodyExt, Full};
|
use http_body_util::{BodyExt, Full};
|
||||||
use hyper::body::{Body, Incoming};
|
use hyper::body::{Body, Incoming};
|
||||||
use hyper::header::{LOCATION, SET_COOKIE};
|
use hyper::header::{LOCATION, SET_COOKIE, COOKIE};
|
||||||
use hyper::server::conn::http1;
|
use hyper::server::conn::http1;
|
||||||
use hyper::service::service_fn;
|
use hyper::service::service_fn;
|
||||||
use hyper::{Error, Method, Request, Response, StatusCode};
|
use hyper::{Error, Method, Request, Response, StatusCode};
|
||||||
@@ -30,6 +30,7 @@ use std::net::SocketAddr;
|
|||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
|
use hyper::http::HeaderValue;
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
struct Player {
|
struct Player {
|
||||||
@@ -79,20 +80,27 @@ async fn get(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Respo
|
|||||||
get_file(path).await
|
get_file(path).await
|
||||||
} else if path.starts_with("/data") {
|
} else if path.starts_with("/data") {
|
||||||
get_data(path, &req, db).await
|
get_data(path, &req, db).await
|
||||||
} else if path.starts_with("/logout") {
|
} else if path.starts_with("/admin") {
|
||||||
logout().await
|
get_admin(&req, path, db).await
|
||||||
} else {
|
} else {
|
||||||
get_page(path).await
|
get_page(&req, path, db).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_page(path: &str) -> Result<Response<Full<Bytes>>, Error> {
|
async fn get_page(req: &Request<Incoming>, path: &str, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||||
let mut routes = env::current_dir().expect("Could not get app directory (Required to get routes)");
|
let mut routes = env::current_dir().expect("Could not get app directory (Required to get routes)");
|
||||||
routes.push("routes.json");
|
routes.push("routes.json");
|
||||||
let file = File::open(routes).expect("Could not open routes file.");
|
let file = File::open(routes).expect("Could not open routes file.");
|
||||||
let map: Value = from_reader(file).expect("Could not parse routes, please verify syntax.");
|
let map: Value = from_reader(file).expect("Could not parse routes, please verify syntax.");
|
||||||
match &map[path] {
|
match map.get(path) {
|
||||||
Value::String(s) => get_file(&s).await,
|
Some(Value::Object(s)) => {
|
||||||
|
let perm = is_authorised(req, db).await;
|
||||||
|
if s.get("permission").unwrap().as_i64().unwrap() <= perm {
|
||||||
|
get_file(s.get("file").unwrap().as_str().unwrap()).await
|
||||||
|
} else {
|
||||||
|
get_file(map.get("/unauthorised").unwrap().get("file").unwrap().as_str().unwrap()).await
|
||||||
|
}
|
||||||
|
},
|
||||||
_ => not_found().await
|
_ => not_found().await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -185,10 +193,8 @@ async fn get_votes(req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Vec<V
|
|||||||
if date.is_none() {
|
if date.is_none() {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
let items = futures::executor::block_on(async move {
|
let formatted_date = format!("{}", date.unwrap().format("%d/%m/%Y"));
|
||||||
let formatted_date = format!("{}", date.unwrap().format("%d/%m/%Y"));
|
let items = sqlx::query!(r#"SELECT * FROM votes WHERE submit_date = ?1 ORDER BY id"#, formatted_date).fetch_all(&pool).await.unwrap();
|
||||||
sqlx::query!(r#"SELECT * FROM votes WHERE submit_date = ?1 ORDER BY id"#, formatted_date).fetch_all(&pool).await.unwrap()
|
|
||||||
});
|
|
||||||
items.iter().map(|x| Vote {
|
items.iter().map(|x| Vote {
|
||||||
plus_player_id: x.plus_player_id,
|
plus_player_id: x.plus_player_id,
|
||||||
plus_nickname: x.plus_nickname.clone(),
|
plus_nickname: x.plus_nickname.clone(),
|
||||||
@@ -199,6 +205,24 @@ async fn get_votes(req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Vec<V
|
|||||||
}).collect()
|
}).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn get_admin(req: &Request<Incoming>, path: &str, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||||
|
let perm = is_authorised(req, db.clone()).await;
|
||||||
|
if perm < 3 {
|
||||||
|
return not_found().await;
|
||||||
|
}
|
||||||
|
if path == "/admin" {
|
||||||
|
return get_page(req, path, db).await;
|
||||||
|
}
|
||||||
|
if path == "/admin/users" {
|
||||||
|
let pool = db.clone().lock().unwrap().clone();
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
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<Full<Bytes>>, Error> {
|
||||||
let path = req.uri().path();
|
let path = req.uri().path();
|
||||||
match path {
|
match path {
|
||||||
@@ -211,6 +235,9 @@ async fn post(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Resp
|
|||||||
"/register" => {
|
"/register" => {
|
||||||
register(req, db).await
|
register(req, db).await
|
||||||
}
|
}
|
||||||
|
"/logout" => {
|
||||||
|
logout().await
|
||||||
|
}
|
||||||
_ => {
|
_ => {
|
||||||
not_found().await
|
not_found().await
|
||||||
}
|
}
|
||||||
@@ -254,8 +281,7 @@ async fn login(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Res
|
|||||||
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(Full::new(Bytes::from("Bad Request"))).unwrap());
|
||||||
}
|
}
|
||||||
let pool = db.clone().lock().unwrap().clone();
|
let pool = db.clone().lock().unwrap().clone();
|
||||||
let mut conn = pool.acquire().await.unwrap();
|
let result = sqlx::query!(r#"SELECT * FROM users WHERE username=?1"#, data.username).fetch_optional(&pool).await;
|
||||||
let result = sqlx::query!(r#"SELECT * FROM users WHERE username=?1"#, data.username).fetch_optional(&mut *conn).await;
|
|
||||||
match result {
|
match result {
|
||||||
Ok(Some(user)) => {
|
Ok(Some(user)) => {
|
||||||
let argon = Argon2::default();
|
let argon = Argon2::default();
|
||||||
@@ -268,6 +294,7 @@ async fn login(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Res
|
|||||||
Ok(Response::builder()
|
Ok(Response::builder()
|
||||||
.header(SET_COOKIE,
|
.header(SET_COOKIE,
|
||||||
format!("token={}; Expires={}; Secure; HttpOnly; SameSite=Strict", user.token, date.to_rfc2822()))
|
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(Full::new(Bytes::from("Ok")))
|
||||||
.unwrap())
|
.unwrap())
|
||||||
}
|
}
|
||||||
@@ -305,7 +332,6 @@ async fn register(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<
|
|||||||
let argon2 = Argon2::default();
|
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(data.password.as_bytes(), &SaltString::generate(&mut OsRng)).unwrap().to_string();
|
||||||
let token = Alphanumeric.sample_string(&mut OsRng, 256);
|
let token = Alphanumeric.sample_string(&mut OsRng, 256);
|
||||||
println!("{}", token);
|
|
||||||
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 )"#, data.username, hash, 0, token).execute(&mut *conn).await;
|
||||||
match result {
|
match result {
|
||||||
Ok(_) => Ok(Response::builder().body(Full::new(Bytes::from(""))).unwrap()),
|
Ok(_) => Ok(Response::builder().body(Full::new(Bytes::from(""))).unwrap()),
|
||||||
@@ -316,12 +342,40 @@ async fn register(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<
|
|||||||
async fn logout() -> Result<Response<Full<Bytes>>, Error> {
|
async fn logout() -> Result<Response<Full<Bytes>>, Error> {
|
||||||
let date: DateTime<Utc> = DateTime::from(SystemTime::now());
|
let date: DateTime<Utc> = DateTime::from(SystemTime::now());
|
||||||
Ok(Response::builder()
|
Ok(Response::builder()
|
||||||
.status(StatusCode::SEE_OTHER)
|
//.status(StatusCode::SEE_OTHER)
|
||||||
.header(LOCATION, "/")
|
//.header(LOCATION, "/")
|
||||||
.header(SET_COOKIE, format!("token=''; Expires={}; Secure; HttpOnly; SameSite=Strict", date.to_rfc2822()))
|
.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(Full::new(Bytes::from(""))).unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn is_authorised(req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> i64 {
|
||||||
|
let cookies = req.headers().get(COOKIE);
|
||||||
|
let token = match cookies {
|
||||||
|
Some(cookies) => {
|
||||||
|
cookies
|
||||||
|
.to_str()
|
||||||
|
.unwrap_or("")
|
||||||
|
.split("; ")
|
||||||
|
.find(|x| x.starts_with("token="))
|
||||||
|
.unwrap_or("")
|
||||||
|
.strip_prefix("token=")
|
||||||
|
.unwrap_or("")},
|
||||||
|
None => ""
|
||||||
|
};
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn check_username(username: &String) -> bool {
|
fn check_username(username: &String) -> bool {
|
||||||
if username.len() > 21 {
|
if username.len() > 21 {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
Reference in New Issue
Block a user