Files
go_blog/handlers/auth.go
T
kevin cefaeac618 feat: add admin user management with role-based access and self-protection
- Add AdminRequired middleware for admin-role routes
- Add login status check to reject disabled/locked accounts
- Add CRUD handlers (list, create, edit, delete) for users
- Add user_list and user_form templates with role/status badges
- Add nav entry and dashboard button for user management
- Add dynamic user count on admin dashboard
- Fix userIDFromSession to handle all numeric session types
- Self-protection: cannot delete/disable self or demote last admin
- Add EN/ZH i18n keys for all user management strings
2026-06-22 18:11:39 +08:00

71 lines
1.6 KiB
Go

package handlers
import (
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"go_blog/models"
)
// LoginPage renders the login form.
func LoginPage() gin.HandlerFunc {
return func(c *gin.Context) {
tr := getTr(c)
data := DefaultData(c)
data["Title"] = tr["page_login"]
if c.Query("error") == "1" {
data["Error"] = tr["login_error"]
}
c.HTML(http.StatusOK, "login", data)
}
}
// Login processes the login form submission.
func Login(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
var user models.User
if err := db.Where("username = ?", username).First(&user).Error; err != nil {
c.Redirect(http.StatusFound, "/login?error=1")
return
}
if !user.CheckPassword(password) {
c.Redirect(http.StatusFound, "/login?error=1")
return
}
// Refuse login for non-normal accounts (disabled / locked / unactivated).
if user.Status != models.StatusNormal {
c.Redirect(http.StatusFound, "/login?error=1")
return
}
// Create session.
session := sessions.Default(c)
session.Set("user_id", user.ID)
session.Set("username", user.Username)
if err := session.Save(); err != nil {
c.String(http.StatusInternalServerError, "Failed to save session")
return
}
c.Redirect(http.StatusFound, "/admin")
}
}
// Logout clears the session and redirects home.
func Logout() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
session.Clear()
session.Save()
c.Redirect(http.StatusFound, "/")
}
}