Add error handling to database functions, use db_read_user()

pull/5/head
~erin 2021-07-23 09:42:33 -04:00
parent 786a4100f2
commit 78cae7a5ac
Signed by: erin
GPG Key ID: DA70E064A8C70F44
4 changed files with 228 additions and 234 deletions

View File

@ -1,3 +1,8 @@
### 0.5.2
- When changing a username, it now deletes the previous user instead of creating a new one
- Database functions should now use some error handling
- Functions use `db_read_user()` instead of reading in the whole database
### 0.5.1 ### 0.5.1
- `/api/logout` API to delete session token - `/api/logout` API to delete session token
- Add basic support for different message types - Add basic support for different message types

View File

@ -1,6 +1,6 @@
[package] [package]
name = "pogchat" name = "pogchat"
version = "0.5.1" version = "0.5.2"
authors = ["Erin Nova <erin@the-system.eu.org>"] authors = ["Erin Nova <erin@the-system.eu.org>"]
edition = "2018" edition = "2018"

View File

@ -27,18 +27,14 @@ 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> = db_read(); // Create an array of users out of parsed json // check if the user exists
for i in &users { if let Some(user) = db_read_user(&name).ok().flatten() {
// loop through elements of the vector warn!("Cannot create user {}! User is already in system.", name);
if i.name == name.to_lowercase() {
warn!("Cannot create user {}! User is already in system.", i.name);
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "user already exists", "reason": "user already exists",
}); });
}; } else {
}
let pin_hashed = sha1::Sha1::from(&pin.to_string()).digest().to_string(); // hash the pin let pin_hashed = sha1::Sha1::from(&pin.to_string()).digest().to_string(); // hash the pin
let new_user: User = User { let new_user: User = User {
@ -49,12 +45,6 @@ pub fn register_user(name: String, pin: i32, pronouns: String) -> JsonValue {
role: UserType::Normal, role: UserType::Normal,
}; };
/*
// append to the json file
match append_json(&new_user) {
Err(why) => panic!("couldn't append json: {}", why),
Ok(()) => info!("Succesfully appended to json"),
};*/
db_add(&new_user); db_add(&new_user);
info!( info!(
@ -66,25 +56,20 @@ pub fn register_user(name: String, pin: i32, pronouns: String) -> JsonValue {
"status": "ok", "status": "ok",
"reason": format!("user {} registered", new_user.name.to_string().to_lowercase()), "reason": format!("user {} registered", new_user.name.to_string().to_lowercase()),
}); });
}
} }
fn create_token(name: String, mut users: Vec<User>) -> String { fn create_token(name: String, mut user: User) -> String {
let charset = "1234567890abcdefghijklmnopqrstuvwxyz"; let charset = "1234567890abcdefghijklmnopqrstuvwxyz";
for i in 0..users.len() { if user.name == name {
if users[i].name == name { user.session_token = generate(12, charset);
users[i].session_token = generate(12, charset); db_add(&user);
/*
match write_json(&users) {
Err(why) => panic!("coudln't write to file: {}", why),
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 = user.session_token.clone();
return token; return token;
}; };
};
warn!("something bad happened while creating a token and idk what"); warn!("something bad happened while creating a token and idk what");
return "NULL".to_string(); return "NULL".to_string();
} }
@ -92,9 +77,9 @@ fn create_token(name: String, mut users: Vec<User>) -> String {
// Check if user is properly logged in // Check if user is properly logged in
#[get("/token/<name>")] #[get("/token/<name>")]
pub fn check_token(name: String, mut cookies: Cookies) -> JsonValue { pub fn check_token(name: String, mut cookies: Cookies) -> JsonValue {
let users: Vec<User> = db_read(); // check if the user is in the system
for i in &users { if let Some(user) = db_read_user(&name).ok().flatten() {
if i.name == name.to_lowercase() { // get the token from the cookie
let token = match cookies.get_private("token") { let token = match cookies.get_private("token") {
None => { None => {
warn!("couldn't get token cookie!"); warn!("couldn't get token cookie!");
@ -105,13 +90,15 @@ pub fn check_token(name: String, mut cookies: Cookies) -> JsonValue {
}, },
Some(token) => token, Some(token) => token,
}; };
// check the token value
if token.value() == "NULL" { if token.value() == "NULL" {
warn!("NULL token!"); warn!("NULL token!");
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "NULL token", "reason": "NULL token",
}); });
} else if token.value() == i.session_token { } else if token.value() == user.session_token {
info!("user {} has correct session token", name); info!("user {} has correct session token", name);
return json!({ return json!({
"status": "ok", "status": "ok",
@ -124,21 +111,19 @@ pub fn check_token(name: String, mut cookies: Cookies) -> JsonValue {
"reason": "incorrect token", "reason": "incorrect token",
}); });
} }
} } else {
}
warn!("user {} not found", name); warn!("user {} not found", name);
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "user not found", "reason": "user not found",
}); });
}
} }
// Logout API // Logout API
#[post("/logout", format = "json", data = "<info>")] #[post("/logout", format = "json", data = "<info>")]
pub fn logout(info: Json<LogoutEvent>, mut cookies: Cookies) -> JsonValue { pub fn logout(info: Json<LogoutEvent>, mut cookies: Cookies) -> JsonValue {
let mut users: Vec<User> = db_read(); if let Some(mut user) = db_read_user(&info.name.to_lowercase()).ok().flatten() {
for i in 0..users.len() {
if info.name.to_lowercase() == users[i].name {
let token = match cookies.get_private("token") { let token = match cookies.get_private("token") {
None => { None => {
warn!("couldn't get token cookie!"); warn!("couldn't get token cookie!");
@ -155,9 +140,10 @@ pub fn logout(info: Json<LogoutEvent>, mut cookies: Cookies) -> JsonValue {
"status": "fail", "status": "fail",
"reason": "NULL token", "reason": "NULL token",
}); });
} else if token.value() == users[i].session_token { } else if token.value() == user.session_token {
cookies.remove_private(Cookie::named("token")); cookies.remove_private(Cookie::named("token"));
users[i].session_token = "NULL".to_string(); user.session_token = "NULL".to_string();
db_add(&user);
info!("logged out user {}", info.name); info!("logged out user {}", info.name);
return json!({ return json!({
"status": "ok", "status": "ok",
@ -170,28 +156,26 @@ pub fn logout(info: Json<LogoutEvent>, mut cookies: Cookies) -> JsonValue {
"reason": "token does not match", "reason": "token does not match",
}); });
} }
} } else {
} warn!("failed to log out user {}, user not found", info.name);
warn!("logged out user {}, user not found", info.name);
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "user not found", "reason": "user not found",
}); });
}
} }
// 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> = db_read(); 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(); let hashed_pin_input = sha1::Sha1::from(&pin.to_string()).digest().to_string();
for i in &users {
// loop through the vector if user.pin_hashed == hashed_pin_input { // check if pin hash matches
if i.name == name.to_lowercase() { info!("pin correct for user {}", &user.name);
if i.pin_hashed == hashed_pin_input {
info!("pin correct for user {}", i.name);
// Create token for user & set a cookie // Create token for user & set a cookie
let token = create_token(i.name.clone(), users); let token = create_token(user.name.clone(), user);
let cookie = Cookie::build("token", token) let cookie = Cookie::build("token", token)
.path("/") .path("/")
.finish(); .finish();
@ -206,14 +190,13 @@ pub fn check_pin(mut cookies: Cookies, name: String, pin: i32) -> JsonValue {
} else { } else {
cookies.remove_private(Cookie::named("token")); cookies.remove_private(Cookie::named("token"));
info!("removed private cookie"); info!("removed private cookie");
warn!("pin incorrect for user {}", i.name); warn!("pin incorrect for user {}", user.name);
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "incorrect pin", "reason": "incorrect pin",
}); });
}; };
}; } else {
}
cookies.remove_private(Cookie::named("token")); cookies.remove_private(Cookie::named("token"));
info!("removed private cookie"); info!("removed private cookie");
warn!( warn!(
@ -224,6 +207,7 @@ pub fn check_pin(mut cookies: Cookies, name: String, pin: i32) -> JsonValue {
"status": "fail", "status": "fail",
"reason": format!("user {} doesn't exist", name.to_string().to_lowercase()), "reason": format!("user {} doesn't exist", name.to_string().to_lowercase()),
}); });
}
} }
// Change info about a user // Change info about a user
@ -251,17 +235,16 @@ pub fn change_info(input: Json<ChangeEvent>, mut cookies: Cookies) -> JsonValue
}); });
} }
// loop through the users // find the user
for i in 0..users.len() { if let Some(mut user) = db_read_user(&input.name).ok().flatten() {
if input.name.to_lowercase() == users[i].name { // if user found... if token.value() == user.session_token { // & if token matches:
if token.value() == users[i].session_token { // & if token matches:
if input.changed_event == "name" { if input.changed_event == "name" {
// remove the user first // remove the user first
db_remove(&users[i]); db_remove(&user);
// change the name // change the name
users[i].name = input.new_event.clone(); user.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);
db_write(&users); db_add(&user);
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),
@ -269,8 +252,8 @@ pub fn change_info(input: Json<ChangeEvent>, mut cookies: Cookies) -> JsonValue
} else if input.changed_event == "pin" { } else if input.changed_event == "pin" {
// 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(); user.pin_hashed = new_hashed_pin.clone();
db_write(&users); db_add(&user);
info!("changed pin of {}", input.name); info!("changed pin of {}", input.name);
return json!({ return json!({
"status": "ok", "status": "ok",
@ -278,9 +261,9 @@ pub fn change_info(input: Json<ChangeEvent>, mut cookies: Cookies) -> JsonValue
}); });
} else if input.changed_event == "pronouns" { } else if input.changed_event == "pronouns" {
// change the pronouns // change the pronouns
users[i].pronouns = input.new_event.clone(); user.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);
db_write(&users); db_add(&user);
return json!({ return json!({
"status": "ok", "status": "ok",
"reason": "successfully changed pronouns", "reason": "successfully changed pronouns",
@ -293,13 +276,17 @@ pub fn change_info(input: Json<ChangeEvent>, mut cookies: Cookies) -> JsonValue
"reason": "incorrect pin", "reason": "incorrect pin",
}); });
}; };
}; } else {
};
warn!("couldn't change users info, user does not exist"); warn!("couldn't change users info, user does not exist");
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "user doesn't exist", "reason": "user doesn't exist",
}); });
}
return json!({
"status": "fail",
"reason": "idk",
});
} }
// Change a users pin/name // Change a users pin/name
@ -421,20 +408,15 @@ pub fn moderation_actions(data: Json<ModerationAction>, mut cookies: Cookies) ->
}, },
Some(token) => token, Some(token) => token,
}; };
let mut user = db_read_user(&data.name.to_lowercase()); if let Some(user) = db_read_user(&data.name.to_lowercase()).ok().flatten() {
let mut users: Vec<User> = Vec::new();
// loop through vector
for i in &users {
if i.name == data.name.to_lowercase() { // found the user!
if token.value() == "NULL" { // fail if token is NULL if token.value() == "NULL" { // fail if token is NULL
warn!("NULL token!"); warn!("NULL token!");
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "NULL token", "reason": "NULL token",
}); });
} else if i.session_token == token.value() { // if token matches } else if user.session_token == token.value() { // if token matches
if i.role == UserType::Normal { if user.role == UserType::Normal {
match data.action { match data.action {
ModActions::Kick => { ModActions::Kick => {
info!("kicked user {}", data.target) info!("kicked user {}", data.target)
@ -460,11 +442,11 @@ pub fn moderation_actions(data: Json<ModerationAction>, mut cookies: Cookies) ->
"reason": "token does not match", "reason": "token does not match",
}) })
}; };
}; } else {
};
warn!("user not found"); warn!("user not found");
json!({ return json!({
"status": "fail", "status": "fail",
"reason": "user not found" "reason": "user not found"
}) });
}
} }

View File

@ -6,6 +6,8 @@ extern crate log;
use crate::user::User; use crate::user::User;
use serde_json::Result; use serde_json::Result;
type MyErrorType = Box<dyn std::error::Error>;
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where where
P: AsRef<Path>, P: AsRef<Path>,
@ -135,10 +137,15 @@ pub fn db_read() -> Vec<User> {
} }
// read one user from the database // read one user from the database
pub fn db_read_user(user: &str) -> User { pub fn db_read_user(user: &str) -> std::result::Result<Option<User>, MyErrorType> {
let db: sled::Db = sled::open("users_db").unwrap(); let db: sled::Db = sled::open("users_db")?;
let bytes = db.get(user).unwrap().unwrap(); let entry = db.get(user)?;
let read_user: User = bincode::deserialize(&bytes).unwrap(); if let Some(user_entry) = entry {
let read_user: User = bincode::deserialize(&user_entry)?;
info!("read user {} from db", read_user.name); info!("read user {} from db", read_user.name);
return read_user; Ok(Some(read_user))
} else {
warn!("user {} not found in db!", user);
Ok(None)
}
} }