auth.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package auth
  2. import (
  3. "os"
  4. "time"
  5. "github.com/google/uuid"
  6. "github.com/patrickmn/go-cache"
  7. )
  8. type InvalidCredentials struct{}
  9. func (i *InvalidCredentials) Error() string {
  10. return "Invalid credentials supplied."
  11. }
  12. type Credentials struct {
  13. Username string `form:"username" json:"username"`
  14. Password string `form:"password" json:"password"`
  15. }
  16. type AuthCache struct {
  17. AuthCookies *cache.Cache
  18. }
  19. const (
  20. defaultExpiration = 20 * time.Minute
  21. purgeTime = 1 * time.Hour
  22. )
  23. func NewCache() *AuthCache {
  24. Cache := cache.New(defaultExpiration, purgeTime)
  25. return &AuthCache{
  26. AuthCookies: Cache,
  27. }
  28. }
  29. func (c *AuthCache) update(id string, cookie string) {
  30. c.AuthCookies.Set(id, cookie, cache.DefaultExpiration)
  31. }
  32. func (c *AuthCache) Read(id string) bool {
  33. _, ok := c.AuthCookies.Get(id)
  34. return ok
  35. }
  36. type Source interface {
  37. AdminUsername() string
  38. AdminPassword() string
  39. }
  40. type EnvAuth struct{}
  41. func (e EnvAuth) AdminUsername() string { return os.Getenv("KEIJI_USERNAME") }
  42. func (e EnvAuth) AdminPassword() string { return os.Getenv("KEIJI_PASSWORD") }
  43. /*
  44. Recieve the credentials from frontend and validate them
  45. :param c: pointer to Credential struct
  46. */
  47. func Authorize(c *Credentials, cache *AuthCache, authSrc Source) (string, error) {
  48. if c.Username == "" || c.Password == "" {
  49. return "", &InvalidCredentials{}
  50. }
  51. if c.Username == authSrc.AdminUsername() {
  52. if c.Password == authSrc.AdminPassword() {
  53. id := uuid.New()
  54. cache.update(id.String(), id.String())
  55. return id.String(), nil
  56. }
  57. return "", &InvalidCredentials{}
  58. }
  59. return "", &InvalidCredentials{}
  60. }