feat: initial blog engine with multi-language, profile, and role system

- Gin + GORM + Tailwind CSS blog engine
- OS-aware config (Linux /etc/blog_go/, Windows ./win/etc/blog_go/)
- SQLite by default, MySQL support via config
- Auto-migrate database + seed admin user on first run
- Session-based auth (login/logout)
- i18n: Chinese/English with auto-detect + manual switch
- Avatar dropdown nav with click-to-toggle menu
- Profile page: avatar upload, edit info, change password
- Role system: admin (full access) and author (profile only)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-21 01:49:04 +08:00
co-authored by Claude Opus 4.8
commit c82d4482d4
20 changed files with 1592 additions and 0 deletions
+86
View File
@@ -0,0 +1,86 @@
package models
import (
"log"
"os"
"path/filepath"
"go_blog/config"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/glebarez/sqlite"
)
// DB is the global database connection, initialized by InitDB.
var DB *gorm.DB
// InitDB opens the database connection, runs migrations, and seeds the admin user.
func InitDB(cfg *config.Config) *gorm.DB {
// Ensure the storage path exists.
if err := os.MkdirAll(cfg.Path, 0755); err != nil {
log.Fatalf("Failed to create storage directory %s: %v", cfg.Path, err)
}
var dialector gorm.Dialector
switch cfg.Database.Type {
case "mysql":
dsn := cfg.Database.DSN
if dsn == "" {
dsn = "root:password@tcp(127.0.0.1:3306)/blog_go?charset=utf8mb4&parseTime=True&loc=Local"
}
dialector = mysql.Open(dsn)
default:
dbPath := filepath.Join(cfg.Path, "blog.db")
dialector = sqlite.Open(dbPath)
}
db, err := gorm.Open(dialector, &gorm.Config{
Logger: logger.Default.LogMode(logger.Warn),
})
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
// Auto-migrate the User table (idempotent).
if err := db.AutoMigrate(&User{}); err != nil {
log.Fatalf("Failed to auto-migrate database: %v", err)
}
// First-run seed: create admin user if no users exist.
var count int64
db.Model(&User{}).Count(&count)
if count == 0 {
admin := &User{
Username: "admin",
DisplayName: "Administrator",
Gender: "other",
Status: StatusNormal,
Role: RoleAdmin,
}
if err := admin.SetPassword("admin"); err != nil {
log.Fatalf("Failed to hash admin password: %v", err)
}
if err := db.Create(admin).Error; err != nil {
log.Fatalf("Failed to create admin user: %v", err)
}
log.Println("==============================================")
log.Println(" First run: created default admin user.")
log.Println(" Username: admin")
log.Println(" Password: admin")
log.Println(" Please change this password immediately!")
log.Println("==============================================")
}
// Migration fix: always set admin role on the admin user.
result := db.Model(&User{}).Where("username = ?", "admin").Update("role", RoleAdmin)
if result.RowsAffected > 0 {
log.Printf("Migration: set admin role for existing admin user (rows affected: %d)", result.RowsAffected)
}
DB = db
return db
}
+52
View File
@@ -0,0 +1,52 @@
package models
import (
"time"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
// Account status constants.
const (
StatusDisabled = 0 // 禁用
StatusNormal = 1 // 正常
StatusLocked = 2 // 锁定
StatusUnactivated = 3 // 未激活
)
// Role constants.
const (
RoleAdmin = "admin"
RoleAuthor = "author"
)
// User represents a blog user (author / admin).
type User struct {
gorm.Model
Username string `gorm:"uniqueIndex;not null;size:255" json:"username"`
Password string `gorm:"not null" json:"-"`
DisplayName string `gorm:"size:255" json:"display_name"`
Avatar string `gorm:"size:512" json:"avatar"`
Birthday *time.Time `json:"birthday"`
Gender string `gorm:"size:16" json:"gender"`
Email string `gorm:"size:255" json:"email"`
Status int `gorm:"default:1" json:"status"`
Role string `gorm:"size:32;default:author" json:"role"`
}
// SetPassword hashes the plain-text password with bcrypt and stores it.
func (u *User) SetPassword(plain string) error {
hash, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
if err != nil {
return err
}
u.Password = string(hash)
return nil
}
// CheckPassword compares a plain-text password against the stored bcrypt hash.
func (u *User) CheckPassword(plain string) bool {
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(plain))
return err == nil
}