Move file functions to seperate file

pull/5/head
~erin 2021-07-17 15:53:10 -04:00
parent a7606709f8
commit 7fa849edf9
Signed by: erin
GPG Key ID: DA70E064A8C70F44
3 changed files with 135 additions and 10 deletions

View File

@ -1,11 +1,8 @@
extern crate log;
use crate::user::User;
use crate::file_io::{read_json, append_json, write_json};
extern crate sha1;
use serde_json::Result;
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::io::{self, BufRead};
use std::path::Path;
#[get("/")]
pub fn index() -> &'static str {
@ -19,7 +16,7 @@ pub fn index() -> &'static str {
`POST /api/users/change/<name>/<pin>/<new-name>/<new-pin>` Change a users name and/or pin"
}
/*
// The output is wrapped in a Result to allow matching on errors
// Returns an Iterator to the Reader of the lines of the file.
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
@ -111,10 +108,10 @@ fn write_json(users_list: &Vec<User>) -> Result<()> {
};
Ok(())
}
*/
// Post request to register a user and pin
#[post("/api/register/<name>/<pin>")]
pub fn register_user(name: &str, pin: i32) -> String {
#[post("/api/register/<name>/<pin>/<pronouns>")]
pub fn register_user(name: &str, pin: i32, pronouns: &str) -> String {
let mut users: Vec<User> = read_json(); // Create an array of users out of parsed json
for i in &users { // loop through elements of the vector
if i.name == name.to_lowercase() {
@ -124,7 +121,14 @@ pub fn register_user(name: &str, pin: i32) -> String {
};
let pin_hashed = sha1::Sha1::from(&pin.to_string()).digest().to_string(); // hash the pin
users.push( User { name: name.to_string().to_lowercase(), pin_hashed: pin_hashed}); // append the user to the vec
users.push( User {
name: name.to_string().to_lowercase(),
pin_hashed: pin_hashed,
pronouns: pronouns.to_string().to_lowercase(),
sessionToken: "NULL".to_string()
}); // append the user to the vec
// append to the json file
match append_json(&users) {
Err(why) => panic!("couldn't append json: {}", why),
@ -214,3 +218,26 @@ pub fn get_user(name: &str) -> String {
None => "User does not exist".to_string(),
}
}
/* Get data about a user */
#[get("/api/about/name/<name>")]
pub fn get_user_name(name: &str) -> String {
let users: Vec<User> = read_json();
let found_user = users.iter().filter(|u| u.name == name.to_lowercase()).next();
match found_user {
Some(user) => user.name.to_string(),
None => "NULL".to_string(),
}
}
#[get("/api/about/pronouns/<name>")]
pub fn get_user_pronouns(name: &str) -> String {
let users: Vec<User> = read_json();
let found_user = users.iter().filter(|u| u.name == name.to_lowercase()).next();
match found_user {
Some(user) => user.pronouns.to_string(),
None => "NULL".to_string(),
}
}

97
src/file_io.rs Normal file
View File

@ -0,0 +1,97 @@
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;
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(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)
.append(true)
.open(&path){
Err(why) => panic!("couldn't create {}: {}", display, why),
Ok(file) => file,
};
// Serialize the last user value
let users_json = serde_json::to_string(&users_list[users_list.len()-1])?;
// 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),
};
// Add newline
match file.write_all("\n".as_bytes()) {
Err(why) => panic!("couldn't write to {}: {}", display, why),
Ok(_) => info!("succesfully wrote 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()-2 { // 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(())
}

View File

@ -6,6 +6,7 @@ use rocket::fairing::AdHoc;
mod auth;
mod user;
mod message;
mod file_io;
#[launch]
fn rocket() -> _ {
@ -21,7 +22,7 @@ fn rocket() -> _ {
rocket::build()
.mount(
"/",
routes![auth::index, auth::get_user, auth::register_user, auth::check_pin, auth::change],
routes![auth::index, auth::get_user, auth::register_user, auth::check_pin, auth::change, auth::get_user_name, auth::get_user_pronouns],
)
.attach(cors_fairing)
}