auth.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package auth
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "os"
  6. "path/filepath"
  7. "sync"
  8. "github.com/gravitl/netmaker/logger"
  9. "github.com/gravitl/netmaker/turnserver/config"
  10. "github.com/pion/turn/v2"
  11. )
  12. var (
  13. authMapLock = &sync.RWMutex{}
  14. HostMap = make(map[string]string)
  15. authBackUpFile = "auth.json"
  16. backUpFilePath = filepath.Join("/etc/config", authBackUpFile)
  17. )
  18. func init() {
  19. os.MkdirAll("/etc/config", os.ModePerm)
  20. // reads creds from disk if any present
  21. loadCredsFromFile()
  22. }
  23. // RegisterNewHostWithTurn - add new host's creds to map and dumps it to the disk
  24. func RegisterNewHostWithTurn(hostID, hostPass string) {
  25. authMapLock.Lock()
  26. HostMap[hostID] = base64.StdEncoding.EncodeToString(turn.GenerateAuthKey(hostID, config.GetTurnHost(), hostPass))
  27. dumpCredsToFile()
  28. authMapLock.Unlock()
  29. }
  30. // UnRegisterNewHostWithTurn - deletes the host creds
  31. func UnRegisterNewHostWithTurn(hostID string) {
  32. authMapLock.Lock()
  33. delete(HostMap, hostID)
  34. dumpCredsToFile()
  35. authMapLock.Unlock()
  36. }
  37. // dumpCredsToFile - saves the creds to file
  38. func dumpCredsToFile() {
  39. d, err := json.MarshalIndent(HostMap, "", " ")
  40. if err != nil {
  41. logger.Log(0, "failed to dump creds to file: ", err.Error())
  42. return
  43. }
  44. err = os.WriteFile(backUpFilePath, d, os.ModePerm)
  45. if err != nil {
  46. logger.Log(0, "failed to backup auth data: ", err.Error())
  47. }
  48. }
  49. // loadCredsFromFile - loads the creds from disk
  50. func loadCredsFromFile() error {
  51. d, err := os.ReadFile(backUpFilePath)
  52. if err != nil {
  53. return err
  54. }
  55. return json.Unmarshal(d, &HostMap)
  56. }