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,34 +27,24 @@ 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() { return json!({
warn!("Cannot create user {}! User is already in system.", i.name); "status": "fail",
return json!({ "reason": "user already exists",
"status": "fail", });
"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 {
name: name.to_string().to_lowercase(), name: name.to_string().to_lowercase(),
pin_hashed, pin_hashed,
pronouns: pronouns.to_string().to_lowercase(), pronouns: pronouns.to_string().to_lowercase(),
session_token: "NULL".to_string(), session_token: "NULL".to_string(),
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);
/* info!("succesfully created token for user {}", name);
match write_json(&users) { let token = user.session_token.clone();
Err(why) => panic!("coudln't write to file: {}", why), return token;
Ok(()) => info!("succesfully wrote to file"),
};*/
db_write(&users);
info!("succesfully created token for user {}", name);
let token = users[i].session_token.clone();
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,138 +77,137 @@ 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!");
return json!({
"status": "fail",
"reason": "could not read cookie",
});
},
Some(token) => token,
};
if token.value() == "NULL" {
warn!("NULL token!");
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "NULL token", "reason": "could not read cookie",
}); });
} else if token.value() == i.session_token { },
info!("user {} has correct session token", name); Some(token) => token,
return json!({ };
"status": "ok",
"reason": "correct token", // check the token value
}); if token.value() == "NULL" {
} else { warn!("NULL token!");
info!("user {} has incorrect token!", name); return json!({
return json!({ "status": "fail",
"status": "fail", "reason": "NULL token",
"reason": "incorrect token", });
}); } else if token.value() == user.session_token {
} info!("user {} has correct session token", name);
return json!({
"status": "ok",
"reason": "correct token",
});
} else {
info!("user {} has incorrect token!", name);
return json!({
"status": "fail",
"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() { let token = match cookies.get_private("token") {
if info.name.to_lowercase() == users[i].name { None => {
let token = match cookies.get_private("token") { warn!("couldn't get token cookie!");
None => {
warn!("couldn't get token cookie!");
return json!({
"status": "fail",
"reason": "could not read cookie",
});
},
Some(token) => token,
};
if token.value() == "NULL" {
warn!("NULL token!");
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "NULL token", "reason": "could not read cookie",
}); });
} else if token.value() == users[i].session_token { },
cookies.remove_private(Cookie::named("token")); Some(token) => token,
users[i].session_token = "NULL".to_string(); };
info!("logged out user {}", info.name); if token.value() == "NULL" {
return json!({ warn!("NULL token!");
"status": "ok", return json!({
"reason": "logged out", "status": "fail",
}); "reason": "NULL token",
} else { });
warn!("token does not match! cannot logout"); } else if token.value() == user.session_token {
return json!({ cookies.remove_private(Cookie::named("token"));
"status": "fail", user.session_token = "NULL".to_string();
"reason": "token does not match", db_add(&user);
}); info!("logged out user {}", info.name);
} return json!({
"status": "ok",
"reason": "logged out",
});
} else {
warn!("token does not match! cannot logout");
return json!({
"status": "fail",
"reason": "token does not match",
});
} }
} else {
warn!("failed to log out user {}, user not found", info.name);
return json!({
"status": "fail",
"reason": "user not found",
});
} }
warn!("logged out user {}, user not found", info.name);
return json!({
"status": "fail",
"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 i.name == name.to_lowercase() {
if i.pin_hashed == hashed_pin_input {
info!("pin correct for user {}", i.name);
// Create token for user & set a cookie if user.pin_hashed == hashed_pin_input { // check if pin hash matches
let token = create_token(i.name.clone(), users); info!("pin correct for user {}", &user.name);
let cookie = Cookie::build("token", token)
.path("/")
.finish();
cookies.remove_private(Cookie::named("token"));
cookies.add_private(cookie);
info!("set the token cookie");
return json!({ // Create token for user & set a cookie
"status": "ok", let token = create_token(user.name.clone(), user);
"reason": "pin matches", let cookie = Cookie::build("token", token)
}); .path("/")
} else { .finish();
cookies.remove_private(Cookie::named("token")); cookies.remove_private(Cookie::named("token"));
info!("removed private cookie"); cookies.add_private(cookie);
warn!("pin incorrect for user {}", i.name); info!("set the token cookie");
return json!({
"status": "fail", return json!({
"reason": "incorrect pin", "status": "ok",
}); "reason": "pin matches",
}; });
} else {
cookies.remove_private(Cookie::named("token"));
info!("removed private cookie");
warn!("pin incorrect for user {}", user.name);
return json!({
"status": "fail",
"reason": "incorrect pin",
});
}; };
} else {
cookies.remove_private(Cookie::named("token"));
info!("removed private cookie");
warn!(
"cannot check pin for user {} as they do not exist",
name.to_string().to_lowercase()
);
return json!({
"status": "fail",
"reason": format!("user {} doesn't exist", name.to_string().to_lowercase()),
});
} }
cookies.remove_private(Cookie::named("token"));
info!("removed private cookie");
warn!(
"cannot check pin for user {} as they do not exist",
name.to_string().to_lowercase()
);
return json!({
"status": "fail",
"reason": format!("user {} doesn't exist", name.to_string().to_lowercase()),
});
} }
// Change info about a user // Change info about a user
@ -251,54 +235,57 @@ 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(&user);
db_remove(&users[i]); // change the name
// change the name user.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); db_add(&user);
db_write(&users);
return json!({
"status": "ok",
"reason": format!("changed name of {} to {}", input.name, input.new_event),
});
} else if input.changed_event == "pin" {
// change the pin
let new_hashed_pin = sha1::Sha1::from(&input.new_event).digest().to_string();
users[i].pin_hashed = new_hashed_pin.clone();
db_write(&users);
info!("changed pin of {}", input.name);
return json!({
"status": "ok",
"reason": "changed pin",
});
} else if input.changed_event == "pronouns" {
// change the pronouns
users[i].pronouns = input.new_event.clone();
info!("changed pronouns of {} to {}", input.name, input.new_event);
db_write(&users);
return json!({
"status": "ok",
"reason": "successfully changed pronouns",
});
};
} else {
warn!("incorrect pin for user {}", input.name);
return json!({ return json!({
"status": "fail", "status": "ok",
"reason": "incorrect pin", "reason": format!("changed name of {} to {}", input.name, input.new_event),
});
} else if input.changed_event == "pin" {
// change the pin
let new_hashed_pin = sha1::Sha1::from(&input.new_event).digest().to_string();
user.pin_hashed = new_hashed_pin.clone();
db_add(&user);
info!("changed pin of {}", input.name);
return json!({
"status": "ok",
"reason": "changed pin",
});
} else if input.changed_event == "pronouns" {
// change the pronouns
user.pronouns = input.new_event.clone();
info!("changed pronouns of {} to {}", input.name, input.new_event);
db_add(&user);
return json!({
"status": "ok",
"reason": "successfully changed pronouns",
}); });
}; };
}; } else {
}; warn!("incorrect pin for user {}", input.name);
warn!("couldn't change users info, user does not exist"); return json!({
"status": "fail",
"reason": "incorrect pin",
});
};
} else {
warn!("couldn't change users info, user does not exist");
return json!({
"status": "fail",
"reason": "user doesn't exist",
});
}
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "user doesn't exist", "reason": "idk",
}); });
} }
@ -421,50 +408,45 @@ 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() {
if token.value() == "NULL" { // fail if token is NULL
let mut users: Vec<User> = Vec::new(); warn!("NULL token!");
// loop through vector return json!({
for i in &users { "status": "fail",
if i.name == data.name.to_lowercase() { // found the user! "reason": "NULL token",
if token.value() == "NULL" { // fail if token is NULL });
warn!("NULL token!"); } else if user.session_token == token.value() { // if token matches
return json!({ if user.role == UserType::Normal {
"status": "fail", match data.action {
"reason": "NULL token", ModActions::Kick => {
}); info!("kicked user {}", data.target)
} else if i.session_token == token.value() { // if token matches },
if i.role == UserType::Normal { ModActions::Ban => info!("banned user {}", data.target),
match data.action { _ => info!("F"),
ModActions::Kick => {
info!("kicked user {}", data.target)
},
ModActions::Ban => info!("banned user {}", data.target),
_ => info!("F"),
};
return json!({
"status": "ok",
"reason": "completed action",
});
} else {
warn!("user does not have sufficient permissions to perform that action!");
return json!({
"status": "fail",
"reason": "insufficient permissions",
});
}; };
return json!({
"status": "ok",
"reason": "completed action",
});
} else { } else {
warn!("token does not match!"); warn!("user does not have sufficient permissions to perform that action!");
return json!({ return json!({
"status": "fail", "status": "fail",
"reason": "token does not match", "reason": "insufficient permissions",
}) });
}; };
} else {
warn!("token does not match!");
return json!({
"status": "fail",
"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 {
info!("read user {} from db", read_user.name); let read_user: User = bincode::deserialize(&user_entry)?;
return read_user; info!("read user {} from db", read_user.name);
Ok(Some(read_user))
} else {
warn!("user {} not found in db!", user);
Ok(None)
}
} }