Remove deprecated functions

pull/5/head
~erin 2021-07-23 09:48:57 -04:00
parent 78cae7a5ac
commit a01cb8b489
Signed by: erin
GPG Key ID: DA70E064A8C70F44
6 changed files with 6 additions and 202 deletions

1
.gitignore vendored
View File

@ -2,4 +2,5 @@
.vscode
users.json
message.zsh
TODO.md
users_db/

2
Cargo.lock generated
View File

@ -807,7 +807,7 @@ checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"
[[package]]
name = "pogchat"
version = "0.5.1"
version = "0.5.2"
dependencies = [
"bincode",
"chrono",

View File

@ -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

View File

@ -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/<name>/<pin>/<pronouns>` Register the username with the pin provided if it doesn't already exist
`GET /api/users/<name>` Check if the user exists
`GET /api/users/<name>/<pin>` Check if the user exists, and if the pin provided matches
`POST /api/users/change/<name>/<pin>/<new-name>/<new-pin>` Change a users name and/or pin
`GET /api/about/name/<name>` Get the name of a user
`GET /api/about/pronouns/<name>` Get the pronouns of a user"
}
// Post request to register a user and pin
#[post("/register/<name>/<pin>/<pronouns>")]
pub fn register_user(name: String, pin: i32, pronouns: String) -> JsonValue {
@ -167,7 +150,7 @@ pub fn logout(info: Json<LogoutEvent>, mut cookies: Cookies) -> JsonValue {
// Check if pin matches user
#[get("/users/<name>/<pin>")]
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<ChangeEvent>, mut cookies: Cookies) -> JsonValue
});
}
// Change a users pin/name
#[post("/users/change/<name>/<pin>/<new_name>/<new_pin>")]
pub fn change(name: String, pin: i32, new_name: String, new_pin: i32) -> JsonValue {
let mut users: Vec<User> = 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/<name>")]
pub fn get_user(name: String) -> JsonValue {
let users: Vec<User> = db_read();

View File

@ -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<dyn std::error::Error>;
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
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<User> {
// Create path to file
let path = Path::new("users.json");
let display = path.display();
let mut users: Vec<User> = 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<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).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();

View File

@ -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,