Compare commits

..

2 Commits

9 changed files with 326 additions and 276 deletions

View File

@ -163,3 +163,51 @@ form#move-compass {
}
}
}
button.btn {
font-family: inherit;
font-size: 1rem;
appearance: none;
outline: none;
background-color: #808080;
background-image: url("/assets/images/overlay.png");
border: 1px solid #808080;
padding: 0.5rem 1rem;
cursor: pointer;
color: white;
box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.2);
text-shadow: 0px 1px 1px rgba(0, 0, 0, 0.1);
&:hover {
background-color: #909090;
}
}
form.standard {
& > div.row {
display: flex;
flex-direction: column;
margin-bottom: 1.5rem;
label {
font-weight: bold;
}
}
span.help {
font-size: 0.8em;
color: #555;
}
& > div.actions {
margin-top: 1rem;
}
}
.mb-1 {
margin-bottom: 1rem;
}
.mb-05 {
margin-bottom: 0.5rem;
}

BIN
assets/images/overlay.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 261 KiB

View File

@ -6,7 +6,6 @@ import (
"dk/internal/auth"
"dk/internal/csrf"
"dk/internal/database"
"dk/internal/middleware"
"dk/internal/password"
"dk/internal/router"
@ -21,48 +20,31 @@ import (
func RegisterAuthRoutes(r *router.Router) {
// Guest routes
guestGroup := r.Group("")
guestGroup.Use(middleware.RequireGuest("/"))
guestGroup.Use(middleware.RequireGuest())
guestGroup.Get("/login", showLogin)
guestGroup.Post("/login", processLogin())
guestGroup.Post("/login", processLogin)
guestGroup.Get("/register", showRegister)
guestGroup.Post("/register", processRegister())
guestGroup.Post("/register", processRegister)
// Authenticated routes
authGroup := r.Group("")
authGroup.Use(middleware.RequireAuth("/login"))
authGroup.Use(middleware.RequireAuth())
authGroup.Post("/logout", processLogout())
authGroup.Post("/logout", processLogout)
}
// showLogin displays the login form
func showLogin(ctx router.Ctx, params []string) {
loginTmpl, err := template.Cache.Load("auth/login.html")
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return
}
loginFormData := map[string]any{
func showLogin(ctx router.Ctx, _ []string) {
components.RenderPageTemplate(ctx, "Log In", "auth/login.html", map[string]any{
"csrf_token": csrf.GetToken(ctx, auth.Manager),
"csrf_field": csrf.HiddenField(ctx, auth.Manager),
"error_message": "",
}
loginContent := loginTmpl.RenderNamed(loginFormData)
pageData := components.NewPageData("Login - Dragon Knight", loginContent)
if err := components.RenderPage(ctx, pageData, nil); err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return
}
})
}
// processLogin handles login form submission
func processLogin() router.Handler {
return func(ctx router.Ctx, params []string) {
func processLogin(ctx router.Ctx, _ []string) {
if !csrf.ValidateFormToken(ctx, auth.Manager) {
ctx.SetStatusCode(fasthttp.StatusForbidden)
ctx.WriteString("CSRF validation failed")
@ -93,37 +75,21 @@ func processLogin() router.Handler {
}
ctx.Redirect("/", fasthttp.StatusFound)
}
}
// showRegister displays the registration form
func showRegister(ctx router.Ctx, _ []string) {
registerTmpl, err := template.Cache.Load("auth/register.html")
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return
}
registerContent := registerTmpl.RenderNamed(map[string]any{
components.RenderPageTemplate(ctx, "Register", "auth/register.html", map[string]any{
"csrf_token": csrf.GetToken(ctx, auth.Manager),
"csrf_field": csrf.HiddenField(ctx, auth.Manager),
"error_message": "",
"username": "",
"email": "",
})
pageData := components.NewPageData("Register - Dragon Knight", registerContent)
if err := components.RenderPage(ctx, pageData, nil); err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return
}
}
// processRegister handles registration form submission
func processRegister() router.Handler {
return func(ctx router.Ctx, params []string) {
func processRegister(ctx router.Ctx, _ []string) {
if !csrf.ValidateFormToken(ctx, auth.Manager) {
ctx.SetStatusCode(fasthttp.StatusForbidden)
ctx.WriteString("CSRF validation failed")
@ -173,12 +139,10 @@ func processRegister() router.Handler {
}
ctx.Redirect("/", fasthttp.StatusFound)
}
}
// processLogout handles logout
func processLogout() router.Handler {
return func(ctx router.Ctx, params []string) {
func processLogout(ctx router.Ctx, params []string) {
// Validate CSRF token
if !csrf.ValidateFormToken(ctx, auth.Manager) {
ctx.SetStatusCode(fasthttp.StatusForbidden)
@ -188,7 +152,6 @@ func processLogout() router.Handler {
middleware.Logout(ctx, auth.Manager)
ctx.Redirect("/", fasthttp.StatusFound)
}
}
// Helper functions
@ -279,23 +242,3 @@ func validateRegistration(username, email, password, confirmPassword string) err
}
return nil
}
// createUser inserts a new user into the database
// This is a simplified version - in a real app you'd have a proper users.Create function
func createUser(user *users.User) error {
query := `INSERT INTO users (username, password, email, verified, auth) VALUES (?, ?, ?, ?, ?)`
err := database.Exec(query, user.Username, user.Password, user.Email, user.Verified, user.Auth)
if err != nil {
return fmt.Errorf("failed to insert user: %w", err)
}
// Get the user ID (simplified - in real app you'd return it from insert)
createdUser, err := users.GetByUsername(user.Username)
if err != nil {
return fmt.Errorf("failed to get created user: %w", err)
}
user.ID = createdUser.ID
return nil
}

View File

@ -3,11 +3,8 @@ package routes
import (
"dk/internal/middleware"
"dk/internal/router"
"dk/internal/template"
"dk/internal/template/components"
"fmt"
"github.com/valyala/fasthttp"
"dk/internal/towns"
)
func RegisterTownRoutes(r *router.Router) {
@ -19,21 +16,8 @@ func RegisterTownRoutes(r *router.Router) {
}
func showTown(ctx router.Ctx, _ []string) {
tmpl, err := template.Cache.Load("town/town.html")
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return
}
content := tmpl.RenderNamed(map[string]any{
"town": ctx.UserValue("town"),
town := ctx.UserValue("town").(*towns.Town)
components.RenderPageTemplate(ctx, town.Name, "town/town.html", map[string]any{
"town": town,
})
pageData := components.NewPageData("Town - Dragon Knight", content)
if err := components.RenderPage(ctx, pageData, nil); err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return
}
}

View File

@ -3,29 +3,15 @@ package components
import (
"fmt"
"maps"
"strings"
"dk/internal/auth"
"dk/internal/csrf"
"dk/internal/middleware"
"dk/internal/router"
"dk/internal/template"
)
// GenerateTopNav generates the top navigation HTML based on authentication status
func GenerateTopNav(ctx router.Ctx) string {
if middleware.IsAuthenticated(ctx) {
csrfField := csrf.HiddenField(ctx, auth.Manager)
return fmt.Sprintf(`<form action="/logout" method="post" class="logout">
%s
<button class="img-button" type="submit"><img src="/assets/images/button_logout.gif" alt="Log Out" title="Log Out"></button>
</form>
<a href="/help"><img src="/assets/images/button_help.gif" alt="Help" title="Help"></a>`, csrfField)
} else {
return `<a href="/login"><img src="/assets/images/button_login.gif" alt="Log In" title="Log In"></a>
<a href="/register"><img src="/assets/images/button_register.gif" alt="Register" title="Register"></a>
<a href="/help"><img src="/assets/images/button_help.gif" alt="Help" title="Help"></a>`
}
}
"github.com/valyala/fasthttp"
)
// PageData holds common page template data
type PageData struct {
@ -100,3 +86,39 @@ func NewPageData(title, content string) PageData {
Build: "dev",
}
}
// PageTitle returns a proper title for a rendered page. If an empty string
// is given, returns "Dragon Knight". If the provided title already has " - Dragon Knight"
// at the end, returns title as-is. Appends " - Dragon Knight" to title otherwise.
func PageTitle(title string) string {
if title == "" {
return "Dragon Knight"
}
if strings.HasSuffix(" - Dragon Knight", title) {
return title
}
return title + " - Dragon Knight"
}
// RenderPageTemplate is a simplified helper that renders a template within the page layout.
// It loads the template, renders it with the provided data, and then renders the full page.
// Returns true if successful, false if an error occurred (error is written to response).
func RenderPageTemplate(ctx router.Ctx, title, templateName string, data map[string]any) bool {
content, err := template.RenderNamed(templateName, data)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return false
}
pageData := NewPageData(PageTitle(title), content)
if err := RenderPage(ctx, pageData, nil); err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return false
}
return true
}

View File

@ -0,0 +1,24 @@
package components
import (
"dk/internal/auth"
"dk/internal/csrf"
"dk/internal/middleware"
"dk/internal/router"
"fmt"
)
// GenerateTopNav generates the top navigation HTML based on authentication status
func GenerateTopNav(ctx router.Ctx) string {
if middleware.IsAuthenticated(ctx) {
return fmt.Sprintf(`<form action="/logout" method="post" class="logout">
%s
<button class="img-button" type="submit"><img src="/assets/images/button_logout.gif" alt="Log Out" title="Log Out"></button>
</form>
<a href="/help"><img src="/assets/images/button_help.gif" alt="Help" title="Help"></a>`, csrf.HiddenField(ctx, auth.Manager))
} else {
return `<a href="/login"><img src="/assets/images/button_login.gif" alt="Log In" title="Log In"></a>
<a href="/register"><img src="/assets/images/button_register.gif" alt="Register" title="Register"></a>
<a href="/help"><img src="/assets/images/button_help.gif" alt="Help" title="Help"></a>`
}
}

View File

@ -327,7 +327,7 @@ func (t *Template) processIncludes(content string, data map[string]any, opts Ren
}
end += start
directive := result[start+9:end] // Skip "{include "
directive := result[start+9 : end] // Skip "{include "
templateName := strings.Trim(directive, "\" ")
if includedTemplate, err := t.cache.Load(templateName); err == nil {
@ -409,3 +409,28 @@ func (t *Template) processBlocks(content string, opts *RenderOptions) string {
return result
}
// RenderToContext is a simplified helper that renders a template and writes it to the request context
// with error handling. Returns true if successful, false if an error occurred (error is written to response).
func RenderToContext(ctx *fasthttp.RequestCtx, templateName string, data map[string]any) bool {
tmpl, err := Cache.Load(templateName)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return false
}
tmpl.WriteTo(ctx, data)
return true
}
// RenderNamed is a simplified helper that loads and renders a template with the given data,
// returning the rendered content or an error.
func RenderNamed(templateName string, data map[string]any) (string, error) {
tmpl, err := Cache.Load(templateName)
if err != nil {
return "", fmt.Errorf("failed to load template %s: %w", templateName, err)
}
return tmpl.RenderNamed(data), nil
}

View File

@ -1,28 +1,30 @@
<h1>Log In</h1>
{error_message}
<form action="/login" method="post">
<form class="standard mb-1" action="/login" method="post">
{csrf_field}
<table width="75%">
<tr>
<td width="30%">Email/Username:</td>
<td><input type="text" size="30" name="email" required></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" size="30" name="password" required></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Log In"></td>
</tr>
<tr>
<td colspan="2">
<div class="row">
<label for="id">Email/Username</label>
<input id="id" type="text" name="id" required>
</div>
<div class="row">
<label for="password">Password</label>
<input id="password" type="password" name="password" required>
</div>
<div class="actions">
<button class="btn" type="submit">Log in</button>
</div>
</form>
<p class="mb-1">
Want to play? You gotta <a href="/register">register your own character.</a>
</p>
<br><br>
<p>
You may also <a href="/change-password">change your password</a>, or
<a href="/lost-password">request a new one</a> if you've lost yours.
</td>
</tr>
</table>
</form>
</p>

View File

@ -1,44 +1,46 @@
<h1>Register</h1>
{error_message}
<form action="/register" method="post">
<form class="standard" action="/register" method="post">
{csrf_field}
<table width="80%">
<tr>
<td width="20%">Username:</td>
<td>
<input type="text" name="username" size="30" maxlength="30" value="{username}" required>
<br>
Usernames must be 30 alphanumeric characters or less.
<br><br><br>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" size="30" required></td>
</tr>
<tr>
<td>Verify Password:</td>
<td>
<input type="password" name="confirm_password" size="30" required>
<br>
Passwords must be at least 6 characters.
<br><br><br>
</td>
</tr>
<tr>
<td>Email Address:</td>
<td>
<input type="email" name="email" size="30" maxlength="100" value="{email}" required>
<br>
A valid email address is required.
<br><br><br>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Register">
<input type="reset" name="reset" value="Reset">
</td>
</tr>
</table>
<div class="row">
<div>
<label for="username">Username</label>
<span class="help">Must be 30 alphanumeric characters or less.</span>
</div>
<input type="text" id="username" name="username" maxlength="30" value="{username}" required>
</div>
<div class="row">
<div>
<label for="password">Password</label>
<span class="help">Passwords must be at least 6 characters.</span>
</div>
<input type="password" id="password" name="password" required class="mb-05">
<label for="confirm_password">Verify Password</label>
<input type="password" id="confirm_password" name="confirm_password" required>
</div>
<div class="row">
<label for="email">Email</label>
<input type="email" id="email" name="email" maxlength="100" value="{email}" required>
</div>
<div class="row">
<label for="charclass">Class</label>
<select id="charclass" name="charclass">
<option>Choose a Class</option>
<option value="1">Mage</option>
<option value="2">Warrior</option>
<option value="3">Paladin</option>
</select>
</div>
<div class="actions">
<button class="btn" type="submit" name="submit">Register</button>
<button class="btn" type="reset" name="reset">Reset</button>
</div>
</form>