auth.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package main
  2. import (
  3. "crypto/rand"
  4. "log"
  5. "net/http"
  6. auth "imuslab.com/arozos/mod/auth"
  7. prout "imuslab.com/arozos/mod/prouter"
  8. )
  9. func AuthInit() {
  10. //Generate session key for authentication module if empty
  11. sysdb.NewTable("auth")
  12. if *session_key == "" {
  13. //Check if the key was generated already. If not, generate a new one
  14. if !sysdb.KeyExists("auth", "sessionkey") {
  15. key := make([]byte, 32)
  16. rand.Read(key)
  17. newSessionKey := string(key)
  18. sysdb.Write("auth", "sessionkey", newSessionKey)
  19. log.Println("Authentication session key loaded from database")
  20. } else {
  21. log.Println("New authentication session key generated")
  22. }
  23. skeyString := ""
  24. sysdb.Read("auth", "sessionkey", &skeyString)
  25. session_key = &skeyString
  26. }
  27. //Create an Authentication Agent
  28. authAgent = auth.NewAuthenticationAgent("ao_auth", []byte(*session_key), sysdb, *allow_public_registry, func(w http.ResponseWriter, r *http.Request) {
  29. //Login Redirection Handler, redirect it login.system
  30. w.Header().Set("Cache-Control", "no-cache, no-store, no-transform, must-revalidate, private, max-age=0")
  31. http.Redirect(w, r, "/login.system?redirect="+r.URL.Path, 307)
  32. })
  33. if *allow_autologin == true {
  34. authAgent.AllowAutoLogin = true
  35. } else {
  36. //Default is false. But just in case
  37. authAgent.AllowAutoLogin = false
  38. }
  39. //Register the API endpoints for the authentication UI
  40. authAgent.RegisterPublicAPIs(auth.AuthEndpoints{
  41. Login: "/system/auth/login",
  42. Logout: "/system/auth/logout",
  43. Register: "/system/auth/register",
  44. CheckLoggedIn: "/system/auth/checkLogin",
  45. Autologin: "/api/auth/login",
  46. })
  47. authAgent.LoadAutologinTokenFromDB()
  48. }
  49. func AuthSettingsInit() {
  50. //Authentication related settings
  51. adminRouter := prout.NewModuleRouter(prout.RouterOption{
  52. ModuleName: "System Setting",
  53. AdminOnly: true,
  54. UserHandler: userHandler,
  55. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  56. sendErrorResponse(w, "Permission Denied")
  57. },
  58. })
  59. //Handle additional batch operations
  60. adminRouter.HandleFunc("/system/auth/csvimport", authAgent.HandleCreateUserAccountsFromCSV)
  61. adminRouter.HandleFunc("/system/auth/groupdel", authAgent.HandleUserDeleteByGroup)
  62. //API for checking with the logger
  63. adminRouter.HandleFunc("/system/auth/logger/index", authAgent.Logger.HandleIndexListing)
  64. adminRouter.HandleFunc("/system/auth/logger/list", authAgent.Logger.HandleTableListing)
  65. }