app/calendar/api_event.go

121 lines
2.5 KiB
Go
Raw Normal View History

2021-12-24 08:56:16 +00:00
package calendar
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"kumoly.io/kumoly/app/auth"
"kumoly.io/kumoly/app/errors"
"kumoly.io/kumoly/app/history"
"kumoly.io/kumoly/app/server"
)
func ApiEventQuery(c *gin.Context) {
id := c.Query("id")
if id != "" {
e := &Event{}
err := HasEventAccess(c, e, id)
if err != nil {
panic(err)
}
server.OK(c, e)
} else {
grp := c.Query("grp")
events := []Event{}
cl, err := auth.GetContextClaims(c)
if err != nil {
panic(err)
}
var result *gorm.DB
if grp != "" && auth.ACHas(c, auth.ADMIN, auth.SYSTEM, grp) {
var grp_id uint
db.Raw("select id from groups where name = ?", grp).Scan(&grp_id)
if grp_id == 0 {
panic(errors.ErrorNotFound)
}
result = db.Find(&events, "`group_id` = ? ", grp_id)
} else if !auth.ACHas(c, auth.ADMIN, auth.SYSTEM) {
result = db.
Find(&events, "`group_id` in (?) or group_id = 0",
db.Table("groups").Select("id").Where("name in ?", cl.Groups))
} else {
result = db.Find(&events)
}
if result.Error != nil {
panic(result.Error)
}
server.OK(c, events)
}
}
func ApiEventNew(c *gin.Context) {
e := &Event{}
if err := c.ShouldBindJSON(e); err != nil {
panic(err)
}
if e.ID != "" {
panic(errors.ErrorBadRequest)
}
if e.Start.IsZero() || e.End.IsZero() || e.Start.Before(e.End) {
panic(ErrorInvalidTime)
}
if !auth.ACHas(c, auth.ADMIN, auth.SYSTEM, e.GroupName) {
panic(errors.ErrorForbidden)
}
if err := db.Create(e).Error; err != nil {
panic(err)
}
history.Send(history.Info().
Nm("Create").
Grp(e.GroupName).Bd(e).
Iss(c.GetString(auth.GinUserKey)).
Msg("Event created"))
server.OK(c, e)
}
func ApiEventUpdate(c *gin.Context) {
e := &Event{}
if err := c.ShouldBindJSON(e); err != nil {
panic(err)
}
if e.ID == "" {
panic(errors.ErrorBadRequest)
}
if err := HasEventAccess(c, &Event{}, e.ID); err != nil {
panic(errors.ErrorForbidden)
}
if err := db.Save(e).Error; err != nil {
panic(err)
}
history.Send(history.Info().
Nm("Update").
Grp(e.GroupName).Bd(e).
Iss(c.GetString(auth.GinUserKey)).
Msg("Event Updated"))
server.OK(c, e)
}
func ApiEventDelete(c *gin.Context) {
id := c.Query("id")
if id == "" {
panic(errors.ErrorBadRequest)
}
e := &Event{}
err := HasEventAccess(c, e, id)
if err != nil {
panic(err)
}
err = db.Delete(&Calendar{}, "id = ?", id).Error
if err != nil {
panic(errors.NewError(404, err))
}
history.Send(history.Info().
Nm("Delete").
Grp(e.GroupName).Bd(e).
Iss(c.GetString(auth.GinUserKey)).
Msg("Event Deleted"))
server.OK(c, "ok")
}