auth.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /*
  37. Recieve the credentials from frontend and validate them
  38. :param c: pointer to Credential struct
  39. */
  40. func Authorize(c *Credentials, cache *AuthCache) (string, error) {
  41. if c.Username == "" || c.Password == "" {
  42. return "", &InvalidCredentials{}
  43. }
  44. if c.Username == os.Getenv("USERNAME") {
  45. if c.Password == os.Getenv("PASSWORD") {
  46. id := uuid.New()
  47. cache.update(id.String(), id.String())
  48. return id.String(), nil
  49. }
  50. return "", &InvalidCredentials{}
  51. }
  52. return "", &InvalidCredentials{}
  53. }