sec.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package sec
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "errors"
  7. "math/rand"
  8. "git.clearsky.net.au/cody/gex.git/sess"
  9. "git.clearsky.net.au/cody/gex.git/srv"
  10. "git.clearsky.net.au/cody/gex.git/utils"
  11. )
  12. type Auth struct {
  13. User_id float64
  14. User_name string
  15. Roles []string
  16. }
  17. func (auth *Auth) HasRole(role string) bool {
  18. for _, val := range auth.Roles {
  19. if role == val {
  20. return true
  21. }
  22. }
  23. return false
  24. }
  25. var permissions = make(map[string][]string)
  26. func GetCtxAuth(req *srv.Req) (Auth, error) {
  27. sess, err := sess.GetCtxSess(req)
  28. if err != nil {
  29. utils.Err(err)
  30. return Auth{}, err
  31. }
  32. if sess.Data["Auth"] == nil {
  33. err := errors.New("no auth context in session data")
  34. utils.Err(err)
  35. return Auth{}, err
  36. }
  37. auth, ok := sess.Data["Auth"].(Auth)
  38. if !ok {
  39. err := errors.New("auth context in session data is not of the expected type")
  40. utils.Err(err)
  41. return Auth{}, err
  42. }
  43. return auth, nil
  44. }
  45. func Route(pattern string, roles []string, handler func(req *srv.Req, res *srv.Res)) {
  46. permissions[pattern] = roles
  47. srv.Route(pattern, handler)
  48. }
  49. func Hash(key string, data string) string {
  50. bKey := []byte(key)
  51. bData := []byte(data)
  52. h := hmac.New(sha256.New, bKey)
  53. h.Write(bData)
  54. return hex.EncodeToString(h.Sum(nil))
  55. }
  56. func Salt(length int) string {
  57. const charset = "1234567890-=!@#$%^&*()_+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  58. b := make([]byte, length)
  59. for i := range b {
  60. b[i] = charset[rand.Intn(len(charset))]
  61. }
  62. return string(b)
  63. }