index.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package controller
  2. import (
  3. "net/http"
  4. "time"
  5. "x-ui/logger"
  6. "x-ui/web/job"
  7. "x-ui/web/service"
  8. "x-ui/web/session"
  9. "github.com/gin-gonic/gin"
  10. )
  11. type LoginForm struct {
  12. Username string `json:"username" form:"username"`
  13. Password string `json:"password" form:"password"`
  14. }
  15. type IndexController struct {
  16. BaseController
  17. userService service.UserService
  18. }
  19. func NewIndexController(g *gin.RouterGroup) *IndexController {
  20. a := &IndexController{}
  21. a.initRouter(g)
  22. return a
  23. }
  24. func (a *IndexController) initRouter(g *gin.RouterGroup) {
  25. g.GET("/", a.index)
  26. g.POST("/login", a.login)
  27. g.GET("/logout", a.logout)
  28. }
  29. func (a *IndexController) index(c *gin.Context) {
  30. if session.IsLogin(c) {
  31. c.Redirect(http.StatusTemporaryRedirect, "xui/")
  32. return
  33. }
  34. html(c, "login.html", "pages.login.title", nil)
  35. }
  36. func (a *IndexController) login(c *gin.Context) {
  37. var form LoginForm
  38. err := c.ShouldBind(&form)
  39. if err != nil {
  40. pureJsonMsg(c, false, I18n(c, "pages.login.toasts.invalidFormData"))
  41. return
  42. }
  43. if form.Username == "" {
  44. pureJsonMsg(c, false, I18n(c, "pages.login.toasts.emptyUsername"))
  45. return
  46. }
  47. if form.Password == "" {
  48. pureJsonMsg(c, false, I18n(c, "pages.login.toasts.emptyPassword"))
  49. return
  50. }
  51. user := a.userService.CheckUser(form.Username, form.Password)
  52. timeStr := time.Now().Format("2006-01-02 15:04:05")
  53. if user == nil {
  54. job.NewStatsNotifyJob().UserLoginNotify(form.Username, getRemoteIp(c), timeStr, 0)
  55. logger.Infof("wrong username or password: \"%s\" \"%s\"", form.Username, form.Password)
  56. pureJsonMsg(c, false, I18n(c, "pages.login.toasts.wrongUsernameOrPassword"))
  57. return
  58. } else {
  59. logger.Infof("%s login success,Ip Address:%s\n", form.Username, getRemoteIp(c))
  60. job.NewStatsNotifyJob().UserLoginNotify(form.Username, getRemoteIp(c), timeStr, 1)
  61. }
  62. err = session.SetLoginUser(c, user)
  63. logger.Info("user", user.Id, "login success")
  64. jsonMsg(c, I18n(c, "pages.login.toasts.successLogin"), err)
  65. }
  66. func (a *IndexController) logout(c *gin.Context) {
  67. user := session.GetLoginUser(c)
  68. if user != nil {
  69. logger.Info("user", user.Id, "logout")
  70. }
  71. session.ClearSession(c)
  72. c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path"))
  73. }