package service import ( "context" "dashoo.cn/micro/app/dao" "dashoo.cn/micro/app/model" "dashoo.cn/opms_libary/micro_srv" "dashoo.cn/opms_libary/myerrors" "dashoo.cn/opms_libary/utils" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/os/grpool" "github.com/gogf/gf/os/gtime" "github.com/gogf/gf/util/gconv" "github.com/mssola/user_agent" ) type LoginLogService struct { *contextService Dao *dao.SysLoginDao Pool *grpool.Pool } func NewLoginLogService(ctx context.Context) (svc *LoginLogService, err error) { svc = new(LoginLogService) if svc.contextService, err = svc.Init(ctx); err != nil { return nil, err } svc.Dao = dao.NewSysLoginDao(svc.Tenant) svc.Pool = grpool.New(100) return svc, nil } func (s *LoginLogService) Invoke(ctx context.Context, userName string, err error) { s.Pool.Add(func() { //写入日志数据 s.Create(ctx, userName, err) }) } func (s *LoginLogService) GetList(req *model.SysLoginLogSearchReq) (total int, list []*model.SysLogin, err error) { db := s.Dao.M order := "info_id DESC" if req.LoginName != "" { db = db.WhereLike("login_name", "%"+req.LoginName+"%") } if req.Status != "" { db = db.Where("status", gconv.Int(req.Status)) } if req.Ipaddr != "" { db = db.WhereLike("ipaddr", "%"+req.Ipaddr+"%") } if req.LoginLocation != "" { db = db.WhereLike("login_location", "%"+req.LoginLocation+"%") } if req.BeginTime != "" { db = db.WhereGTE("login_time", req.BeginTime) } if req.EndTime != "" { db = db.WhereLTE("login_time", req.EndTime) } if req.SortName != "" { if req.SortOrder != "" { order = req.SortName + " " + req.SortOrder } else { order = req.SortName + " DESC" } } total, err = db.Count() if err != nil { g.Log().Error(err) err = myerrors.TipsError("获取总行数失败") return } err = db.Page(req.GetPage()).Order(order).Scan(&list) if err != nil { g.Log().Error(err) err = myerrors.TipsError("获取数据失败") } return } // Create 记录登录日志 func (s *LoginLogService) Create(ctx context.Context, userName string, loginErr error) { clientIP, userAgent, err := micro_srv.GetBrowserInfo(ctx) if err != nil { // 非必要信息,只输出错误日志 g.Log().Error(err) } ua := user_agent.New(userAgent) browser, _ := ua.Browser() status := "10" msg := "登录成功" if loginErr != nil { status = "20" msg = loginErr.Error() } loginData := &model.SysLogin{ UserName: userName, Ipaddr: clientIP, LoginLocation: utils.GetCityByIp(clientIP), Browser: browser, Os: ua.OS(), Status: status, Msg: msg, LoginTime: gtime.Now(), } _, err = s.Dao.Insert(loginData) if err != nil { // 非必要信息,只输出错误日志 g.Log().Error(err) } } func (s *LoginLogService) DeleteByIds(ids []int64) (err error) { if len(ids) == 0 { err = myerrors.TipsError("参数错误") return } _, err = s.Dao.Delete("info_id in (?)", ids) if err != nil { g.Log().Error(err) err = myerrors.TipsError("删除失败") } return } func (s *LoginLogService) ClearLoginLog() (err error) { _, err = s.Dao.DB.Exec("truncate " + s.Dao.Table) if err != nil { g.Log().Error(err) err = myerrors.TipsError("清除失败") } return }