feat: implement email validation, CI/CD pipeline, migration history, and web templates
Email validation: - Replace @/. check with net/mail.ParseAddress on register - Add size limit check (max 254 chars, RFC 5321) CI/CD Pipeline: - Add .gitea/workflows/ci.yml (lint → test → build → docker push) - Registry: gitea.mrixs.me/Mrixs/MrixsCraft-server - Push only on main branch Database: - Add migrations/002_migration_history.sql (tracking applied migrations) - Add migrations/README.md (manual apply instructions) Web Templates: - Add base.html with Minecraft-themed layout (dark + green accent) - Add index.html, login.html, register.html with POST forms - Rewrite templates.go for data-driven rendering with pageData struct - Fallback placeholder preserved when templates dir missing
This commit is contained in:
90
.gitea/workflows/ci.yml
Normal file
90
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,90 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
branches: ["main"]
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
|
||||
- name: go vet
|
||||
run: go vet ./...
|
||||
|
||||
- name: gofmt check
|
||||
run: |
|
||||
fmt=$(gofmt -l .)
|
||||
if [ -n "$fmt" ]; then
|
||||
echo "Files needing formatting:"
|
||||
echo "$fmt"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
needs: lint
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
|
||||
- name: Run tests
|
||||
run: go test ./... -v -race -cover
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
needs: test
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
|
||||
- name: Build binary
|
||||
run: go build -o mrixscraft-server ./cmd/server
|
||||
|
||||
- name: Upload artifact
|
||||
if: github.ref == 'refs/heads/main'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: mrixscraft-server
|
||||
path: mrixscraft-server
|
||||
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
if: github.ref == 'refs/heads/main'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Gitea Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: gitea.mrixs.me
|
||||
username: ${{ secrets.GITEA_USERNAME }}
|
||||
password: ${{ secrets.GITEA_TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: |
|
||||
gitea.mrixs.me/Mrixs/MrixsCraft-server:latest
|
||||
gitea.mrixs.me/Mrixs/MrixsCraft-server:${{ github.sha }}
|
||||
cache-from: type=registry,ref=gitea.mrixs.me/Mrixs/MrixsCraft-server:latest
|
||||
cache-to: type=inline
|
||||
@@ -81,7 +81,7 @@ func main() {
|
||||
Handler: handler,
|
||||
}
|
||||
|
||||
// Graceful shutdown.
|
||||
// Graceful shutdown on SIGINT/SIGTERM.
|
||||
done := make(chan os.Signal, 1)
|
||||
signal.Notify(done, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -156,8 +157,12 @@ func (h *Handler) register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Basic email validation.
|
||||
if !strings.Contains(req.Email, "@") || !strings.Contains(req.Email, ".") {
|
||||
// Basic email validation (RFC 5321).
|
||||
if len(req.Email) > 254 {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Email too long (max 254 characters)")
|
||||
return
|
||||
}
|
||||
if _, err := mail.ParseAddress(req.Email); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Invalid email address")
|
||||
return
|
||||
}
|
||||
|
||||
103
internal/templates/html/base.html
Normal file
103
internal/templates/html/base.html
Normal file
@@ -0,0 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{.Title}} — MrixsCraft</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #1a1a2e;
|
||||
--surface: #16213e;
|
||||
--accent: #4ade80;
|
||||
--accent-hover: #22c55e;
|
||||
--text: #e2e8f0;
|
||||
--text-muted: #94a3b8;
|
||||
--error: #f87171;
|
||||
--border: #334155;
|
||||
}
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
a { color: var(--accent); text-decoration: none; }
|
||||
a:hover { text-decoration: underline; }
|
||||
header {
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 0.75rem 0;
|
||||
}
|
||||
header .container {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 0 1rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
header .logo { font-size: 1.25rem; font-weight: 700; color: var(--accent); }
|
||||
header nav a { margin-left: 1rem; font-size: 0.9rem; }
|
||||
main { flex: 1; padding: 2rem 1rem; }
|
||||
.container { max-width: 960px; margin: 0 auto; }
|
||||
h1, h2 { margin-bottom: 1rem; }
|
||||
p { margin-bottom: 0.75rem; color: var(--text-muted); line-height: 1.6; }
|
||||
form { max-width: 360px; }
|
||||
label { display: block; margin-bottom: 0.25rem; font-size: 0.85rem; color: var(--text-muted); }
|
||||
input[type="text"], input[type="email"], input[type="password"] {
|
||||
width: 100%;
|
||||
padding: 0.6rem 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
color: var(--text);
|
||||
font-size: 1rem;
|
||||
}
|
||||
input:focus { outline: none; border-color: var(--accent); }
|
||||
.btn {
|
||||
display: inline-block;
|
||||
background: var(--accent);
|
||||
color: #000;
|
||||
border: none;
|
||||
padding: 0.7rem 1.5rem;
|
||||
border-radius: 6px;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:hover { background: var(--accent-hover); text-decoration: none; }
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 2rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
footer {
|
||||
text-align: center;
|
||||
padding: 1rem;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="container">
|
||||
<span class="logo">MrixsCraft</span>
|
||||
<nav>
|
||||
<a href="/">Главная</a>
|
||||
<a href="/login">Вход</a>
|
||||
<a href="/register">Регистрация</a>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
<main><div class="container">{{template "content" .}}</div></main>
|
||||
<footer>MrixsCraft Server © 2026</footer>
|
||||
</body>
|
||||
</html>
|
||||
17
internal/templates/html/index.html
Normal file
17
internal/templates/html/index.html
Normal file
@@ -0,0 +1,17 @@
|
||||
{{define "content"}}
|
||||
<div class="card">
|
||||
<h1>Добро пожаловать в MrixsCraft</h1>
|
||||
<p>Приватный Minecraft-сервер с модпаками. Зарегистрируйся, скачай лаунчер и играй.</p>
|
||||
<p>
|
||||
<a href="/register" class="btn">Начать играть</a>
|
||||
</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Как начать</h2>
|
||||
<ol style="margin-left: 1.25rem; color: var(--text-muted); line-height: 1.8;">
|
||||
<li>Зарегистрируйся на сайте</li>
|
||||
<li>Скачай лаунчер для своей ОС</li>
|
||||
<li>Авторизуйся, выбирай модпак и нажимай PLAY</li>
|
||||
</ol>
|
||||
</div>
|
||||
{{end}}
|
||||
42
internal/templates/html/login.html
Normal file
42
internal/templates/html/login.html
Normal file
@@ -0,0 +1,42 @@
|
||||
{{define "content"}}
|
||||
<div class="card">
|
||||
<h1>Вход</h1>
|
||||
<form id="loginForm">
|
||||
<label for="username">Логин или Email</label>
|
||||
<input type="text" id="username" name="username" required autocomplete="username">
|
||||
|
||||
<label for="password">Пароль</label>
|
||||
<input type="password" id="password" name="password" required autocomplete="current-password">
|
||||
|
||||
<button type="submit" class="btn">Войти</button>
|
||||
</form>
|
||||
<p id="error" style="color: var(--error); margin-top: 0.75rem; display: none;"></p>
|
||||
<p style="margin-top: 1rem;">Нет аккаунта? <a href="/register">Зарегистрироваться</a></p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const form = new FormData(e.target);
|
||||
const res = await fetch('/api/web/login', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
username: form.get('username'),
|
||||
password: form.get('password')
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
document.getElementById('error').textContent = data.error || 'Ошибка входа';
|
||||
document.getElementById('error').style.display = 'block';
|
||||
return;
|
||||
}
|
||||
// Save token to localStorage and redirect.
|
||||
localStorage.setItem('token', data.token);
|
||||
localStorage.setItem('uuid', data.uuid);
|
||||
localStorage.setItem('username', data.username);
|
||||
window.location.href = '/';
|
||||
});
|
||||
</script>
|
||||
{{end}}
|
||||
43
internal/templates/html/register.html
Normal file
43
internal/templates/html/register.html
Normal file
@@ -0,0 +1,43 @@
|
||||
{{define "content"}}
|
||||
<div class="card">
|
||||
<h1>Регистрация</h1>
|
||||
<form id="regForm">
|
||||
<label for="username">Никнейм</label>
|
||||
<input type="text" id="username" name="username" required minlength="3" maxlength="20" autocomplete="username">
|
||||
|
||||
<label for="email">Email</label>
|
||||
<input type="email" id="email" name="email" required autocomplete="email">
|
||||
|
||||
<label for="password">Пароль</label>
|
||||
<input type="password" id="password" name="password" required minlength="6" autocomplete="new-password">
|
||||
|
||||
<button type="submit" class="btn">Создать аккаунт</button>
|
||||
</form>
|
||||
<p id="error" style="color: var(--error); margin-top: 0.75rem; display: none;"></p>
|
||||
<p style="margin-top: 1rem;">Уже есть аккаунт? <a href="/login">Войти</a></p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('regForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const form = new FormData(e.target);
|
||||
const res = await fetch('/api/web/register', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
username: form.get('username'),
|
||||
email: form.get('email'),
|
||||
password: form.get('password')
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
document.getElementById('error').textContent = data.error || 'Ошибка регистрации';
|
||||
document.getElementById('error').style.display = 'block';
|
||||
return;
|
||||
}
|
||||
// Registration successful — go to login.
|
||||
window.location.href = '/login';
|
||||
});
|
||||
</script>
|
||||
{{end}}
|
||||
@@ -1,7 +1,4 @@
|
||||
// package templates handles Go html/template rendering for the site and admin panel.
|
||||
//
|
||||
// This is a placeholder implementation. Actual templates will be added
|
||||
// when the web UI is designed.
|
||||
// package templates handles Go html/template rendering for the website.
|
||||
package templates
|
||||
|
||||
import (
|
||||
@@ -15,14 +12,20 @@ import (
|
||||
"gitea.mrixs.me/Mrixs/MrixsCraft-server/internal/database"
|
||||
)
|
||||
|
||||
// Handler serves template-rendered pages.
|
||||
type Handler struct {
|
||||
db *database.DB
|
||||
cfg *config.Config
|
||||
layout *template.Template
|
||||
// pageData is passed to all templates.
|
||||
type pageData struct {
|
||||
Title string
|
||||
}
|
||||
|
||||
// NewHandler creates a new templates handler and parses embedded/ondisk templates.
|
||||
// Handler serves template-rendered pages.
|
||||
type Handler struct {
|
||||
db *database.DB
|
||||
cfg *config.Config
|
||||
tmpl *template.Template
|
||||
loaded bool
|
||||
}
|
||||
|
||||
// NewHandler creates a new templates handler and parses on-disk templates.
|
||||
func NewHandler(db *database.DB, cfg *config.Config) *Handler {
|
||||
h := &Handler{db: db, cfg: cfg}
|
||||
h.parseTemplates()
|
||||
@@ -43,36 +46,47 @@ func (h *Handler) index(w http.ResponseWriter, r *http.Request) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if h.layout == nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("<h1>MrixsCraft</h1>"))
|
||||
if !h.loaded {
|
||||
fallback(w, "MrixsCraft")
|
||||
return
|
||||
}
|
||||
h.layout.ExecuteTemplate(w, "index", nil)
|
||||
h.render(w, "index.html", pageData{Title: "Главная"})
|
||||
}
|
||||
|
||||
func (h *Handler) loginPage(w http.ResponseWriter, r *http.Request) {
|
||||
if h.layout == nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("<h1>Login</h1>"))
|
||||
if !h.loaded {
|
||||
fallback(w, "Login")
|
||||
return
|
||||
}
|
||||
h.layout.ExecuteTemplate(w, "login", nil)
|
||||
h.render(w, "login.html", pageData{Title: "Вход"})
|
||||
}
|
||||
|
||||
func (h *Handler) registerPage(w http.ResponseWriter, r *http.Request) {
|
||||
if h.layout == nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("<h1>Register</h1>"))
|
||||
if !h.loaded {
|
||||
fallback(w, "Register")
|
||||
return
|
||||
}
|
||||
h.layout.ExecuteTemplate(w, "register", nil)
|
||||
h.render(w, "register.html", pageData{Title: "Регистрация"})
|
||||
}
|
||||
|
||||
// render executes the named template with data, writing to w.
|
||||
func (h *Handler) render(w http.ResponseWriter, name string, data pageData) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := h.tmpl.ExecuteTemplate(w, name, data); err != nil {
|
||||
log.Printf("Template error (%s): %v", name, err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// fallback writes a minimal placeholder when templates are missing.
|
||||
func fallback(w http.ResponseWriter, title string) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("<h1>" + title + "</h1>"))
|
||||
}
|
||||
|
||||
// ── Template parsing ───────────────────────────────────────────
|
||||
|
||||
func (h *Handler) parseTemplates() {
|
||||
// Look for templates in common locations.
|
||||
dirs := []string{
|
||||
filepath.Join("internal", "templates", "html"),
|
||||
"templates",
|
||||
@@ -81,16 +95,18 @@ func (h *Handler) parseTemplates() {
|
||||
if _, err := os.Stat(dir); err != nil {
|
||||
continue
|
||||
}
|
||||
tmpl, err := template.ParseGlob(filepath.Join(dir, "*.html"))
|
||||
if err == nil && tmpl != nil {
|
||||
h.layout = tmpl
|
||||
pattern := filepath.Join(dir, "*.html")
|
||||
tmpl, err := template.New("").Funcs(template.FuncMap{}).ParseGlob(pattern)
|
||||
if err != nil {
|
||||
log.Printf("Template parse error in %s: %v", dir, err)
|
||||
continue
|
||||
}
|
||||
if tmpl != nil {
|
||||
h.tmpl = tmpl
|
||||
h.loaded = true
|
||||
log.Printf("Loaded templates from %s", dir)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("Template parse error in %s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
// No templates found — handler will use placeholder responses.
|
||||
log.Println("No HTML templates found; using placeholder responses")
|
||||
}
|
||||
|
||||
12
migrations/002_migration_history.sql
Normal file
12
migrations/002_migration_history.sql
Normal file
@@ -0,0 +1,12 @@
|
||||
-- 002_migration_history.sql — Track applied migrations.
|
||||
-- Run manually: psql $DATABASE_URL -f migrations/002_migration_history.sql
|
||||
|
||||
CREATE TABLE IF NOT EXISTS migration_history (
|
||||
id SERIAL PRIMARY KEY,
|
||||
filename VARCHAR(255) UNIQUE NOT NULL,
|
||||
applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Record this migration.
|
||||
INSERT INTO migration_history (filename) VALUES ('002_migration_history.sql')
|
||||
ON CONFLICT (filename) DO NOTHING;
|
||||
14
migrations/README.md
Normal file
14
migrations/README.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Migrations
|
||||
|
||||
Applied manually in order:
|
||||
|
||||
```bash
|
||||
psql "$DATABASE_URL" -f migrations/001_init.sql # schema
|
||||
psql "$DATABASE_URL" -f migrations/002_migration_history.sql # tracking
|
||||
```
|
||||
|
||||
Check applied:
|
||||
|
||||
```sql
|
||||
SELECT * FROM migration_history ORDER BY id;
|
||||
```
|
||||
Reference in New Issue
Block a user