handler.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package agi
  2. import (
  3. "net/http"
  4. "os"
  5. "path/filepath"
  6. "imuslab.com/arozos/mod/agi/static"
  7. "imuslab.com/arozos/mod/utils"
  8. )
  9. // Handle AGI Exectuion Request with token, design for letting other web scripting language like php to interface with AGI
  10. func (g *Gateway) HandleAgiExecutionRequestWithToken(w http.ResponseWriter, r *http.Request) {
  11. token, err := utils.GetPara(r, "token")
  12. if err != nil {
  13. //Username not defined
  14. utils.SendErrorResponse(w, "Token not defined or empty.")
  15. return
  16. }
  17. script, err := utils.GetPara(r, "script")
  18. if err != nil {
  19. //Username not defined
  20. utils.SendErrorResponse(w, "Script path not defined or empty.")
  21. return
  22. }
  23. //Try to get the username from token
  24. username, err := g.Option.UserHandler.GetAuthAgent().GetUsernameFromToken(token)
  25. if err != nil {
  26. //This token is not valid
  27. w.WriteHeader(http.StatusUnauthorized)
  28. w.Write([]byte("401 - Unauthorized (Token not valid)"))
  29. return
  30. }
  31. //Check if user exists and have access to the script
  32. targetUser, err := g.Option.UserHandler.GetUserInfoFromUsername(username)
  33. if err != nil {
  34. //This user not exists
  35. w.WriteHeader(http.StatusUnauthorized)
  36. w.Write([]byte("401 - Unauthorized (User not exists)"))
  37. return
  38. }
  39. scriptScope := ""
  40. allowAccess := static.CheckUserAccessToScript(targetUser, script, scriptScope)
  41. if !allowAccess {
  42. w.WriteHeader(http.StatusUnauthorized)
  43. w.Write([]byte("401 - Unauthorized (Permission Denied)"))
  44. return
  45. }
  46. //Get the content of the script
  47. scriptContentByte, err := os.ReadFile(filepath.Join("./web/", script))
  48. if err != nil {
  49. w.WriteHeader(http.StatusNotFound)
  50. w.Write([]byte("404 - Script Not Found"))
  51. return
  52. }
  53. scriptContent := string(scriptContentByte)
  54. g.ExecuteAGIScript(scriptContent, nil, script, scriptScope, w, r, targetUser)
  55. }