public string LoginLogSaveChanges(string jsonString, string action) { try { LoginLogEntity entity = JsonConvert.DeserializeObject <LoginLogEntity>(jsonString); LoginLogManager manager = new LoginLogManager(); if (action == "add") { if (entity == null) { return("error"); } manager.Insert(entity); } else { LoginLogEntity oldEntity = manager.GetLoginLogByGuid(entity.Guid); oldEntity.StartTime = entity.StartTime; oldEntity.EndTime = entity.EndTime; manager.Update(oldEntity); } return("success"); } catch (Exception e) { return(e.ToString()); } }
public bool AddLoginInfo(LoginLogEntity logEntity, string openMoblie, TradeAccountSource source, out string error, out long tradeAccountID) { error = string.Empty; tradeAccountID = 0; if (logEntity == null) { error = "参数为null"; return(false); } using (var conn = factory.Create(DatabaseName.DB_IQFTrade)) { var list = conn.Query("proc_Login_Add_New", new { userID = logEntity.UserID, brokerAccount = logEntity.BrokerAccount, brokerType = logEntity.BrokerType, accountType = logEntity.AccountType, IP = logEntity.IP, Mac = logEntity.Mac, packType = logEntity.PackType, clientVersion = logEntity.ClientVersion, status = logEntity.Status, errorNo = logEntity.ErrorNo, errorMsg = logEntity.ErrorMsg, openAcctMobile = openMoblie, source = source, compCounter = logEntity.CompCounter }, null, true, null, CommandType.StoredProcedure).FirstOrDefault(); var ret = list as IDictionary <string, object>; if (ret == null) { error = "插入登录数据失败"; return(false); } var errorNo = (int)ret.Values.First(); if (errorNo != 0) { error = ret.Values.ElementAt(1).ToString(); return(false); } tradeAccountID = Convert.ToInt64(ret.Values.ElementAt(2)); return(true); } }
public List <LoginLogEntity> GetSearch(string whereCondition, string sort, string order, int offset, int pageSize, out int total) { int pageCount = 0; string querySql = string.Format("select * from LoginLog(nolock) {0}", whereCondition); DataTable dt = SplitPage.SqlSplitPage(querySql, string.Format("order by {0} {1}", sort, order), null, offset / pageSize, pageSize, out pageCount, out total); List <LoginLogEntity> list = new List <LoginLogEntity>(); foreach (DataRow dr in dt.Rows) { LoginLogEntity entity = new LoginLogEntity(); entity.ID = Ext.ToInt(dr["ID"]); entity.Guid = Ext.ToString(dr["Guid"]); entity.Type = Ext.ToString(dr["Type"]); entity.LoginID = Ext.ToInt(dr["LoginName"]); entity.LoginName = Ext.ToString(dr["LoginName"]); entity.LoginType = Ext.ToString(dr["LoginType"]); entity.Action = Ext.ToString(dr["Action"]); entity.TimeRecord = Ext.ToDateOrNull(dr["TimeRecord"]); entity.Remark = Ext.ToString(dr["Remark"]); entity.MachineID = Ext.ToString(dr["MachineID"]); entity.LoginIP = Ext.ToString(dr["LoginIP"]); entity.LoginIP2 = Ext.ToString(dr["LoginIP2"]); entity.StartTime = Ext.ToDateOrNull(dr["StartTime"]); entity.EndTime = Ext.ToDateOrNull(dr["EndTime"]); entity.CreateTime = Ext.ToDate(dr["CreateTime"]); entity.UpdateTime = Ext.ToDate(dr["UpdateTime"]); list.Add(entity); } return(list); }
public async Task <IResultModel> Add(LoginLogEntity info) { if (info == null) { return(ResultModel.Failed()); } info.Id = _repository.GetSeq("S_SYS_LOGINLOG").ToString(); int result = await _repository.InsertAsync(info); return(ResultModel.Success(result)); }
/// <summary> /// 写日志 /// </summary> /// <param name="logEntity">对象</param> public static void WriteLog(this LoginLogEntity logEntity) { try { service.WriteLog(logEntity); } catch (Exception ex) { LogUtil.Error(ex.InnerException.Message); throw; } }
public int Add(LoginLogEntity entity) { if (null == entity) { return(0); } string insert = "INSERT INTO [LoginLog] ([UserID],[BrokerAccount],[BrokerType],[AccountType],[IP],[Mac],[PackType],[ClientVersion],[Status],[ErrorNo],[ErrorMsg]) VALUES (@UserID, @BrokerAccount, @BrokerType, @AccountType, @IP, @Mac, @PackType, @ClientVersion,@Status,@ErrorNo,@ErrorMsg)"; using (var conn = factory.Create(DatabaseName.DB_IQFTrade)) { return(conn.Execute(insert, entity)); } }
/// <summary> /// 保存日志 /// </summary> protected async ValueTask SaveLog(LoginLogEntity log, ResultModel <LoginResultModel> result) { log.Success = result.Successful; log.Error = result.Msg; //保存日志,不能抛出异常以免影响登录本身的功能 try { await _logHandler.Handle(log); } catch (Exception ex) { _logger.LogError("登录日志存储失败:{@ex}", ex); } }
/// <summary> /// 登陆 /// </summary> /// <param name="dto">登录信息</param> /// <returns></returns> public async Task <UserLoginDto> LoginAsync(LoginDto dto) { var reslt = new UserLoginDto(); var logDbSet = _context.LoginLogs; var loginName = dto.LoginName.Trim(); var entity = await _context.Users.FirstOrDefaultAsync(item => item.LoginName == loginName); var loginLog = new LoginLogEntity { Id = Guid.NewGuid().ToString("N"), LoginName = dto.LoginName, IP = dto.LoginIP, CreateDateTime = DateTime.Now }; if (entity == null) { reslt.Message = "Account not exists"; reslt.Result = LoginResult.AccountNotExists; loginLog.UserId = string.Empty; } else { if (entity.Password == dto.Password.ToMd5()) { reslt.LoginSuccess = true; reslt.Message = "Login success"; reslt.Result = LoginResult.Success; reslt.User = _mapper.Map <UserEntity, UserDto>(entity); reslt.User.UserRoles = await _context.UserRoles.Where(x => x.UserId == entity.Id) .Select(x => new UserRoleDto { RoleId = x.RoleId, RoleName = x.Role.Name }).ToListAsync(); } else { reslt.Message = "Wrong password"; reslt.Result = LoginResult.WrongPassword; } loginLog.UserId = entity.Id; } loginLog.Message = reslt.Message; logDbSet.Add(loginLog); await _context.SaveChangesAsync(); return(reslt); }
private async Task AddLoginLog(LoginLogEntity entity) { entity.IP = IPHelper.GetIP(HttpContext?.Request); string ua = HttpContext.Request.Headers["User-Agent"]; if (ua.NotNull()) { var client = UAParser.Parser.GetDefault().Parse(ua); var device = client.Device.Family; device = device.ToLower() == "other" ? "" : device; entity.Browser = client.UA.Family; entity.Os = client.OS.Family; entity.Device = device; entity.BrowserInfo = ua; } var id = (await _loginLogRepository.InsertAsync(entity)).Id; }
/// <summary> /// 登陆 /// </summary> /// <param name="dto">登录信息</param> /// <returns></returns> public async Task <UserLoginDto> LoginAsync(LoginDto dto) { using (var scope = _dbContextScopeFactory.Create()) { var reslt = new UserLoginDto(); var db = scope.DbContexts.Get <JuCheapContext>(); var dbSet = db.Set <UserEntity>(); var logDbSet = db.Set <LoginLogEntity>(); var entity = await dbSet.FirstOrDefaultAsync(item => item.LoginName == dto.LoginName.Trim()); var loginLog = new LoginLogEntity { Id = BaseIdGenerator.Instance.GetId(), LoginName = dto.LoginName, IP = dto.LoginIP }; if (entity == null) { reslt.Message = "账号不存在"; reslt.Result = LoginResult.AccountNotExists; loginLog.UserId = "0"; } else { if (entity.Password == dto.Password.ToMd5()) { reslt.LoginSuccess = true; reslt.Message = "登陆成功"; reslt.Result = LoginResult.Success; reslt.User = _mapper.Map <UserEntity, UserDto>(entity); } else { reslt.Message = "登陆密码错误"; reslt.Result = LoginResult.WrongPassword; } loginLog.UserId = entity.Id; } loginLog.Mac = reslt.Message; logDbSet.Add(loginLog); await scope.SaveChangesAsync(); return(reslt); } }
public Task Handle(LoginResultModel model) { var entity = new LoginLogEntity { AccountId = model.AccountId, UserName = model.UserName, Email = model.Email, Error = model.Error, LoginMode = model.LoginMode, LoginTime = model.LoginTime, Phone = model.Phone, Platform = model.Platform, Success = model.Success, IP = _loginInfo.IP, UserAgent = _loginInfo.UserAgent }; return(_repository.AddAsync(entity)); }
public void Update(LoginLogEntity entity) { entity.UpdateTime = DateTime.Now; IDbSession session = SessionFactory.CreateSession(); try { session.BeginTrans(); Repository.Update <LoginLogEntity>(session.Connection, entity, session.Transaction); session.Commit(); } catch (System.Exception) { session.Rollback(); throw; } finally { session.Dispose(); } }
public void GetLoginLogs(string jsonString) { //用于序列化实体类的对象 JavaScriptSerializer jss = new JavaScriptSerializer(); //查询条件 LoginLogEntity entity = JsonConvert.DeserializeObject <LoginLogEntity>(jsonString); //请求中携带的条件 string order = HttpContext.Request.Params["order"]; string sort = HttpContext.Request.Params["sort"]; int offset = Convert.ToInt32(HttpContext.Request.Params["offset"]); //0 int pageSize = Convert.ToInt32(HttpContext.Request.Params["limit"]); StringBuilder sbCondition = new StringBuilder(); if (entity != null) { sbCondition.Append(" where 1 = 1"); if (!string.IsNullOrWhiteSpace(entity.Type)) { sbCondition.Append(string.Format(" and Type = '{0}'", entity.Type)); } if (!string.IsNullOrWhiteSpace(entity.Guid)) { sbCondition.Append(string.Format(" and Guid = '{0}'", entity.Guid)); } if (entity.LoginID > 0) { sbCondition.Append(string.Format(" and LoginID = {0}", entity.LoginID)); } if (!string.IsNullOrWhiteSpace(entity.LoginName)) { sbCondition.Append(string.Format(" and LoginName = '{0}'", entity.LoginName)); } if (!string.IsNullOrWhiteSpace(entity.LoginType)) { sbCondition.Append(string.Format(" and LoginType = '{0}'", entity.LoginType)); } if (!string.IsNullOrWhiteSpace(entity.Action)) { sbCondition.Append(string.Format(" and Action = '{0}'", entity.Action)); } if (entity.StartTime != null) { sbCondition.Append(string.Format(" and TimeRecord >= '{0}'", entity.StartTime)); } if (entity.EndTime != null) { sbCondition.Append(string.Format(" and TimeRecord <= '{0}'", entity.EndTime)); } } int total = 0; LoginLogManager manager = new LoginLogManager(); List <LoginLogEntity> list = manager.GetSearch(sbCondition.ToString(), sort, order, offset, pageSize, out total); //给分页实体赋值 PageModels <LoginLogEntity> model = new PageModels <LoginLogEntity>(); model.total = total; if (total % pageSize == 0) { model.page = total / pageSize; } else { model.page = (total / pageSize) + 1; } model.rows = list; //将查询结果返回 HttpContext.Response.Write(jss.Serialize(model)); }
/// <summary> /// 登录处理 /// </summary> private async Task <ResultModel <LoginResultModel> > Handle(PhoneLoginModel model, LoginLogEntity log) { var result = new ResultModel <LoginResultModel>(); var config = _configProvider.Get <AuthConfig>(); if (!config.LoginMode.Phone) { return(result.Failed("不允许使用手机号登录的方式")); } //检测图片验证码 var verifyCodeCheckResult = _verifyCodeProvider.Check(model); if (!verifyCodeCheckResult.Successful) { return(result.Failed(verifyCodeCheckResult.Msg)); } //检测手机验证码 var verifyResult = await _phoneVerifyCodeProvider.Verify(model.Phone, model.Code, model.AreaCode); if (!verifyResult.Successful) { return(result.Failed(verifyResult.Msg)); } //查询账户 var account = await _repository.GetByPhone(model.Phone, model.AccountType); if (account == null) { return(result.Failed("账户不存在")); } if (log != null) { log.AccountId = account.Id; } //检测账户 var accountCheckResult = account.Check(); if (!accountCheckResult.Successful) { return(result.Failed(accountCheckResult.Msg)); } //更新认证信息并返回登录结果 var resultModel = await UpdateAuthInfo(account, model, config); return(resultModel != null?result.Success(resultModel) : result.Failed()); }
/// <summary> /// 添加登录日志 /// </summary> /// <param name="log"></param> /// <returns></returns> public async Task <bool> AddLoginLog(LoginLogEntity log) { await _content.LoginLog.AddAsync(log); return(await _content.SaveChangesAsync() > 0); }
public async Task <IResponseOutput> Login(LoginInput input) { if (!ModelState.IsValid) { return(ResponseOutput.NotOk(ModelState.Values.First().Errors[0].ErrorMessage)); } var sw = new Stopwatch(); sw.Start(); var context = await _interaction.GetAuthorizationContextAsync(input.ReturnUrl); var user = await _userRepository.Select.Where(a => a.UserName == input.UserName) .ToOneAsync(a => new { a.Id, a.Password, a.NickName }); if (user == null) { return(ResponseOutput.NotOk("", 1)); } var password = MD5Encrypt.Encrypt32(input.Password); if (user.Password != password) { return(ResponseOutput.NotOk("", 2)); } AuthenticationProperties props = null; if (input.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1)) }; } ; var identityServerUser = new IdentityServerUser(user.Id.ToString()) { DisplayName = input.UserName }; await HttpContext.SignInAsync(identityServerUser, props); sw.Stop(); //写登录日志 var loginLogEntity = new LoginLogEntity() { CreatedUserId = user.Id, NickName = user.NickName, CreatedUserName = input.UserName, ElapsedMilliseconds = sw.ElapsedMilliseconds, Status = true }; await AddLoginLog(loginLogEntity); return(ResponseOutput.Ok()); }
public Task Handle(LoginLogEntity entity) { return(_repository.AddAsync(entity)); }
public async Task <IResponseOutput> Login(LoginInput input) { if (!ModelState.IsValid) { return(ResponseOutput.NotOk(ModelState.Values.First().Errors[0].ErrorMessage)); } if (input.Captcha == null) { return(ResponseOutput.NotOk("请完成安全验证!")); } //滑动验证 input.Captcha.DeleteCache = true; using var client = new HttpClient(); var res = await client.GetAsync($"{_appSettings.Captcha.CheckUrl}?{ToParams(input.Captcha)}"); var content = await res.Content.ReadAsStringAsync(); var captchaResult = JsonConvert.DeserializeObject <ResultModel <string> >(content); if (!captchaResult.Success) { return(ResponseOutput.NotOk("安全验证不通过,请重新登录!")); } var sw = new Stopwatch(); sw.Start(); var context = await _interaction.GetAuthorizationContextAsync(input.ReturnUrl); var user = await _userRepository.Select.Where(a => a.UserName == input.UserName) .ToOneAsync(a => new { a.Id, a.Password, a.NickName, a.TenantId }); if (user == null) { return(ResponseOutput.NotOk("", 1)); } var password = MD5Encrypt.Encrypt32(input.Password); if (user.Password != password) { return(ResponseOutput.NotOk("", 2)); } AuthenticationProperties props = null; if (input.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1)) }; } ; var identityServerUser = new IdentityServerUser(user.Id.ToString()) { DisplayName = input.UserName }; await HttpContext.SignInAsync(identityServerUser, props); sw.Stop(); //写登录日志 var loginLogEntity = new LoginLogEntity() { Id = YitIdHelper.NextId(), TenantId = user.TenantId, CreatedUserId = user.Id, NickName = user.NickName, CreatedUserName = input.UserName, ElapsedMilliseconds = sw.ElapsedMilliseconds, Status = true }; await AddLoginLog(loginLogEntity); return(ResponseOutput.Ok()); }
/// <summary> /// 添加登录日志 /// </summary> /// <param name="log"></param> /// <returns></returns> public Task <bool> AddLoginLog(LoginLogEntity log) { return(_data.AddLoginLog(log)); }
/// <summary> /// 登录处理 /// </summary> private async Task <ResultModel <LoginResultModel> > Handle(UserNameLoginModel model, LoginLogEntity log) { var result = new ResultModel <LoginResultModel>(); var config = _configProvider.Get <AuthConfig>(); if (!config.LoginMode.UserName) { return(result.Failed("不允许使用用户名的登录方式")); } //检测验证码 var verifyCodeCheckResult = _verifyCodeProvider.Check(model); if (!verifyCodeCheckResult.Successful) { return(result.Failed(verifyCodeCheckResult.Msg)); } //查询账户 var account = await _repository.GetByUserName(model.UserName, model.AccountType); if (account == null) { return(result.Failed("账户不存在")); } if (log != null) { log.AccountId = account.Id; } //检测密码 var password = _passwordHandler.Encrypt(account.UserName, model.Password); if (!account.Password.Equals(password)) { return(result.Failed("密码错误")); } //检测账户 var accountCheckResult = account.Check(); if (!accountCheckResult.Successful) { return(result.Failed(accountCheckResult.Msg)); } //更新认证信息并返回登录结果 var resultModel = await UpdateAuthInfo(account, model, config); return(resultModel != null?result.Success(resultModel) : result.Failed()); }
public async Task <IResponseOutput> Login(LoginInputModel input) { if (!ModelState.IsValid) { return(ResponseOutput.NotOk(ModelState.Values.First().Errors[0].ErrorMessage)); } var sw = new Stopwatch(); sw.Start(); // check if we are in the context of an authorization request var context = await _interaction.GetAuthorizationContextAsync(input.ReturnUrl); var user = await _userRepository.Select.Where(a => a.UserName == input.UserName) .ToOneAsync(a => new { a.Id, a.Password, a.NickName }); if (user == null) { return(ResponseOutput.NotOk("", 1)); } var password = MD5Encrypt.Encrypt32(input.Password); if (user.Password != password) { return(ResponseOutput.NotOk("", 2)); } await _events.RaiseAsync(new UserLoginSuccessEvent(input.UserName, user.Id.ToString(), input.UserName, clientId : context?.ClientId)); // only set explicit expiration here if user chooses "remember me". // otherwise we rely upon expiration configured in cookie middleware. AuthenticationProperties props = null; if (AccountOptions.AllowRememberLogin && input.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; } ; // issue authentication cookie with subject ID and username var isuser = new IdentityServerUser(user.Id.ToString()) { DisplayName = input.UserName }; await HttpContext.SignInAsync(isuser, props); sw.Stop(); //写登录日志 var loginLogEntity = new LoginLogEntity() { CreatedUserId = user.Id, NickName = user.NickName, CreatedUserName = input.UserName, ElapsedMilliseconds = sw.ElapsedMilliseconds, Status = true }; await AddLoginLog(loginLogEntity); return(ResponseOutput.Ok()); /* * if (context != null) * { * if (await _clientStore.IsPkceClientAsync(context.ClientId)) * { * // if the client is PKCE then we assume it's native, so this change in how to * // return the response is for better UX for the end user. * return this.LoadingPage("Redirect", input.ReturnUrl); * } * * // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null * return Redirect(input.ReturnUrl); * } * * // request for a local page * if (Url.IsLocalUrl(input.ReturnUrl)) * { * return Redirect(input.ReturnUrl); * } * else if (string.IsNullOrEmpty(input.ReturnUrl)) * { * return Redirect("~/"); * } * else * { * // user might have clicked on a malicious link - should be logged * throw new Exception("invalid return URL"); * } * * await _events.RaiseAsync(new UserLoginFailureEvent(input.UserName, "invalid credentials", clientId: context?.ClientId)); * ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage); */ }