use crate::db::{self, TenebrousDbConn}; use crate::errors::Error; use crate::models::{ characters::{CharacterEntry, NewCharacter}, User, }; use rocket::response::Redirect; use rocket_contrib::templates::Template; use serde_derive::Serialize; use std::collections::HashMap; pub(crate) fn routes() -> Vec { routes![ view_character, new_character, new_character_not_logged_in, edit_character ] } //TODO make private -- currently is referenced in homepage route. //or move to common place. #[derive(Serialize)] pub struct TemplateContext { pub characters: Vec, pub user: User, } //TODO should return result based on whether or not character is publicly viewable. #[get("//")] fn view_character( character_id: i32, user: Option, conn: TenebrousDbConn, ) -> Result { let user = user.ok_or(Error::NotFound)?; let character = db::load_character(conn, character_id)?.ok_or(Error::NotFound)?; let mut context = HashMap::new(); context.insert("name", character.name); context.insert("username", user.username); Ok(Template::render("view_character", context)) } #[get("/new")] fn new_character(logged_in_user: User, conn: TenebrousDbConn) -> Result { let context = HashMap::::new(); Ok(Template::render("new_character", context)) } #[get("/new", rank = 2)] fn new_character_not_logged_in() -> Redirect { super::common::redirect_to_login() } #[get("///edit")] fn edit_character( character_id: i32, owner: Option, logged_in_user: Option, conn: TenebrousDbConn, ) -> Result { let owner = owner.ok_or(Error::NotFound)?; let logged_in_user = logged_in_user.ok_or(Error::NotLoggedIn)?; let character = db::load_character(conn, character_id)?.ok_or(Error::NotFound)?; if logged_in_user != owner { return Err(Error::NoPermission); } let mut context = HashMap::new(); context.insert("name", character.name); context.insert("username", owner.username); Ok(Template::render("view_character", context)) }