62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
var adminPasswordHash []byte
|
|
|
|
func InitAdminPassword() error {
|
|
password := os.Getenv("ADMIN_PASSWORD")
|
|
if password == "" {
|
|
password = "admin"
|
|
}
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
adminPasswordHash = hash
|
|
return nil
|
|
}
|
|
|
|
type loginRequest struct {
|
|
Password string `json:"password" binding:"required"`
|
|
}
|
|
|
|
func Login(c *gin.Context) {
|
|
var req loginRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "密码不能为空"})
|
|
return
|
|
}
|
|
|
|
if err := bcrypt.CompareHashAndPassword(adminPasswordHash, []byte(req.Password)); err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"})
|
|
return
|
|
}
|
|
|
|
token, err := GenerateToken()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "生成令牌失败"})
|
|
return
|
|
}
|
|
|
|
c.SetSameSite(http.SameSiteStrictMode)
|
|
c.SetCookie("token", token, 86400, "/", "", IsSecure(), true)
|
|
c.JSON(http.StatusOK, gin.H{"message": "登录成功"})
|
|
}
|
|
|
|
func Logout(c *gin.Context) {
|
|
c.SetSameSite(http.SameSiteStrictMode)
|
|
c.SetCookie("token", "", -1, "/", "", IsSecure(), true)
|
|
c.JSON(http.StatusOK, gin.H{"message": "已退出登录"})
|
|
}
|
|
|
|
func CheckAuth(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"authenticated": true})
|
|
}
|