cachedpassword.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package dataprovider
  15. import (
  16. "sync"
  17. )
  18. var cachedPasswords passwordsCache
  19. func init() {
  20. cachedPasswords = passwordsCache{
  21. cache: make(map[string]string),
  22. }
  23. }
  24. type passwordsCache struct {
  25. sync.RWMutex
  26. cache map[string]string
  27. }
  28. func (c *passwordsCache) Add(username, password string) {
  29. if !config.PasswordCaching || username == "" || password == "" {
  30. return
  31. }
  32. c.Lock()
  33. defer c.Unlock()
  34. c.cache[username] = password
  35. }
  36. func (c *passwordsCache) Remove(username string) {
  37. if !config.PasswordCaching {
  38. return
  39. }
  40. c.Lock()
  41. defer c.Unlock()
  42. delete(c.cache, username)
  43. }
  44. // Check returns if the user is found and if the password match
  45. func (c *passwordsCache) Check(username, password string) (bool, bool) {
  46. if username == "" || password == "" {
  47. return false, false
  48. }
  49. c.RLock()
  50. defer c.RUnlock()
  51. pwd, ok := c.cache[username]
  52. if !ok {
  53. return false, false
  54. }
  55. return true, pwd == password
  56. }
  57. // CheckCachedPassword is an utility method used only in test cases
  58. func CheckCachedPassword(username, password string) (bool, bool) {
  59. return cachedPasswords.Check(username, password)
  60. }