Use database for storing users

pull/5/head
~erin 2021-07-22 11:01:07 -04:00
parent 588c37af08
commit 6f18959e9c
Signed by: erin
GPG Key ID: DA70E064A8C70F44
5 changed files with 83 additions and 22 deletions

10
Cargo.lock generated
View File

@ -98,6 +98,15 @@ version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
[[package]]
name = "bincode"
version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "1.2.1" version = "1.2.1"
@ -800,6 +809,7 @@ checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"
name = "pogchat" name = "pogchat"
version = "0.4.0" version = "0.4.0"
dependencies = [ dependencies = [
"bincode",
"chrono", "chrono",
"env_logger", "env_logger",
"log 0.4.14", "log 0.4.14",

View File

@ -19,3 +19,4 @@ rocket_contrib = { version = "0.4.10", default-features = false, features = ["js
once_cell = "1.8.0" once_cell = "1.8.0"
random-string = "1.0" random-string = "1.0"
sled = "0.34.6" sled = "0.34.6"
bincode = "1.3.3"

View File

@ -1,5 +1,5 @@
extern crate log; extern crate log;
use crate::file_io::{append_json, read_json, write_json}; use crate::file_io::{db_add, db_write, db_read};
use rocket::http::{Cookie, Cookies}; use rocket::http::{Cookie, Cookies};
use crate::user::User; use crate::user::User;
use rocket_contrib::json::{Json, JsonValue}; use rocket_contrib::json::{Json, JsonValue};
@ -27,7 +27,7 @@ pub fn index() -> &'static str {
// Post request to register a user and pin // Post request to register a user and pin
#[post("/register/<name>/<pin>/<pronouns>")] #[post("/register/<name>/<pin>/<pronouns>")]
pub fn register_user(name: String, pin: i32, pronouns: String) -> JsonValue { pub fn register_user(name: String, pin: i32, pronouns: String) -> JsonValue {
let mut users: Vec<User> = read_json(); // Create an array of users out of parsed json let mut users: Vec<User> = db_read(); // Create an array of users out of parsed json
for i in &users { for i in &users {
// loop through elements of the vector // loop through elements of the vector
if i.name == name.to_lowercase() { if i.name == name.to_lowercase() {
@ -48,16 +48,18 @@ pub fn register_user(name: String, pin: i32, pronouns: String) -> JsonValue {
session_token: "NULL".to_string(), session_token: "NULL".to_string(),
}; // append the user to the vec }; // append the user to the vec
/*
// append to the json file // append to the json file
match append_json(&new_user) { match append_json(&new_user) {
Err(why) => panic!("couldn't append json: {}", why), Err(why) => panic!("couldn't append json: {}", why),
Ok(()) => info!("Succesfully appended to json"), Ok(()) => info!("Succesfully appended to json"),
}; };*/
db_add(&new_user);
info!( info!(
"succesfully created user {} with pin hash {}", "succesfully created user {} with pin hash {}",
users[users.len() - 1].name.to_string(), new_user.name.to_string(),
users[users.len() - 1].pin_hashed new_user.pin_hashed
); );
return json!({ return json!({
"status": "ok", "status": "ok",
@ -71,10 +73,12 @@ fn create_token(name: String, mut users: Vec<User>) -> String {
for i in 0..users.len() { for i in 0..users.len() {
if users[i].name == name { if users[i].name == name {
users[i].session_token = generate(12, charset); users[i].session_token = generate(12, charset);
/*
match write_json(&users) { match write_json(&users) {
Err(why) => panic!("coudln't write to file: {}", why), Err(why) => panic!("coudln't write to file: {}", why),
Ok(()) => info!("succesfully wrote to file"), Ok(()) => info!("succesfully wrote to file"),
}; };*/
db_write(&users);
info!("succesfully created token for user {}", name); info!("succesfully created token for user {}", name);
let token = users[i].session_token.clone(); let token = users[i].session_token.clone();
return token; return token;
@ -87,7 +91,7 @@ fn create_token(name: String, mut users: Vec<User>) -> String {
// Check if pin matches user // Check if pin matches user
#[get("/users/<name>/<pin>")] #[get("/users/<name>/<pin>")]
pub fn check_pin(mut cookies: Cookies, name: String, pin: i32) -> JsonValue { pub fn check_pin(mut cookies: Cookies, name: String, pin: i32) -> JsonValue {
let users: Vec<User> = read_json(); let users: Vec<User> = db_read();
let hashed_pin_input = sha1::Sha1::from(&pin.to_string()).digest().to_string(); let hashed_pin_input = sha1::Sha1::from(&pin.to_string()).digest().to_string();
for i in &users { for i in &users {
// loop through the vector // loop through the vector
@ -136,7 +140,7 @@ pub struct Event {
pub fn change_info(input: Json<Event>) -> JsonValue { pub fn change_info(input: Json<Event>) -> JsonValue {
println!("{:?}", input); println!("{:?}", input);
// read in the users & hash the pin // read in the users & hash the pin
let mut users: Vec<User> = read_json(); let mut users: Vec<User> = db_read();
let hashed_pin = sha1::Sha1::from(&input.pin).digest().to_string(); let hashed_pin = sha1::Sha1::from(&input.pin).digest().to_string();
// loop through the users // loop through the users
@ -147,7 +151,7 @@ pub fn change_info(input: Json<Event>) -> JsonValue {
// change the name // change the name
users[i].name = input.new_event.clone(); users[i].name = input.new_event.clone();
info!("changed name of {} to {}", input.name, input.new_event); info!("changed name of {} to {}", input.name, input.new_event);
write_json(&users); db_write(&users);
return json!({ return json!({
"status": "ok", "status": "ok",
"reason": format!("changed name of {} to {}", input.name, input.new_event), "reason": format!("changed name of {} to {}", input.name, input.new_event),
@ -156,7 +160,7 @@ pub fn change_info(input: Json<Event>) -> JsonValue {
// change the pin // change the pin
let new_hashed_pin = sha1::Sha1::from(&input.new_event).digest().to_string(); let new_hashed_pin = sha1::Sha1::from(&input.new_event).digest().to_string();
users[i].pin_hashed = new_hashed_pin.clone(); users[i].pin_hashed = new_hashed_pin.clone();
write_json(&users); db_write(&users);
info!("changed pin of {}", input.name); info!("changed pin of {}", input.name);
return json!({ return json!({
"status": "ok", "status": "ok",
@ -166,7 +170,7 @@ pub fn change_info(input: Json<Event>) -> JsonValue {
// change the pronouns // change the pronouns
users[i].pronouns = input.new_event.clone(); users[i].pronouns = input.new_event.clone();
info!("changed pronouns of {} to {}", input.name, input.new_event); info!("changed pronouns of {} to {}", input.name, input.new_event);
write_json(&users); db_write(&users);
return json!({ return json!({
"status": "ok", "status": "ok",
"reason": "successfully changed pronouns", "reason": "successfully changed pronouns",
@ -191,7 +195,7 @@ pub fn change_info(input: Json<Event>) -> JsonValue {
// Change a users pin/name // Change a users pin/name
#[post("/users/change/<name>/<pin>/<new_name>/<new_pin>")] #[post("/users/change/<name>/<pin>/<new_name>/<new_pin>")]
pub fn change(name: String, pin: i32, new_name: String, new_pin: i32) -> JsonValue { pub fn change(name: String, pin: i32, new_name: String, new_pin: i32) -> JsonValue {
let mut users: Vec<User> = read_json(); let mut users: Vec<User> = db_read();
let hashed_pin_input = sha1::Sha1::from(&pin.to_string()).digest().to_string(); let hashed_pin_input = sha1::Sha1::from(&pin.to_string()).digest().to_string();
@ -205,10 +209,12 @@ pub fn change(name: String, pin: i32, new_name: String, new_pin: i32) -> JsonVal
if users[i].name == new_name.to_lowercase() { if users[i].name == new_name.to_lowercase() {
// check if new name already exists // check if new name already exists
users[i].pin_hashed = sha1::Sha1::from(&new_pin.to_string()).digest().to_string(); users[i].pin_hashed = sha1::Sha1::from(&new_pin.to_string()).digest().to_string();
/*
match write_json(&users) { match write_json(&users) {
Err(why) => panic!("Cannot write to json! {}", why), Err(why) => panic!("Cannot write to json! {}", why),
Ok(()) => info!("succesfully wrote to json file"), Ok(()) => info!("succesfully wrote to json file"),
} }*/
db_write(&users);
info!("Changed pin of {}", name.to_string().to_lowercase()); info!("Changed pin of {}", name.to_string().to_lowercase());
return json!({ return json!({
"status": "ok", "status": "ok",
@ -232,11 +238,12 @@ pub fn change(name: String, pin: i32, new_name: String, new_pin: i32) -> JsonVal
users[i].name = new_name.to_string().to_lowercase(); users[i].name = new_name.to_string().to_lowercase();
users[i].pin_hashed = users[i].pin_hashed =
sha1::Sha1::from(&new_pin.to_string()).digest().to_string(); sha1::Sha1::from(&new_pin.to_string()).digest().to_string();
/*
match write_json(&users) { match write_json(&users) {
Err(why) => panic!("couldn't write to json file! {}", why), Err(why) => panic!("couldn't write to json file! {}", why),
Ok(()) => info!("succesfully wrote to json file"), Ok(()) => info!("succesfully wrote to json file"),
} }*/
db_write(&users);
info!( info!(
"Changed name of {} to {}. New pin hash is {}", "Changed name of {} to {}. New pin hash is {}",
name.to_string(), name.to_string(),
@ -269,7 +276,7 @@ pub fn change(name: String, pin: i32, new_name: String, new_pin: i32) -> JsonVal
#[get("/users/<name>")] #[get("/users/<name>")]
pub fn get_user(name: String) -> JsonValue { pub fn get_user(name: String) -> JsonValue {
let users: Vec<User> = read_json(); let users: Vec<User> = db_read();
let found_user = users let found_user = users
.iter() .iter()
.filter(|u| u.name == name.to_lowercase()) .filter(|u| u.name == name.to_lowercase())

View File

@ -96,12 +96,56 @@ pub fn write_json(users_list: &Vec<User>) -> Result<()> {
}; };
Ok(()) Ok(())
} }
/*
// test sled funtion // test sled funtion
pub fn test_sled() { pub fn test_sled() {
// create test user
let user = User {
name: "erin".to_string(),
pin_hashed: "nyaa".to_string(),
pronouns: "she/her".to_string(),
session_token: "NULL".to_string(),
};
// open database
let db: sled::Db = sled::open("my_db").unwrap(); let db: sled::Db = sled::open("my_db").unwrap();
db.insert("key", "value"); let bytes = bincode::serialize(&user).unwrap();
let value = std::str::from_utf8(&db.get("key").unwrap().unwrap()).unwrap(); db.insert(&user.name, bytes).unwrap();
info!("database: {:?}", &value); match db.get(user.name).unwrap() {
Some(bytes) => {
let read_user: User = bincode::deserialize(&bytes).unwrap();
println!("username: {}, pronouns: {}", read_user.name, read_user.pronouns);
},
None => (),
}
}
}*/ // add a user to the database
pub fn db_add(user: &User) {
let db: sled::Db = sled::open("users_db").unwrap();
let bytes = bincode::serialize(&user).unwrap();
db.insert(&user.name, bytes).unwrap();
info!("succesfully appended user {} to database", &user.name);
}
// write all changed users to database
pub fn db_write(users_list: &Vec<User>) {
let db: sled::Db = sled::open("users_db").unwrap();
for i in users_list {
let bytes = bincode::serialize(&i).unwrap();
db.insert(&i.name, bytes).unwrap();
info!("wrote user {} to db", &i.name);
}
info!("wrote all users to db");
}
// read all users from the database
pub fn db_read() -> Vec<User> {
let db: sled::Db = sled::open("users_db").unwrap();
let mut users: Vec<User> = Vec::new();
for (_, bytes) in db.iter().filter_map(|r| r.ok()) {
let read_user: User = bincode::deserialize(&bytes).unwrap();
info!("read user {} from db", read_user.name);
users.push(read_user);
}
return users;
}

View File

@ -18,7 +18,6 @@ mod user;
fn main() { fn main() {
env_logger::init(); env_logger::init();
//file_io::test_sled();
info!("Started up rocket"); info!("Started up rocket");
let cors_fairing = AdHoc::on_response("CORS", |_, res| { let cors_fairing = AdHoc::on_response("CORS", |_, res| {
res.set_raw_header("Access-Control-Allow-Origin", "*"); res.set_raw_header("Access-Control-Allow-Origin", "*");