gosora/common/group.go

114 lines
2.9 KiB
Go
Raw Normal View History

package common
import (
2022-02-21 03:32:53 +00:00
"database/sql"
"encoding/json"
2022-02-21 03:32:53 +00:00
qgen "github.com/Azareal/Gosora/query_gen"
)
var blankGroup = Group{ID: 0, Name: ""}
type GroupAdmin struct {
2022-02-21 03:32:53 +00:00
ID int
Name string
Rank string
RankClass string
CanEdit bool
CanDelete bool
}
// ! Fix the data races in the fperms
type Group struct {
2022-02-21 03:32:53 +00:00
ID int
Name string
IsMod bool
IsAdmin bool
IsBanned bool
Tag string
Perms Perms
PermissionsText []byte
PluginPerms map[string]bool // Custom permissions defined by plugins. What if two plugins declare the same permission, but they handle them in incompatible ways? Very unlikely, we probably don't need to worry about this, the plugin authors should be aware of each other to some extent
PluginPermsText []byte
CanSee []int // The IDs of the forums this group can see
UserCount int // ! Might be temporary as I might want to lean on the database instead for this
}
type GroupStmts struct {
2022-02-21 03:32:53 +00:00
updateGroup *sql.Stmt
updateGroupRank *sql.Stmt
updateGroupPerms *sql.Stmt
}
var groupStmts GroupStmts
func init() {
2022-02-21 03:32:53 +00:00
DbInits.Add(func(acc *qgen.Accumulator) error {
set := func(s string) *sql.Stmt {
return acc.Update("users_groups").Set(s).Where("gid=?").Prepare()
}
groupStmts = GroupStmts{
updateGroup: set("name=?,tag=?"),
updateGroupRank: set("is_admin=?,is_mod=?,is_banned=?"),
updateGroupPerms: set("permissions=?"),
}
return acc.FirstError()
})
}
func (g *Group) ChangeRank(isAdmin, isMod, isBanned bool) (err error) {
2022-02-21 03:32:53 +00:00
_, err = groupStmts.updateGroupRank.Exec(isAdmin, isMod, isBanned, g.ID)
if err != nil {
return err
}
_ = Groups.Reload(g.ID)
return nil
}
func (g *Group) Update(name, tag string) (err error) {
2022-02-21 03:32:53 +00:00
_, err = groupStmts.updateGroup.Exec(name, tag, g.ID)
if err != nil {
return err
}
_ = Groups.Reload(g.ID)
return nil
}
// Please don't pass arbitrary inputs to this method
func (g *Group) UpdatePerms(perms map[string]bool) (err error) {
2022-02-21 03:32:53 +00:00
pjson, err := json.Marshal(perms)
if err != nil {
return err
}
_, err = groupStmts.updateGroupPerms.Exec(pjson, g.ID)
if err != nil {
return err
}
return Groups.Reload(g.ID)
}
// Copy gives you a non-pointer concurrency safe copy of the group
func (g *Group) Copy() Group {
2022-02-21 03:32:53 +00:00
return *g
}
func (g *Group) CopyPtr() (co *Group) {
2022-02-21 03:32:53 +00:00
co = new(Group)
*co = *g
return co
}
// TODO: Replace this sorting mechanism with something a lot more efficient
// ? - Use sort.Slice instead?
type SortGroup []*Group
func (sg SortGroup) Len() int {
2022-02-21 03:32:53 +00:00
return len(sg)
}
func (sg SortGroup) Swap(i, j int) {
2022-02-21 03:32:53 +00:00
sg[i], sg[j] = sg[j], sg[i]
}
func (sg SortGroup) Less(i, j int) bool {
2022-02-21 03:32:53 +00:00
return sg[i].ID < sg[j].ID
}