auth.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. 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 *AllCache) (string, error) {
  41. if c.Username == os.Getenv("USERNAME") {
  42. if c.Password == os.Getenv("PASSWORD") {
  43. id := uuid.New()
  44. cache.update(id.String(), id.String())
  45. return id.String(), nil
  46. }
  47. return "", &InvalidCredentials{}
  48. }
  49. return "", &InvalidCredentials{}
  50. }