login_check.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package ui
  2. import (
  3. "net/http"
  4. "github.com/miniflux/miniflux/http/context"
  5. "github.com/miniflux/miniflux/http/cookie"
  6. "github.com/miniflux/miniflux/http/request"
  7. "github.com/miniflux/miniflux/http/response"
  8. "github.com/miniflux/miniflux/http/response/html"
  9. "github.com/miniflux/miniflux/http/route"
  10. "github.com/miniflux/miniflux/logger"
  11. "github.com/miniflux/miniflux/ui/form"
  12. "github.com/miniflux/miniflux/ui/session"
  13. "github.com/miniflux/miniflux/ui/view"
  14. )
  15. // CheckLogin validates the username/password and redirects the user to the unread page.
  16. func (c *Controller) CheckLogin(w http.ResponseWriter, r *http.Request) {
  17. ctx := context.New(r)
  18. sess := session.New(c.store, ctx)
  19. authForm := form.NewAuthForm(r)
  20. view := view.New(c.tpl, ctx, sess)
  21. view.Set("errorMessage", "Invalid username or password.")
  22. view.Set("form", authForm)
  23. if err := authForm.Validate(); err != nil {
  24. logger.Error("[Controller:CheckLogin] %v", err)
  25. html.OK(w, r, view.Render("login"))
  26. return
  27. }
  28. if err := c.store.CheckPassword(authForm.Username, authForm.Password); err != nil {
  29. logger.Error("[Controller:CheckLogin] %v", err)
  30. html.OK(w, r, view.Render("login"))
  31. return
  32. }
  33. sessionToken, userID, err := c.store.CreateUserSession(authForm.Username, r.UserAgent(), request.RealIP(r))
  34. if err != nil {
  35. html.ServerError(w, err)
  36. return
  37. }
  38. logger.Info("[Controller:CheckLogin] username=%s just logged in", authForm.Username)
  39. c.store.SetLastLogin(userID)
  40. user, err := c.store.UserByID(userID)
  41. if err != nil {
  42. html.ServerError(w, err)
  43. return
  44. }
  45. sess.SetLanguage(user.Language)
  46. sess.SetTheme(user.Theme)
  47. http.SetCookie(w, cookie.New(
  48. cookie.CookieUserSessionID,
  49. sessionToken,
  50. c.cfg.IsHTTPS,
  51. c.cfg.BasePath(),
  52. ))
  53. response.Redirect(w, r, route.Path(c.router, "unread"))
  54. }