Core functionality for new aiterp.net servers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.3 KiB

7 years ago
  1. package auth
  2. import (
  3. "net/http"
  4. "strings"
  5. "git.aiterp.net/gisle/wrouter/response"
  6. )
  7. type handler struct {
  8. }
  9. func (h *handler) Handle(path string, w http.ResponseWriter, req *http.Request, user *User) bool {
  10. // Get the subpath out of the path
  11. subpath := req.URL.Path[len(path):]
  12. if subpath[0] == '/' {
  13. subpath = subpath[1:]
  14. }
  15. method := FindAuthenticator(req.Form.Get("method"))
  16. switch strings.ToLower(subpath) {
  17. case "login":
  18. {
  19. if req.Method != "POST" {
  20. response.Text(w, 405, req.Method+" not allowed")
  21. return true
  22. }
  23. username := req.Form.Get("username")
  24. password := req.Form.Get("password")
  25. w.Header().Set("X-Auth-Method", method.Name())
  26. user, err := method.Login(username, password)
  27. if err != nil && user != nil {
  28. sess := OpenSession(user)
  29. http.SetCookie(w, &http.Cookie{Name: SessionCookieName, Value: sess.ID, Expires: sess.Time.Add(SessionMaxTime)})
  30. response.JSON(w, 200, sess)
  31. } else {
  32. response.Text(w, 401, "Login failed")
  33. }
  34. }
  35. case "register":
  36. {
  37. if req.Method != "POST" {
  38. response.Text(w, 405, req.Method+" not allowed")
  39. return true
  40. }
  41. data := make(map[string]string)
  42. for key, value := range req.Form {
  43. if key != "username" && key != "password" && key != "method" {
  44. data[key] = value[0]
  45. }
  46. }
  47. username := req.Form.Get("username")
  48. password := req.Form.Get("password")
  49. user, err := method.Register(username, password, data)
  50. if err != nil && user != nil {
  51. sess := OpenSession(user)
  52. http.SetCookie(w, &http.Cookie{Name: SessionCookieName, Value: sess.ID, Expires: sess.Time.Add(SessionMaxTime)})
  53. response.JSON(w, 200, sess)
  54. } else {
  55. response.Text(w, 401, "Register failed")
  56. }
  57. }
  58. case "logout-all":
  59. {
  60. if req.Method != "POST" {
  61. response.Text(w, 405, req.Method+" not allowed")
  62. return true
  63. }
  64. if user != nil {
  65. ClearSessions(user)
  66. response.Empty(w)
  67. } else {
  68. response.Text(w, 401, "Not logged in")
  69. }
  70. }
  71. case "status":
  72. {
  73. if req.Method != "GET" {
  74. response.Text(w, 405, req.Method+" not allowed")
  75. return true
  76. }
  77. if user != nil {
  78. response.JSON(w, 200, user)
  79. } else {
  80. response.Text(w, 401, "Not logged in")
  81. }
  82. }
  83. default:
  84. {
  85. response.Text(w, 404, "Operation not found: "+subpath)
  86. }
  87. }
  88. return true
  89. }
  90. var Handler = &handler{}