diff options
| author | MHSanaei <mc.sanaei@gmail.com> | 2023-02-09 22:18:06 +0300 |
|---|---|---|
| committer | MHSanaei <mc.sanaei@gmail.com> | 2023-02-09 22:18:06 +0300 |
| commit | b73e4173a3c1e69e02ad6b4e3b43e425e57a5be9 (patch) | |
| tree | d95d2f5e903d97082e11eb9f9023c165b1bde388 /web/controller/index.go | |
3x-ui
Diffstat (limited to 'web/controller/index.go')
| -rw-r--r-- | web/controller/index.go | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/web/controller/index.go b/web/controller/index.go new file mode 100644 index 00000000..e0be6076 --- /dev/null +++ b/web/controller/index.go @@ -0,0 +1,84 @@ +package controller + +import ( + "net/http" + "time" + "x-ui/logger" + "x-ui/web/job" + "x-ui/web/service" + "x-ui/web/session" + + "github.com/gin-gonic/gin" +) + +type LoginForm struct { + Username string `json:"username" form:"username"` + Password string `json:"password" form:"password"` +} + +type IndexController struct { + BaseController + + userService service.UserService +} + +func NewIndexController(g *gin.RouterGroup) *IndexController { + a := &IndexController{} + a.initRouter(g) + return a +} + +func (a *IndexController) initRouter(g *gin.RouterGroup) { + g.GET("/", a.index) + g.POST("/login", a.login) + g.GET("/logout", a.logout) +} + +func (a *IndexController) index(c *gin.Context) { + if session.IsLogin(c) { + c.Redirect(http.StatusTemporaryRedirect, "xui/") + return + } + html(c, "login.html", "pages.login.title", nil) +} + +func (a *IndexController) login(c *gin.Context) { + var form LoginForm + err := c.ShouldBind(&form) + if err != nil { + pureJsonMsg(c, false, I18n(c , "pages.login.toasts.invalidFormData")) + return + } + if form.Username == "" { + pureJsonMsg(c, false, I18n(c, "pages.login.toasts.emptyUsername")) + return + } + if form.Password == "" { + pureJsonMsg(c, false, I18n(c , "pages.login.toasts.emptyPassword")) + return + } + user := a.userService.CheckUser(form.Username, form.Password) + timeStr := time.Now().Format("2006-01-02 15:04:05") + if user == nil { + job.NewStatsNotifyJob().UserLoginNotify(form.Username, getRemoteIp(c), timeStr, 0) + logger.Infof("wrong username or password: \"%s\" \"%s\"", form.Username, form.Password) + pureJsonMsg(c, false, I18n(c , "pages.login.toasts.wrongUsernameOrPassword")) + return + } else { + logger.Infof("%s login success,Ip Address:%s\n", form.Username, getRemoteIp(c)) + job.NewStatsNotifyJob().UserLoginNotify(form.Username, getRemoteIp(c), timeStr, 1) + } + + err = session.SetLoginUser(c, user) + logger.Info("user", user.Id, "login success") + jsonMsg(c, I18n(c , "pages.login.toasts.successLogin"), err) +} + +func (a *IndexController) logout(c *gin.Context) { + user := session.GetLoginUser(c) + if user != nil { + logger.Info("user", user.Id, "logout") + } + session.ClearSession(c) + c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path")) +} |
