Add admin-route & dropdown-menu. Add clear-cache & create-code. Adjustments for activation-code and user models. Add sweet-alert for admin-tools.

This commit is contained in:
MaxJa4
2024-01-20 16:47:22 +01:00
parent f2ab72ba1e
commit e5d13f2270
15 changed files with 281 additions and 55 deletions

61
auth.go
View File

@@ -50,37 +50,56 @@ func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
session, _ := utils.Store.Get(c.Request, utils.LoginSessionName)
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth || !controllers.IsUserEnabled(session.Values["username"].(string)) {
session.Options.MaxAge = -1
err := session.Save(c.Request, c.Writer)
if err != nil {
log.Fatal(err)
}
c.Redirect(http.StatusFound, "/login")
c.Abort()
redirectToLogin(c)
return
}
c.Next()
}
}
func AdminAuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
session, _ := utils.Store.Get(c.Request, utils.LoginSessionName)
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
redirectToLogin(c)
return
}
username, ok := session.Values["username"].(string)
if !ok || !controllers.IsUserEnabled(username) || !controllers.IsUserAdmin(username) {
redirectToLogin(c)
return
}
c.Next()
}
}
func isUserAdmin(c *gin.Context) bool {
session, _ := utils.Store.Get(c.Request, utils.LoginSessionName)
username, ok := session.Values["username"].(string)
if !ok {
return false
}
return controllers.IsUserAdmin(username)
}
func redirectToLogin(c *gin.Context) {
session, _ := utils.Store.Get(c.Request, utils.LoginSessionName)
session.Options.MaxAge = -1
err := session.Save(c.Request, c.Writer)
if err != nil {
log.Fatal(err)
}
c.Redirect(http.StatusFound, "/login")
c.Abort()
}
func isValidCode(code string) bool {
var activationCode models.ActivationCode
if err := models.DB.Where("code = ?", code).First(&activationCode).Error; err != nil {
return false
}
if activationCode.Code == code && !activationCode.Used {
models.DB.Model(&activationCode).Updates(map[string]interface{}{
"Code": code,
"Used": true,
})
newCode := utils.GenerateActivationCode()
newCodeObj := models.ActivationCode{Code: newCode, Used: false}
models.DB.Create(&newCodeObj)
return true
}
return false
return activationCode.Code == code && activationCode.UsedForUsername == ""
}