package web import ( "errors" "net/http" "git.keks.cloud/kekskurse/miniauth/pkg/miniauth" "github.com/gin-gonic/gin" ) type WebConfig struct { PublicRegistration bool `env:"PUBLIC_REGISTRATION, default=0"` } type Web struct { config WebConfig ma miniauth.Miniauth } func NewWeb(config WebConfig, ma miniauth.Miniauth) Web { w := Web{} w.config = config w.ma = ma return w } func (w Web) RegisterRoutes(routing *gin.RouterGroup) error { routing.GET("/register", w.GetRegisterPage) routing.POST("/register", w.PostRegisterPage) routing.GET("/login", w.GetLoginPage) routing.POST("/login", w.PostLoginPage) return nil } func (w Web) GetRegisterPage(c *gin.Context) { if !w.config.PublicRegistration { c.HTML(403, "msg.html", gin.H{"msg": "Public registration disabled"}) return } c.HTML(http.StatusOK, "register.html", nil) } func (w Web) PostRegisterPage(c *gin.Context) { if !w.config.PublicRegistration { c.HTML(403, "msg.html", gin.H{"msg": "Public registration disabled"}) return } if c.PostForm("password") != c.PostForm("confirm_password") { c.HTML(http.StatusOK, "register.html", gin.H{"msg": "Passworts dont match"}) return } err := w.ma.RegisterUser(c.PostForm("username"), c.PostForm("email"), c.PostForm("password")) if err != nil { c.HTML(http.StatusOK, "register.html", gin.H{"msg": err.Error()}) return } c.HTML(403, "msg.html", gin.H{"msg": "Your account was created, you can login now"}) } func (w Web) GetLoginPage(c *gin.Context) { c.HTML(http.StatusOK, "login.html", nil) } func (w Web) PostLoginPage(c *gin.Context) { username := c.PostForm("username") password := c.PostForm("password") err := w.ma.UserLogin(username, password) if err != nil { c.HTML(http.StatusOK, "login.html", gin.H{"msg": errors.Unwrap(err).Error()}) return } c.HTML(http.StatusOK, "msg.html", gin.H{"msg": "Login ok!"}) }