package sec import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "errors" "math/rand" "git.clearsky.net.au/cody/gex.git/sess" "git.clearsky.net.au/cody/gex.git/srv" "git.clearsky.net.au/cody/gex.git/utils" ) type Auth struct { User_id float64 User_name string Roles []string } func (auth *Auth) HasRole(role string) bool { for _, val := range auth.Roles { if role == val { return true } } return false } var permissions = make(map[string][]string) func GetCtxAuth(req *srv.Req) (Auth, error) { sess, err := sess.GetCtxSess(req) if err != nil { utils.Err(err) return Auth{}, err } if sess.Data["Auth"] == nil { err := errors.New("no auth context in session data") utils.Err(err) return Auth{}, err } auth, ok := sess.Data["Auth"].(Auth) if !ok { err := errors.New("auth context in session data is not of the expected type") utils.Err(err) return Auth{}, err } return auth, nil } func Route(pattern string, roles []string, handler func(req *srv.Req, res *srv.Res)) { permissions[pattern] = roles srv.Route(pattern, handler) } func Hash(key string, data string) string { bKey := []byte(key) bData := []byte(data) h := hmac.New(sha256.New, bKey) h.Write(bData) return hex.EncodeToString(h.Sum(nil)) } func Salt(length int) string { const charset = "1234567890-=!@#$%^&*()_+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" b := make([]byte, length) for i := range b { b[i] = charset[rand.Intn(len(charset))] } return string(b) }