The backend for the AiteStory website
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.

65 lines
1.5 KiB

  1. package controllers
  2. import (
  3. "net/http"
  4. "git.aiterp.net/AiteRP/aitestory/view"
  5. "git.aiterp.net/AiteRP/aitestory/viewmodel"
  6. "git.aiterp.net/gisle/wrouter"
  7. "git.aiterp.net/gisle/wrouter/auth"
  8. )
  9. // UserController serves and handles the login form
  10. var UserController = wrouter.Router{}
  11. func userLogin(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool {
  12. //var err error
  13. if (req.Method != "GET" && req.Method != "POST") || len(req.URL.Path) > len(path) {
  14. return false
  15. }
  16. if req.Method == "GET" && user != nil {
  17. http.Redirect(w, req, "/", 302)
  18. return true
  19. }
  20. ul := viewmodel.UserLogin{}
  21. if req.Method == "POST" {
  22. req.ParseForm()
  23. wa := WikiAthenticator{}
  24. newUser, err := wa.Login(req.Form.Get("username"), req.Form.Get("password"))
  25. if err == nil {
  26. sess := auth.OpenSession(newUser)
  27. http.SetCookie(w, &http.Cookie{Name: auth.SessionCookieName, Value: sess.ID, Expires: sess.Time.Add(auth.SessionMaxTime), Path: "/", HttpOnly: true})
  28. http.Redirect(w, req, "/", 302)
  29. return true
  30. }
  31. ul.UserName = req.Form.Get("username")
  32. ul.Error = err.Error()
  33. }
  34. ul.Setup(user)
  35. view.Render(w, "login", 200, ul)
  36. return true
  37. }
  38. func userLogout(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool {
  39. //var err error
  40. if user != nil {
  41. auth.CloseSession(user.Session.ID)
  42. }
  43. http.Redirect(w, req, "/", 302)
  44. return true
  45. }
  46. func init() {
  47. UserController.Function("/login", userLogin)
  48. UserController.Function("/logout", userLogout)
  49. }