auth.go 1.6 KB

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