users.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package sso
  2. import (
  3. "encoding/json"
  4. "time"
  5. "github.com/xlzd/gotp"
  6. "imuslab.com/zoraxy/mod/auth"
  7. )
  8. /*
  9. users.go
  10. This file contains the user structure and user management
  11. functions for the SSO module.
  12. If you are looking for handlers, please refer to handlers.go.
  13. */
  14. type SubdomainAccessRule struct {
  15. Subdomain string
  16. AllowAccess bool
  17. }
  18. type UserEntry struct {
  19. UserID string //User ID, in UUIDv4 format
  20. Username string //Username
  21. PasswordHash string //Password hash
  22. TOTPCode string //2FA TOTP code
  23. Enable2FA bool //Enable 2FA for this user
  24. Subdomains map[string]*SubdomainAccessRule //Subdomain and access rule
  25. parent *SSOHandler //Parent SSO handler
  26. }
  27. func (s *SSOHandler) SSO_UserExists(userid string) bool {
  28. //Check if the user exists in the database
  29. var userEntry UserEntry
  30. err := s.Config.Database.Read("sso_users", userid, &userEntry)
  31. if err != nil {
  32. return false
  33. }
  34. return true
  35. }
  36. func (s *SSOHandler) SSO_GetUser(userid string) (UserEntry, error) {
  37. //Load the user entry from database
  38. var userEntry UserEntry
  39. err := s.Config.Database.Read("sso_users", userid, &userEntry)
  40. if err != nil {
  41. return UserEntry{}, err
  42. }
  43. userEntry.parent = s
  44. return userEntry, nil
  45. }
  46. func (s *UserEntry) VerifyPassword(password string) bool {
  47. return s.PasswordHash == auth.Hash(password)
  48. }
  49. // Write changes in the user entry back to the database
  50. func (u *UserEntry) Update() error {
  51. js, _ := json.Marshal(u)
  52. err := u.parent.Config.Database.Write("sso_users", u.UserID, string(js))
  53. if err != nil {
  54. return err
  55. }
  56. return nil
  57. }
  58. // Reset and update the TOTP code for the current user
  59. // Return the provision uri of the new TOTP code for Google Authenticator
  60. func (u *UserEntry) ResetTotp(accountName string, issuerName string) (string, error) {
  61. u.TOTPCode = gotp.RandomSecret(16)
  62. totp := gotp.NewDefaultTOTP(u.TOTPCode)
  63. err := u.Update()
  64. if err != nil {
  65. return "", err
  66. }
  67. return totp.ProvisioningUri(accountName, issuerName), nil
  68. }
  69. // Verify the TOTP code at current time
  70. func (u *UserEntry) VerifyTotp(enteredCode string) bool {
  71. totp := gotp.NewDefaultTOTP(u.TOTPCode)
  72. return totp.Verify(enteredCode, time.Now().Unix())
  73. }