auth.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package main
  2. import (
  3. "crypto/rand"
  4. "encoding/json"
  5. "net/http"
  6. auth "imuslab.com/arozos/mod/auth"
  7. prout "imuslab.com/arozos/mod/prouter"
  8. "imuslab.com/arozos/mod/utils"
  9. )
  10. func AuthInit() {
  11. //Generate session key for authentication module if empty
  12. sysdb.NewTable("auth")
  13. if *session_key == "" {
  14. //Check if the key was generated already. If not, generate a new one
  15. if !sysdb.KeyExists("auth", "sessionkey") {
  16. key := make([]byte, 32)
  17. rand.Read(key)
  18. newSessionKey := string(key)
  19. sysdb.Write("auth", "sessionkey", newSessionKey)
  20. systemWideLogger.PrintAndLog("Auth", "New authentication session key generated", nil)
  21. } else {
  22. systemWideLogger.PrintAndLog("Auth", "Authentication session key loaded from database", nil)
  23. }
  24. skeyString := ""
  25. sysdb.Read("auth", "sessionkey", &skeyString)
  26. session_key = &skeyString
  27. }
  28. //Create an Authentication Agent
  29. authAgent = auth.NewAuthenticationAgent("ao_auth", []byte(*session_key), sysdb, *allow_public_registry, func(w http.ResponseWriter, r *http.Request) {
  30. //Login Redirection Handler, redirect it login.system
  31. w.Header().Set("Cache-Control", "no-cache, no-store, no-transform, must-revalidate, private, max-age=0")
  32. http.Redirect(w, r, utils.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect="+r.URL.Path, http.StatusTemporaryRedirect)
  33. })
  34. if *allow_autologin {
  35. authAgent.AllowAutoLogin = true
  36. } else {
  37. //Default is false. But just in case
  38. authAgent.AllowAutoLogin = false
  39. }
  40. //Register the API endpoints for the authentication UI
  41. http.HandleFunc("/system/auth/login", authAgent.HandleLogin)
  42. http.HandleFunc("/system/auth/logout", authAgent.HandleLogout)
  43. http.HandleFunc("/system/auth/register", authAgent.HandleRegister)
  44. http.HandleFunc("/system/auth/checkLogin", authAgent.CheckLogin)
  45. http.HandleFunc("/api/auth/login", authAgent.HandleAutologinTokenLogin)
  46. authAgent.LoadAutologinTokenFromDB()
  47. }
  48. func AuthSettingsInit() {
  49. //Authentication related settings
  50. adminRouter := prout.NewModuleRouter(prout.RouterOption{
  51. ModuleName: "System Setting",
  52. AdminOnly: true,
  53. UserHandler: userHandler,
  54. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  55. utils.SendErrorResponse(w, "Permission Denied")
  56. },
  57. })
  58. //Handle additional batch operations
  59. adminRouter.HandleFunc("/system/auth/csvimport", authAgent.HandleCreateUserAccountsFromCSV)
  60. adminRouter.HandleFunc("/system/auth/groupdel", authAgent.HandleUserDeleteByGroup)
  61. //System for logging and displaying login user information
  62. registerSetting(settingModule{
  63. Name: "Connection Log",
  64. Desc: "Logs for login attempts",
  65. IconPath: "SystemAO/security/img/small_icon.png",
  66. Group: "Security",
  67. StartDir: "SystemAO/security/connlog.html",
  68. RequireAdmin: true,
  69. })
  70. adminRouter.HandleFunc("/system/auth/logger/index", authAgent.Logger.HandleIndexListing)
  71. adminRouter.HandleFunc("/system/auth/logger/list", authAgent.Logger.HandleTableListing)
  72. //Blacklist Management
  73. registerSetting(settingModule{
  74. Name: "Access Control",
  75. Desc: "Prevent / Allow certain IP ranges from logging in",
  76. IconPath: "SystemAO/security/img/small_icon.png",
  77. Group: "Security",
  78. StartDir: "SystemAO/security/accesscontrol.html",
  79. RequireAdmin: true,
  80. })
  81. //Whitelist API
  82. adminRouter.HandleFunc("/system/auth/whitelist/enable", authAgent.WhitelistManager.HandleSetWhitelistEnable)
  83. adminRouter.HandleFunc("/system/auth/whitelist/list", authAgent.WhitelistManager.HandleListWhitelistedIPs)
  84. adminRouter.HandleFunc("/system/auth/whitelist/set", authAgent.WhitelistManager.HandleAddWhitelistedIP)
  85. adminRouter.HandleFunc("/system/auth/whitelist/unset", authAgent.WhitelistManager.HandleRemoveWhitelistedIP)
  86. //Blacklist API
  87. adminRouter.HandleFunc("/system/auth/blacklist/enable", authAgent.BlacklistManager.HandleSetBlacklistEnable)
  88. adminRouter.HandleFunc("/system/auth/blacklist/list", authAgent.BlacklistManager.HandleListBannedIPs)
  89. adminRouter.HandleFunc("/system/auth/blacklist/ban", authAgent.BlacklistManager.HandleAddBannedIP)
  90. adminRouter.HandleFunc("/system/auth/blacklist/unban", authAgent.BlacklistManager.HandleRemoveBannedIP)
  91. //Register nightly task for clearup all user retry counter
  92. nightlyManager.RegisterNightlyTask(authAgent.ExpDelayHandler.ResetAllUserRetryCounter)
  93. //Register nightly task for clearup all expired switchable account pools
  94. nightlyManager.RegisterNightlyTask(authAgent.SwitchableAccountManager.RunNightlyCleanup)
  95. /*
  96. Account switching functions
  97. */
  98. //Register the APIs for account switching functions
  99. userRouter := prout.NewModuleRouter(prout.RouterOption{
  100. AdminOnly: false,
  101. UserHandler: userHandler,
  102. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  103. utils.SendErrorResponse(w, "Permission Denied")
  104. },
  105. })
  106. userRouter.HandleFunc("/system/auth/u/list", authAgent.SwitchableAccountManager.HandleSwitchableAccountListing)
  107. userRouter.HandleFunc("/system/auth/u/switch", authAgent.SwitchableAccountManager.HandleAccountSwitch)
  108. userRouter.HandleFunc("/system/auth/u/logoutAll", authAgent.SwitchableAccountManager.HandleLogoutAllAccounts)
  109. //API for not logged in pool check
  110. http.HandleFunc("/system/auth/u/p/list", func(w http.ResponseWriter, r *http.Request) {
  111. type ResumableSessionAccount struct {
  112. Username string
  113. ProfileImage string
  114. }
  115. resp := ResumableSessionAccount{}
  116. sessionOwnerName := authAgent.SwitchableAccountManager.GetUnauthedSwitchableAccountCreatorList(w, r)
  117. resp.Username = sessionOwnerName
  118. if sessionOwnerName != "" {
  119. u, err := userHandler.GetUserInfoFromUsername(sessionOwnerName)
  120. if err == nil {
  121. resp.ProfileImage = u.GetUserIcon()
  122. }
  123. }
  124. js, _ := json.Marshal(resp)
  125. utils.SendJSONResponse(w, string(js))
  126. })
  127. }