auth.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package helpers
  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 AllCache struct {
  17. AuthCookies *cache.Cache
  18. }
  19. const (
  20. defaultExpiration = 20 * time.Minute
  21. purgeTime = 1 * time.Hour
  22. )
  23. func NewCache() *AllCache {
  24. Cache := cache.New(defaultExpiration, purgeTime)
  25. return &AllCache{
  26. AuthCookies: Cache,
  27. }
  28. }
  29. func (c *AllCache) update(id string, cookie string) {
  30. c.AuthCookies.Set(id, cookie, cache.DefaultExpiration)
  31. }
  32. func (c *AllCache) Read(id string) bool {
  33. _, ok := c.AuthCookies.Get(id)
  34. if ok {
  35. return true
  36. }
  37. return false
  38. }
  39. /*
  40. Recieve the credentials from frontend and validate them
  41. :param c: pointer to Credential struct
  42. */
  43. func Authorize(c *Credentials, cache *AllCache) (string, error) {
  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. }