
encode params takes a &[u8] as parameter now instead of &str utils::decode_params removed for now as it has not real use atm
99 lines
2.7 KiB
Rust
99 lines
2.7 KiB
Rust
use chrono::Utc;
|
|
use std::env;
|
|
use rocket_contrib::json::{Json, JsonValue};
|
|
use diesel::{self, prelude::*};
|
|
use diesel::result::Error;
|
|
|
|
use crate::utils::{encode_param, new_key};
|
|
use crate::models::{User, USER_OFFLINE};
|
|
use crate::{DBConn, schema};
|
|
|
|
pub fn create_new_user(new_name: String) -> User {
|
|
/*
|
|
* Should only eveer be called under good circumstances
|
|
*/
|
|
use schema::users::dsl::*;
|
|
use crate::models::InsertableUser;
|
|
|
|
let conn = MysqlConnection::establish(&env::var("DATABASE_URL").unwrap()).unwrap();
|
|
let ins = InsertableUser {
|
|
name: new_name,
|
|
secret: encode_param(&new_key()),
|
|
date: Utc::now().timestamp() as u64,
|
|
status: USER_OFFLINE,
|
|
};
|
|
// insert the nwe user data then return usable user data to the client
|
|
let _inserted_user = diesel::insert_into(users)
|
|
.values(&ins)
|
|
.execute(&conn);
|
|
|
|
let new_user_data : Result<User, diesel::result::Error> = users
|
|
.filter(date.eq(ins.date))
|
|
.first(&conn);
|
|
|
|
match new_user_data {
|
|
Ok(data) => data,
|
|
Err(_e) => panic!("User could not be found with date of {}", ins.date)
|
|
}
|
|
}
|
|
|
|
|
|
#[delete("/remove/<hash>")]
|
|
pub fn remove_user(hash: u64, conn: DBConn) -> JsonValue {
|
|
// Attempt to remove the user first
|
|
use schema::users::dsl::*;
|
|
use diesel::result::Error;
|
|
|
|
let res: Result<usize, Error> = diesel::delete(users.filter(id.eq(hash))).execute(&conn.0);
|
|
match res {
|
|
Ok(_res) => json!({"staus":"ok"}),
|
|
Err(_e) => json!({"status":"err"}),
|
|
}
|
|
}
|
|
|
|
|
|
// TODO: optional paramter where we can specify getting the offline users as well
|
|
// TODO: More optionally specify what kind of users we want online/offline/away etc.
|
|
#[get("/list")]
|
|
pub fn get_user_list(conn: DBConn) -> Json<Vec<(u64, String, i32)>> {
|
|
use schema::users::dsl::*;
|
|
|
|
let db_response: Result<Vec<(u64, String, i32)>, Error> = users.select((id, name, status))
|
|
.filter(status.ne(USER_OFFLINE))
|
|
.load::<(u64, String, i32)>(&conn.0);
|
|
|
|
match db_response {
|
|
Ok(data) => Json(data),
|
|
Err(_e) => Json(vec!())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod user_tests {
|
|
use super::*;
|
|
use rocket;
|
|
use rocket::local::Client;
|
|
use rocket::http::Status;
|
|
|
|
macro_rules! rocket_inst {
|
|
($func:expr) => {
|
|
rocket::ignite()
|
|
.mount("/users", routes![$func])
|
|
.attach(DBConn::fairing())
|
|
}
|
|
}
|
|
|
|
|
|
#[test]
|
|
fn get_user_list() {
|
|
let app = rocket_inst!(get_user_list);
|
|
let client = Client::new(app).expect("Bad rocket instance");
|
|
|
|
let mut response = client.get("/users/list").dispatch();
|
|
let body: String = response.body_string().unwrap();
|
|
assert_eq!(response.status(), Status::Ok);
|
|
println!("{}", body);
|
|
}
|
|
|
|
}
|