68 lines
2.2 KiB
Go
68 lines
2.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/dchest/captcha"
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"go-dy/internal/config"
|
|
dbpkg "go-dy/internal/db"
|
|
"go-dy/internal/repo"
|
|
"go-dy/internal/resp"
|
|
)
|
|
|
|
func RegisterHandler(cfg config.Config) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if !cfg.AllowRegistration {
|
|
resp.Error(c, http.StatusForbidden, "registration disabled")
|
|
return
|
|
}
|
|
name := strings.TrimSpace(c.PostForm("name"))
|
|
password := c.PostForm("password")
|
|
confirm := c.PostForm("confirm_password")
|
|
captchaID := c.PostForm("captcha_id")
|
|
captchaCode := c.PostForm("captcha_code")
|
|
if cfg.RegisterRequireCaptcha {
|
|
if name == "" || password == "" || confirm == "" || captchaID == "" || captchaCode == "" {
|
|
resp.Error(c, http.StatusBadRequest, "missing fields: name/password/confirm/captcha")
|
|
return
|
|
}
|
|
} else {
|
|
if name == "" || password == "" || confirm == "" {
|
|
resp.Error(c, http.StatusBadRequest, "missing fields: name/password/confirm")
|
|
return
|
|
}
|
|
}
|
|
if password != confirm {
|
|
resp.Error(c, http.StatusBadRequest, "passwords do not match")
|
|
return
|
|
}
|
|
if cfg.RegisterRequireCaptcha {
|
|
if !captcha.VerifyString(captchaID, captchaCode) {
|
|
resp.Error(c, http.StatusBadRequest, "invalid captcha")
|
|
return
|
|
}
|
|
}
|
|
db, err := dbpkg.Get(cfg)
|
|
if err != nil {
|
|
resp.Error(c, http.StatusInternalServerError, "database not available")
|
|
return
|
|
}
|
|
existing, err := repo.GetUserByName(db, name)
|
|
if err != nil {
|
|
resp.Error(c, http.StatusInternalServerError, "database error")
|
|
return
|
|
}
|
|
if existing != nil {
|
|
resp.Error(c, http.StatusBadRequest, "user already exists")
|
|
return
|
|
}
|
|
if err := repo.CreateUser(db, name, password); err != nil {
|
|
resp.Error(c, http.StatusInternalServerError, "create user failed")
|
|
return
|
|
}
|
|
resp.OK(c, gin.H{"username": name})
|
|
}
|
|
} |