Merge branch 'messaging-broken'

Basic messaging funcionality along with other json features are
finished.
pull/5/head
~erin 2021-07-18 12:07:35 -04:00
commit 0833deb93f
10 changed files with 840 additions and 1043 deletions

1391
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,19 @@
[package]
name = "pogchat"
version = "0.2.0"
version = "0.3.0"
authors = ["Erin Nova <erin@the-system.eu.org>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = "0.5.0-rc.1"
serde = "1.0.126"
rocket = "0.4.10"
serde = { version = "1.0.126", features = ["derive"] }
serde_json = "1.0"
sha1 = "0.6.0"
uuid = { version = "0.8.1", features = ["serde", "v4"] }
log = "0.4.0"
env_logger = "0.8.4"
chrono = { version = "0.4.11", features = ["serde"] }
rocket_contrib = { version = "0.4.10", default-features = false, features = ["json"] }
once_cell = "1.8.0"

View File

@ -6,16 +6,39 @@ Send it the unhashed username and pin, and it'll store it in the `users.json` fi
## API Documentation
`POST /api/register/<name>/<pin>/<pronouns>` Register the username with the pin provided if it doesn't already exist
Returns status & reason json.
`GET /api/users/<name>` Check if the user exists
Returns either
`{
"status": "fail",
"reason": "user not found",
}`
or
`{
"status": "ok",
"user": {
"name": "<name>",
"pronouns": "<pronouns>",
},
}`
`GET /api/users/<name>/<pin>` Check if the user exists, and if the pin provided matches
Returns status & reason json.
`POST /api/users/change/<name>/<pin>/<new-name>/<new-pin>` Change a users pin/name
Returns status & reason json.
`GET /api/about/name/<name>` Get's the name of a user, probably just for checking if they exist
`GET /api/about/pronouns/<name>` Get's the pronouns of a user
## Chat Documentation
`POST /api/message/send {"name":"username","body":"message body","date":"yyy-mm-dd","token":"USER_TOKEN"}` Post a json message.
Returns status & reason json.
`GET /api/message/messages.json` Get a json file of all the messages
## Chat Planning
@ -25,7 +48,25 @@ Whenever user sends a message, client will send message & token and backend will
## To-Do:
- [x] Basic auth api
- [ ] Basic messaging system
- [x] Basic auth API
- [ ] Return json instead of string
- "status" shows wether request was succesful or not, either "ok" or "fail"
- "reason" is for more details, mainly just for debugging?
- [x] Basic messaging system
- [x] Finish up `chat::create_message()`
- [x] Create `chat::fetch_messages()`
- [ ] Create `chat::delete_message()`
- [ ] Token generation & storage
- [ ] API to refresh token
- [ ] Store token in json
- [ ] API to check token?
- [x] Pronouns
- [x] Set pronouns
- [ ] Change pronouns
- [ ] Multiple sets of pronouns
- [ ] Some form of plural support?
- [ ] User management (banning, etc.)
- [ ] Blacklist words from chat/names
- [ ] More advanced chat features
- [ ] Different types of message events? eg. default, announcement, command
- [ ] Emote support?

1
message.zsh Executable file
View File

@ -0,0 +1 @@
http POST 'http://localhost:8000/api/message/send' name=Sarah body="meow" date=2021-07-01 token=NULL

View File

@ -1,8 +1,8 @@
extern crate log;
use crate::file_io::{append_json, read_json, write_json};
use crate::user::User;
use crate::file_io::{read_json, append_json, write_json};
use rocket_contrib::json::{Json, JsonValue};
extern crate sha1;
use serde_json::Result;
#[get("/")]
pub fn index() -> &'static str {
@ -20,117 +20,29 @@ pub fn index() -> &'static str {
`GET /api/about/pronouns/<name>` Get the pronouns of a user"
}
/*
// 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>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
// Function to read json from file into the vector
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
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
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(())
}
*/
// Post request to register a user and pin
#[post("/api/register/<name>/<pin>/<pronouns>")]
pub fn register_user(name: &str, pin: i32, pronouns: &str) -> String {
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
for i in &users { // loop through elements of the vector
for i in &users {
// loop through elements of the vector
if i.name == name.to_lowercase() {
warn!("Cannot create user {}! User is already in system.", i.name);
return "User already exists!".to_string();
return json!({
"status": "fail",
"reason": "user already exists",
});
};
};
}
let pin_hashed = sha1::Sha1::from(&pin.to_string()).digest().to_string(); // hash the pin
users.push( User {
users.push(User {
name: name.to_string().to_lowercase(),
pin_hashed: pin_hashed,
pronouns: pronouns.to_string().to_lowercase(),
sessionToken: "NULL".to_string()
session_token: "NULL".to_string(),
}); // append the user to the vec
// append to the json file
@ -139,109 +51,148 @@ pub fn register_user(name: &str, pin: i32, pronouns: &str) -> String {
Ok(()) => info!("Succesfully appended to json"),
};
info!("succesfully created user {} with pin hash {}", users[users.len()-1].name.to_string(), users[users.len()-1].pin_hashed);
return format!("User {} registered with pin hash: {}", users[users.len()-1].name.to_string().to_lowercase(), users[users.len()-1].pin_hashed);
info!(
"succesfully created user {} with pin hash {}",
users[users.len() - 1].name.to_string(),
users[users.len() - 1].pin_hashed
);
return json!({
"status": "ok",
"reason": format!("user {} registered", users[users.len()-1].name.to_string().to_lowercase()),
});
}
// Check if pin matches user
#[get("/api/users/<name>/<pin>")]
pub fn check_pin(name: &str, pin: i32) -> String {
pub fn check_pin(name: String, pin: i32) -> JsonValue {
let users: Vec<User> = read_json();
let hashed_pin_input = sha1::Sha1::from(&pin.to_string()).digest().to_string();
for i in &users { // loop through the vector
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);
return "pin matches".to_string();
return json!({
"status": "ok",
"reason": "pin matches",
});
} else {
warn!("pin incorrect for user {}", i.name);
return "Incorrect pin".to_string();
return json!({
"status": "fail",
"reason": "incorrect pin",
});
};
};
};
warn!("cannot check pin for user {} as they do not exist", name.to_string().to_lowercase());
return format!("User {} does not exist.", name.to_string().to_lowercase());
}
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 a users pin/name
#[post("/api/users/change/<name>/<pin>/<new_name>/<new_pin>")]
pub fn change(name: &str, pin: i32, new_name: &str, new_pin: i32) -> String {
pub fn change(name: String, pin: i32, new_name: String, new_pin: i32) -> JsonValue {
let mut users: Vec<User> = read_json();
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 users[i].pin_hashed == hashed_pin_input { // check if pin is correct
if users[i].name == name.to_lowercase() {
// make sure name exists
if users[i].pin_hashed == hashed_pin_input {
// check if pin 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"),
}
info!("Changed pin of {}", name.to_string().to_lowercase());
return format!("User {}'s new pin hash is {}.", name.to_string().to_lowercase(), users[i].pin_hashed);
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"),
}
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 format!("New name {} is already taken!", 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();
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"),
}
info!("Changed name of {} to {}. New pin hash is {}", name.to_string(), users[i].name.to_string(), users[i].pin_hashed.to_string());
return format!("User previously known as {} is now {}. Pin hash, if different, is {}", name.to_string(), users[i].name.to_string(), users[i].pin_hashed.to_string());
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 pin given for user {}!", name.to_string());
return format!("Incorrect pin for user {}!", name.to_string());
return json!({
"status": "fail",
"reason": "incorrect pin for user",
});
}
}
}
warn!("User {} not found, could not change pin and/or name.", name.to_string());
return format!("User {} not found.", name.to_string());
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("/api/users/<name>")]
pub fn get_user(name: &str) -> String {
pub fn get_user(name: String) -> JsonValue {
let users: Vec<User> = read_json();
let found_user = users.iter().filter(|u| u.name == name.to_lowercase()).next();
let found_user = users
.iter()
.filter(|u| u.name == name.to_lowercase())
.next();
match found_user {
Some(user) => format!("User {}", &user.name),
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(),
Some(user) => json!({
"status":"ok",
"user": {
"name": user.name,
"pronouns": user.pronouns,
},
}),
None => json!({
"status": "fail",
"reason": format!("user {} not found", name),
}),
}
}

93
src/chat.rs Normal file
View File

@ -0,0 +1,93 @@
/* Contains Rocket code for chat/message functionality */
extern crate log;
use once_cell::sync::Lazy;
use std::sync::Mutex;
use crate::file_io::read_json;
use crate::message::{Message, MessageInput};
use rocket_contrib::json::{Json, JsonValue};
use chrono::prelude::*;
use uuid::Uuid;
use crate::user::User;
static MESSAGES: Lazy<Mutex<Vec<Message>>> = Lazy::new(|| Mutex::new(Vec::new()));
#[get("/api/message/messages.json")]
pub fn fetch_messages() -> Json<Vec<Message>> {
let messages = {
let messages = MESSAGES.lock().unwrap();
messages.to_vec()
};
Json(messages)
}
// Create full message object and write to file
fn create_message(message: Json<MessageInput>, file: &str, user: &User) -> JsonValue {
// create full message object
// append message to file
// Create proper datetime format out of string
let date_split: Vec<&str> = message.date.split("-").collect();
let year: i32 = match date_split[0].trim().parse() { // extract year
Err(why) => panic!("could not extract year from given date: {}", why),
Ok(year) => year,
};
let month: u32 = match date_split[1].trim().parse() { // extract month
Err(why) => panic!("could not extract month from given date: {}", why),
Ok(month) => month,
};
let day: u32 = match date_split[2].trim().parse() { // extract day
Err(why) => panic!("could not extract day from given date: {}", why),
Ok(month) => month,
};
let date: DateTime<Utc> = Utc.ymd(year, month, day).and_hms(9, 10, 11);
let message_obj: Message = Message {
id: Uuid::new_v4(),
user: user.to_owned(),
body: message.body.to_string(),
created_at: date,
};
info!("created mesage: {:?}", message_obj);
let mut messages = MESSAGES.lock().unwrap();
messages.push(message_obj.to_owned());
return json!({
"status": "ok",
"reason": "message created",
});
}
// Check if user can create the message, and then create more info about the message
fn check_token(message: Json<MessageInput>) -> JsonValue {
// check if token is correct for name given
let users: Vec<User> = read_json(); // create vector out of users in json file
for i in &users {
// loop through elements
if i.name == message.name.to_lowercase() { // if it finds the user in the file
if i.session_token == message.token { // if token matches
info!("user exists and given token matches");
return create_message(message, "messages.json", i);
} else {
warn!("token does not match!");
return json!({
"status": "fail",
"reason": "token does not match"
})
};
};
};
warn!("user not found");
json!({
"status": "fail",
"reason": "user not found"
})
}
// Receive a basic message
#[post("/api/message/send", format = "json", data = "<message>")]
pub fn send_message(message: Json<MessageInput<'_>>) -> JsonValue {
check_token(message)
}

View File

@ -7,7 +7,9 @@ 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>, {
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
@ -35,22 +37,23 @@ pub fn read_json() -> Vec<User> {
}
// Function to append the last value of the users vector to the file
pub fn append_json(users_list: &Vec<User>) -> Result<()> {
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){
.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])?;
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()) {
@ -71,19 +74,17 @@ pub fn write_json(users_list: &Vec<User>) -> Result<()> {
let path = Path::new("users.json");
let display = path.display();
let mut file = match OpenOptions::new()
.write(true)
.create(true)
.open(&path){
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
if i != users_list.len() - 1 {
// don't append newline if it's the last element
users_json += "\n";
}
}

View File

@ -1,28 +1,41 @@
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate log;
#[macro_use] extern crate rocket;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
use rocket::fairing::AdHoc;
mod auth;
mod user;
mod message;
mod chat;
mod file_io;
mod message;
mod user;
#[launch]
fn rocket() -> _ {
fn main() {
env_logger::init();
info!("Started up rocket");
let cors_fairing = AdHoc::on_response("CORS", |_, res| {
Box::pin(async move {
res.set_raw_header("Access-Control-Allow-Origin", "*");
})
res.set_raw_header("Access-Control-Allow-Origin", "*");
});
info!("Built CORS fairing");
rocket::build()
rocket::ignite()
.mount(
"/",
routes![auth::index, auth::get_user, auth::register_user, auth::check_pin, auth::change, auth::get_user_name, auth::get_user_pronouns],
routes![
auth::index,
auth::get_user,
auth::register_user,
auth::check_pin,
auth::change,
chat::send_message,
chat::fetch_messages
],
)
.attach(cors_fairing)
.launch();
}

View File

@ -1,8 +1,17 @@
use uuid::Uuid;
use chrono::prelude::*;
use crate::user::User;
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Clone)]
#[derive(Deserialize, Serialize)]
pub struct MessageInput<'r> {
pub name: &'r str,
pub body: &'r str,
pub date: &'r str,
pub token: &'r str,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Message {
pub id: Uuid,
pub user: User,

View File

@ -1,10 +1,11 @@
use serde::{Deserialize, Serialize};
// Struct to store basic user data
#[derive(Clone, Serialize, Deserialize)]
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct User {
pub name: String,
pub pin_hashed: String,
pub pronouns: String,
pub sessionToken: String,
#[serde(rename = "sessionToken")]
pub session_token: String,
}