diff --git a/.gitignore b/.gitignore index 5a12ba4..753be59 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ .vscode users.json message.zsh +TODO.md users_db/ diff --git a/Cargo.lock b/Cargo.lock index 9aef55b..93fff42 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -807,7 +807,7 @@ checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" [[package]] name = "pogchat" -version = "0.5.1" +version = "0.5.2" dependencies = [ "bincode", "chrono", diff --git a/message.zsh b/message.zsh index 267cabb..915a2a2 100755 --- a/message.zsh +++ b/message.zsh @@ -1 +1 @@ -http POST 'http://localhost:8000/api/message/send' name=erin body="nyaa uwu" date="2021-07-21" +http POST 'http://localhost:8000/api/mod' name=erin action=Ban target=sarah diff --git a/src/auth.rs b/src/auth.rs index 4d49529..7baac90 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -1,5 +1,5 @@ extern crate log; -use crate::file_io::{db_add, db_write, db_read, db_read_user, db_remove}; +use crate::file_io::*; use rocket::http::{Cookie, Cookies}; use crate::user::*; use rocket_contrib::json::{Json, JsonValue}; @@ -7,23 +7,6 @@ use random_string::generate; extern crate sha1; use serde::Deserialize; -#[get("/")] -pub fn index() -> &'static str { - "API Info: - - `POST /api/register///` Register the username with the pin provided if it doesn't already exist - - `GET /api/users/` Check if the user exists - - `GET /api/users//` Check if the user exists, and if the pin provided matches - - `POST /api/users/change////` Change a users name and/or pin - - `GET /api/about/name/` Get the name of a user - - `GET /api/about/pronouns/` Get the pronouns of a user" -} - // Post request to register a user and pin #[post("/register///")] pub fn register_user(name: String, pin: i32, pronouns: String) -> JsonValue { @@ -167,7 +150,7 @@ pub fn logout(info: Json, mut cookies: Cookies) -> JsonValue { // Check if pin matches user #[get("/users//")] -pub fn check_pin(mut cookies: Cookies, name: String, pin: i32) -> JsonValue { +pub fn login(mut cookies: Cookies, name: String, pin: i32) -> JsonValue { if let Some(user) = db_read_user(&name.to_lowercase()).ok().flatten() { let hashed_pin_input = sha1::Sha1::from(&pin.to_string()).digest().to_string(); @@ -289,88 +272,6 @@ pub fn change_info(input: Json, mut cookies: Cookies) -> JsonValue }); } -// Change a users pin/name -#[post("/users/change////")] -pub fn change(name: String, pin: i32, new_name: String, new_pin: i32) -> JsonValue { - let mut users: Vec = db_read(); - - let hashed_pin_input = sha1::Sha1::from(&pin.to_string()).digest().to_string(); - - // Loop over elements in vector - for i in 0..users.len() { - if users[i].name == name.to_lowercase() { - // make sure name exists - if hashed_pin_input == users[i].pin_hashed { - // check if token is correct - // Check wether to change name or name+pin - if users[i].name == new_name.to_lowercase() { - // check if new name already exists - users[i].pin_hashed = sha1::Sha1::from(&new_pin.to_string()).digest().to_string(); - /* - match write_json(&users) { - Err(why) => panic!("Cannot write to json! {}", why), - Ok(()) => info!("succesfully wrote to json file"), - }*/ - db_write(&users); - info!("Changed pin of {}", name.to_string().to_lowercase()); - return json!({ - "status": "ok", - "reason": format!("changed {}'s pin", name.to_string().to_lowercase()), - }); - } else { - // check if new name already exists - for n in &users { - if n.name == new_name.to_lowercase() { - warn!( - "Could not change name of {} to {}, as new name is already taken.", - name.to_lowercase(), - new_name.to_lowercase() - ); - return json!({ - "status": "fail", - "reason": format!("new name {} is already taken", new_name.to_lowercase()), - }); - } - } - users[i].name = new_name.to_string().to_lowercase(); - users[i].pin_hashed = - sha1::Sha1::from(&new_pin.to_string()).digest().to_string(); - /* - match write_json(&users) { - Err(why) => panic!("couldn't write to json file! {}", why), - Ok(()) => info!("succesfully wrote to json file"), - }*/ - db_write(&users); - info!( - "Changed name of {} to {}. New pin hash is {}", - name.to_string(), - users[i].name.to_string(), - users[i].pin_hashed.to_string() - ); - return json!({ - "status": "ok", - "reason": "successfully changed name and/or pin", - }); - } - } else { - warn!("Incorrect token for user {}!", name.to_string()); - return json!({ - "status": "fail", - "reason": "incorrect token for user", - }); - } - } - } - warn!( - "User {} not found, could not change pin and/or name.", - name.to_string() - ); - return json!({ - "status": "fail", - "reason": format!("user {} not found", name.to_string().to_lowercase()), - }); -} - #[get("/users/")] pub fn get_user(name: String) -> JsonValue { let users: Vec = db_read(); diff --git a/src/file_io.rs b/src/file_io.rs index 14f997e..8a740c2 100644 --- a/src/file_io.rs +++ b/src/file_io.rs @@ -1,104 +1,8 @@ -use std::fs::{File, OpenOptions}; -use std::io::prelude::*; -use std::io::{self, BufRead}; -use std::path::Path; extern crate log; use crate::user::User; -use serde_json::Result; type MyErrorType = Box; -fn read_lines

