diff --git a/controllers/userController.go b/controllers/userController.go index 3f6a88c..f20a581 100644 --- a/controllers/userController.go +++ b/controllers/userController.go @@ -2,7 +2,6 @@ package controllers import ( "fmt" - "math/rand" "net/http" "github.com/gin-gonic/gin" @@ -182,6 +181,38 @@ func (rc *UserController) RegisterView(c *gin.Context) { c.HTML(http.StatusOK, "register.html", data) } +func (rc *UserController) InitAdmin(c *gin.Context) { + isEmpty, err := repositories.Users.IsEmpty() + + if err != nil { + data := gin.H{ + "error": err, + "success": "", + } + + c.HTML(http.StatusInternalServerError, "error.html", data) + return + } + + if !isEmpty { + data := gin.H{ + "error": "Registration is closed", + "success": "", + } + + c.HTML(http.StatusInternalServerError, "error.html", data) + return + + } + + data := gin.H{ + "error": "", + "success": "", + } + + c.HTML(http.StatusOK, "register.html", data) +} + func (rc *UserController) ResetView(c *gin.Context) { shopItems, _ := repositories.ShopItems.GetAll() diff --git a/main.go b/main.go index a94b39f..b3f9f3b 100644 --- a/main.go +++ b/main.go @@ -87,6 +87,7 @@ func main() { //write middleware that redirects to homescreen on register/login/reset for logged in users viewRoutes.GET("/login", userController.LoginView) viewRoutes.GET("/logout", userController.Logout) + viewRoutes.GET("/register", userController.InitAdmin) viewRoutes.GET("/register/:token", userController.RegisterView) viewRoutes.GET("/passwordreset", userController.ResetView) viewRoutes.GET("/additem", authValidator.RequireAuth, shopItemController.AddItemView) diff --git a/repositories/userRepository.go b/repositories/userRepository.go index ae47eeb..d322edb 100644 --- a/repositories/userRepository.go +++ b/repositories/userRepository.go @@ -1,15 +1,16 @@ package repositories -import( +import ( "gorm.io/gorm" "git.dynamicdiscord.de/kalipso/zineshop/models" -) +) type UserRepository interface { - Create(models.User) (models.User, error) + Create(models.User) (models.User, error) GetByEmail(string) (models.User, error) GetById(interface{}) (models.User, error) + IsEmpty() (bool, error) } type GORMUserRepository struct { @@ -22,7 +23,7 @@ func NewGORMUserRepository(db *gorm.DB) UserRepository { } } -func (u *GORMUserRepository) Create(user models.User) (models.User, error) { +func (u *GORMUserRepository) Create(user models.User) (models.User, error) { result := u.DB.Create(&user) if result.Error != nil { @@ -53,3 +54,18 @@ func (u *GORMUserRepository) GetById(id interface{}) (models.User, error) { return user, nil } + +func (u *GORMUserRepository) IsEmpty() (bool, error) { + var user models.User + result := u.DB.First(&user) + + if result.Error != nil { + if result.Error == gorm.ErrRecordNotFound { + return true, nil + } else { + return false, result.Error + } + } + + return false, nil +}