reprogl
1package security2
3import (4"errors"5
6"xelbot.com/reprogl/models"7)
8
9type Identity struct {10ID int `json:"i,omitempty"`11Username string `json:"u,omitempty"`12Role Role `json:"r,omitempty"`13}
14
15type IdentityAware interface {16SetIdentity(Identity)17HasIdentity() bool18IsAdmin() bool19}
20
21type Role uint822
23const (24Guest = iota25User
26Admin
27)
28
29var (30SerializeRoleError = errors.New("security: serialize unknown role")31DeserializeRoleError = errors.New("security: unserialize unknown role")32)
33
34func CreateIdentity(user *models.LoggedUser) Identity {35var role Role36if user.Role == "admin" {37role = Admin38} else {39role = User40}41
42return Identity{43ID: user.ID,44Username: user.Username,45Role: role,46}47}
48
49func (i Identity) IsZero() bool {50return i.ID == 051}
52
53func (i Identity) IsAdmin() bool {54return i.Role == Admin55}
56
57func (r Role) MarshalText() (text []byte, err error) {58switch r {59case Admin:60text = []byte("admin")61case User:62text = []byte("user")63case Guest:64text = []byte{}65default:66err = SerializeRoleError67}68
69return70}
71
72func (r *Role) UnmarshalText(text []byte) error {73switch string(text) {74case "admin":75*r = Admin76case "user":77*r = User78case "":79*r = Guest80default:81return DeserializeRoleError82}83
84return nil85}
86