pub mod forms; pub mod db; use bcrypt::{ hash, verify, DEFAULT_COST }; use rocket::{ form::Form, response::Redirect, State }; use forms::{ UserLoginForm, NewUserForm, NewListForm, PermsForm, NewNoteForm, }; use db::{ List, Notes, Note, Result, add_permission, get_user_from_email, get_user_lists, get_user_lists_from_perms, get_notes_from_list, add_note_to_list, User, }; #[macro_use] extern crate rocket; use rocket_dyn_templates::{Template, context}; use rocket_db_pools::{ Database, Connection, sqlx::{ self, Row, }, }; use rocket::{ serde::{ Serialize }, http::{ Cookie, CookieJar, RawStr, }, }; #[get("/hello//")] async fn hello(name: &str, age: u8) -> String { format!("Hello, {} year old named {}!", age, name) } #[get("/")] async fn home() -> Template { Template::render("index", context!{}) } #[get("/create")] async fn create() -> Template { Template::render("new", context!{}) } #[post("/new", data="")] async fn new_user(user: Form>, mut db: Connection) -> Result { let check_exists = sqlx::query!("SELECT id FROM users WHERE username = $1 OR email = $2", user.username, user.email) .fetch_optional(&mut *db) .await?; if check_exists.is_some() { return Ok(format!("This account already exists!")); } let hashed_pass = match hash(user.password, DEFAULT_COST) { Ok(pass) => pass, Err(e) => panic!("Could not hash a password! {}", e) }; sqlx::query!("INSERT INTO users (username,password,email) VALUES ($1, $2, $3)", user.username, hashed_pass, user.email) .execute(&mut *db) .await?; Ok(format!("Thanks, {}, for creating an account on our service.", user.username)) } #[post("/login", data="")] async fn login(user: Form>, mut db: Connection, cookies: &CookieJar<'_>) -> Result { match cookies.get_private("user_uuid") { Some(crumb) => println!("UUID: {:?}", crumb.value()), _ => {} }; let result = sqlx::query!("SELECT * FROM users WHERE username=$1", user.username) .fetch_optional(&mut *db) .await?; let success = match result { Some(ref db_user) => verify(&user.password, &db_user.password).unwrap(), _ => false, }; if success { cookies.add_private(Cookie::new("user_uuid", result.unwrap().uuid)); Ok(format!("Yay! Thanks for logging in to our service!")) } else { Ok(format!("Incorrect login!")) } } #[post("/list", data="")] async fn new_list(mut db: Connection, user: User, new_list: Form>) -> Result { sqlx::query!("INSERT INTO list (owner_id, name) VALUES ($1, $2)", user.id, new_list.name) .execute(&mut *db) .await?; Ok(format!("You added a new list: {}", new_list.name)) } #[post("/list", data="", rank=2)] async fn new_list_not_logged_in(new_list: Form>) -> Redirect { Redirect::to(uri!(home)) } #[get("/lists")] async fn show_list(mut db: Connection, user: User) -> Result