(filename: P) -> io::Result>> -where - P: AsRef, -{ - let file = File::open(filename)?; - Ok(io::BufReader::new(file).lines()) -} - -// Function to read json from file into the vector -pub fn read_json() -> Vec { - // Create path to file - let path = Path::new("users.json"); - let display = path.display(); - - let mut users: Vec = Vec::new(); // Create an empty vector of users - - // Read through the lines and append them to the array - if let Ok(lines) = read_lines(&path) { - for line in lines { - if let Ok(user) = line { - info!("read {} from json file {}", display, &user); - // Parse line from file into a data structure - let user: User = serde_json::from_str(&user).unwrap(); - users.push(user); - } - } - } - return users; -} - -// Function to append the last value of the users vector to the file -pub fn append_json(user: &User) -> Result<()> { - // Create a file to write to - let path = Path::new("users.json"); - let display = path.display(); - - let mut file = match OpenOptions::new() - .write(true) - .create(true) - .append(true) - .open(&path) - { - Err(why) => panic!("couldn't create {}: {}", display, why), - Ok(file) => file, - }; - - // Serialize the last user value - let user_json = serde_json::to_string(&user)?; - - // Write to the file - match file.write_all(user_json.as_bytes()) { - Err(why) => panic!("couldn't write to {}: {}", display, why), - Ok(_) => info!("succesfully wrote to {}", display), - }; - // Add newline - match file.write_all("\n".as_bytes()) { - Err(why) => panic!("couldn't write to {}: {}", display, why), - Ok(_) => info!("succesfully wrote newline to {}", display), - }; - Ok(()) -} - -// Function to write whole vector of users to file -pub fn write_json(users_list: &Vec) -> Result<()> { - // Create a file to write to - let path = Path::new("users.json"); - let display = path.display(); - - let mut file = match OpenOptions::new().write(true).create(true).open(&path) { - Err(why) => panic!("couldn't create {}: {}", display, why), - Ok(file) => file, - }; - - let mut users_json = String::new(); - for i in 0..users_list.len() { - // Serialize the users - users_json += &serde_json::to_string(&users_list[i])?; - if i != users_list.len()-1 { - // don't append newline if it's the last element - users_json += "\n"; - } - } - - // Write to the file - match file.write_all(users_json.as_bytes()) { - Err(why) => panic!("couldn't write to {}: {}", display, why), - Ok(_) => info!("succesfully wrote to {}", display), - }; - Ok(()) -} - // add a user to the database pub fn db_add(user: &User) { let db: sled::Db = sled::open("users_db").unwrap(); diff --git a/src/main.rs b/src/main.rs index dd729d8..ca9d12a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,11 +28,9 @@ fn main() { .mount( "/api", routes![ - auth::index, auth::get_user, auth::register_user, - auth::check_pin, - auth::change, + auth::login, chat::send_message, chat::fetch_messages, auth::change_info,