public void Insert(UserLoginLog model) { using (var con = WriteConnection()) { con.Execute(@"INSERT INTO UserLoginLog(UserAccountId,IP,Timestamp) VALUES(@UserAccountId,@IP,@Timestamp);", model); } }
private UserLoginLog prepareLog(HttpContext ctx, string email) { string browserAgent = Helper.GetRequestAgent(ctx); int browserAgentID = 0; try { string friendlyName = Helper.GetBrowserName(ctx); using (var _lu = new BegiumLogUnit()) { browserAgentID = _lu.BrowserAgentUnit.GetBrowserAgentID(browserAgent, friendlyName); } } catch (Exception ex) { _log.Error("Unable to prepare UserLoginLog", ex); } UserLoginLog log = new UserLoginLog() { Login = email, IsSuccess = false, DateLogin = DateTime.Now.ToUniversalTime(), RemoteIP = Helper.GetRequestIP(ctx), Domain = Helper.GetRequestDomain(ctx), BrowserAgentID = short.Parse(browserAgentID.ToString()) }; return(log); }
public List <Claim> ValidateUser(UserLoginLog userLoginLog, out User user) { var result = default(List <Claim>); user = default(User); #if DEBUG if (userLoginLog.HostName == "localhost") { userLoginLog.HostName = DevConstants.Dev_Host_Name; } #endif var primaryDbContext = this.unitOfWork.GetIdentityDbContext(); var parmsCollection = new ParmsCollection(); result = primaryDbContext.ExecuteStoredProcedure <Claim>("[Core].[validateUserCredentials]", parmsCollection .AddParm("@userId", SqlDbType.Int, userLoginLog.UserId) .AddParm("@userName", SqlDbType.VarChar, userLoginLog.UserName) .AddParm("@password", SqlDbType.VarChar, userLoginLog.Password) .AddParm("@remoteIpAddress", SqlDbType.VarChar, userLoginLog.RemoteIPAddress) .AddParm("@localIpAddress", SqlDbType.VarChar, userLoginLog.LocalIPAddress) .AddParm("@appKey", SqlDbType.VarChar, userLoginLog.AppKey) ).ToList(); if (result.Any(r => r.ClaimType == "UserId")) { var userId = int.Parse(result.First(r => r.ClaimType == "UserId").ClaimValue); user = primaryDbContext.Users.First(emp => emp.UserId == userId); } return(result); }
public string Create(UserLoginLogPoco poco) { UserLoginLog entity = _mapper.Map <UserLoginLog>(poco); _userLoginLogs.InsertOne(entity); return(entity.Id); }
private void LoginLogWrite(BCEnterpriseContext db, UserLoginState userLoginState, EnterpriseData.Common.LoginStatus status, string description) { if (userLoginState == null) { return; } var loginLog = new UserLoginLog { UserID = userLoginState.UserID, UserName = userLoginState.UserName, Device = userLoginState.Device, IP = userLoginState.LoginIP, Status = (int)status, Description = description }; if (status == EnterpriseData.Common.LoginStatus.Login && userLoginState.LoginTime.HasValue) { loginLog.Time = userLoginState.LoginTime.Value; } else { loginLog.Time = ML.BC.EnterpriseData.Model.Extend.DBTimeHelper.DBNowTime(db); } LoginLogWrite(db, loginLog); }
private void ForceLogout(BCEnterpriseContext db, int roleId, EnterpriseData.Common.LoginStatus status, string description) { var loginStateList = (from ur in db.UserRoles where ur.RoleID == roleId && !ur.Deleted join uls in db.UserLoginStates on ur.UserID equals uls.UserID select uls).ToList(); var dbNowTime = ML.BC.EnterpriseData.Model.Extend.DBTimeHelper.DBNowTime(db); loginStateList.ForEach(n => { var loginLog = new UserLoginLog { UserID = n.UserID, UserName = n.UserName, IP = n.LoginIP, Device = n.Device, Time = dbNowTime, Description = description, Status = (int)status }; db.UserLoginLogs.Add(loginLog); db.UserLoginStates.Remove(n); }); db.SaveChanges(); }
public ActionResult <MessageModel <RegisterResponseDTO> > Login([FromBody] LoginUserRequest loginRequest) { if (!ModelState.IsValid) { return(BadRequest()); } var loginUserRegistger = new UserRegisterType() { AuthPlatformId = loginRequest.userId, RegisterType = (byte)loginRequest.loginType }; dynamic verifiedData = userService.VerifyUserInfo(loginRequest.accessToken, loginRequest.permissions, loginUserRegistger).Result; if (verifiedData == null || verifiedData["name"] == null || verifiedData["email"] == null) { return(Unauthorized(new MessageModel <Object> { Status = (int)HttpStatusCode.Unauthorized, Success = false, Msg = "Unauthorized", Data = null })); } loginUserRegistger.Name = verifiedData["name"].ToString(); loginUserRegistger.Email = verifiedData["email"].ToString(); if (userService.GetUserInfo(loginUserRegistger).Result == null) { userService.AddNewUserInfo(loginUserRegistger).Wait(); } var loginUser = userService.GetUserInfo(loginUserRegistger).Result; var accessToken = this.jwtHandler.CreateAccessToken((int)loginUser.Id, loginUser.Email, loginUser.Name); var remoteIpAddress = HttpContext.Connection.RemoteIpAddress; UserLoginLog loginLog = new UserLoginLog { Ip = remoteIpAddress.ToString(), LoginType = (byte)loginRequest.loginType, LoginTime = DateTime.UtcNow, UserId = loginUser.Id }; userLoginLogService.AddLoginLog(loginLog); return(Ok(new MessageModel <RegisterResponseDTO> { Data = new RegisterResponseDTO() { Jwt = accessToken.Token, kycStatus = (short)loginUser.KycStatus } })); }
public virtual async Task <UserLoginLog> CreateAsync(UserLoginLog userLoginLog, CancellationToken cancellationToken) { if (userLoginLog == null) { throw new ArgumentNullException(nameof(userLoginLog)); } return(await Store.CreateAsync(userLoginLog, cancellationToken)); }
private void SaveUserLoginLog(UserLoginLog log, Core.Common.Security.EnumLoginStatus status) { log.Status = status; log.StatusDisplayString = log.Status.DisplayName(); DB.Repository <UserLoginLog>().Create(log); DB.Save(); }
private bool loginNormalUser(HttpContext ctx, string email, string pwd) { UserLoginLog log = prepareLog(ctx, email); bool result = false; using (var _u = new BegiumUnit()) { User uModel = _u.UserUnit.GetByLogin(email); if (uModel == null) { return(result); } string hashedPwd = Util.Helper.GetSHA256Hash(pwd, uModel.SaltPassword); User uInfo = _u.UserUnit.GetByLogin(email, hashedPwd); using (var _lu = new BegiumLogUnit()) { if (uInfo != null) { // write log log.IsSuccess = true; log.UserID = uInfo.UserID; _lu.UserLoginLogUnit.Insert(log, true); // update last login _u.UserUnit.UpdateEach(x => x.UserID == uInfo.UserID, x => x.DateLastLogin = DateTime.Now.ToUniversalTime(), true); // get user profile pic var img = _u.ImageUnit.GetUniqueImage(uInfo.UserID, Core.ImageType.User); if (img != null) { uInfo.ProfileImgURL = img.URL; } // get agencyName and branchName string agencyName = ""; string branchName = ""; _u.UserUnit.GetBranchNameAgencyNameByUserID(uInfo.AgencyID, uInfo.UserID, ref agencyName, ref branchName); uInfo.AgencyName = agencyName; uInfo.BranchName = branchName; // set user session ctx.Session["CURRENT_USER_INFO"] = uInfo; result = true; } else { // write log log.UserID = 0; _lu.UserLoginLogUnit.Insert(log, true); } } } return(result); }
private void LoginLogWrite(BCEnterpriseContext db, UserLoginLog loginLog) { if (loginLog == null) { return; } db.UserLoginLogs.Add(loginLog); db.SaveChanges(); }
public string Create(UserLoginLogPoco poco) { UserLoginLog entity = _mapper.Map <UserLoginLog>(poco); entity.Id = Guid.NewGuid().ToString(); _context.SaveAsync(entity); return(entity.Id); }
/// <summary> /// 创建 /// </summary> /// <param name="parameter">参数</param> public async Task CreateAsync(UserLoginLogParameter parameter) { var entity = new UserLoginLog(); parameter.MapTo(entity); entity.Init(); entity.CreationTime = DateTime.Now; await UserLoginLogRepository.AddAsync(entity); }
public void AddUserLoginLog(UserLoginLogInformation logInfo) { var userLoginLog = new UserLoginLog { UserLoginLogIdentificator = _keyGenerator.GenerateNewId(), LogData = logInfo }; _logRepository.AddUserLoginLog(userLoginLog); }
public async Task <UserLoginLog> CreateAsync(UserLoginLog organization, CancellationToken cancellationToken) { if (organization == null) { throw new ArgumentNullException(nameof(organization)); } Context.Add(organization); await Context.SaveChangesAsync(cancellationToken); return(organization); }
private void AddUserLoginLog(UserLoginServerTicketDTO ticket, EnumLoginType loginType, string loginAccount) { var loginlog = new UserLoginLog(); loginlog.UserID = ticket.UserID; loginlog.LoginType = loginType; loginlog.LoginTime = DateTime.Now; loginlog.LoginAccount = loginAccount; new UserLoginLogService(ticket.UserID).Insert(loginlog); }
private void MapClientLogInfo(ClientLogInfo clientLogInfo, UserLoginLog entity) { entity.UserAgent = clientLogInfo.UserAgent; entity.Platform = clientLogInfo.Platform; entity.PlatformVersion = clientLogInfo.PlatformVersion; entity.Browser = clientLogInfo.Browser; entity.BrowserVersion = clientLogInfo.BrowserVersion; entity.Ip = clientLogInfo.Ip; entity.Country = clientLogInfo.Country; entity.City = clientLogInfo.City; }
public void AddUserLoginLog(ApplicationUser user) { var userLoginLog = new UserLoginLog { Ip = ClientIpAddress, Address = string.Empty, BrowserInfo = string.Empty, User = user }; _userLoginLog.AddAndSave(userLoginLog); }
/// <summary> /// 新增登录日志 /// </summary> /// <param name="ip"></param> /// <param name="userId"></param> /// <returns></returns> public async Task AddUserLoginLog(string ip, string userId) { var entity = new UserLoginLog { Ip = ip, LoginTime = DateTime.Now, UserId = userId }; await _userLoginLogRepository.Insert(entity); await _userLoginLogRepository.Save(); }
private void Insert() { //插入数据 UserLoginLog ull = new UserLoginLog { User_ID = "a100", UserName = "******", IP = "20190312", TimeStamp = Guid.NewGuid().ToString("N").Substring(0, 12) }; ctx.UserLoginLogs.InsertOnSubmit(ull); ctx.SubmitChanges(); }
public void SaveLoginSession(long userId, string sessionId, DateTime loginDateTime) { var domain = new UserLoginLog { LoginDateTime = loginDateTime, SessionId = sessionId, UserId = userId, IsNew = true }; _userLogRepository.Save(domain); }
public UserLoginLog CreateEntityFromRequest(SignUpRequest request, User user) { var entity = new UserLoginLog(); MapClientLogInfo(request.ClientLogInfo, entity); entity.OrganizationUid = user.OrganizationUid; entity.OrganizationName = user.OrganizationName; entity.UserUid = user.Uid; entity.UserName = request.FirstName + " " + request.LastName; return(entity); }
public JsonWebToken CreateToken(int userId, string userName, string authCode, string password, DateTime expiry) { JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); var httpContextAccessor = DIContainer.ServiceLocator.Instance.Get <IHttpContextAccessor>(); var userBusinessAccess = DIContainer.ServiceLocator.Instance.Get <IUserBusinessAccess>(); var url = httpContextAccessor.HttpContext.Request.Host.HasValue ? httpContextAccessor.HttpContext.Request.Host.Host : string.Empty; var userLoginLog = new UserLoginLog { UserId = userId, HostName = url, UserName = (password == "000appauth0000") ? "" : userName, Password = password, AppKey = (password == "000appauth0000") ? userName : "", LocalIPAddress = (httpContextAccessor.HttpContext.Connection.LocalIpAddress != null) ? httpContextAccessor.HttpContext.Connection.LocalIpAddress.ToString() : "Not exists", RemoteIPAddress = (httpContextAccessor.HttpContext.Connection.RemoteIpAddress != null) ? httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString() : "Not exists" }; var claims = userBusinessAccess.ValidateUser(userLoginLog, user: out var user); if (claims != null && claims.Count > 0 && claims.Any(c => c.ClaimType == "Status" && c.ClaimValue == "Success")) { ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user.UserName, "jwt")); identity.AddClaims(claims.Where(c => c.ClaimType != "Status").Select(c => new System.Security.Claims.Claim(c.ClaimType, c.ClaimValue)).ToList()); SecurityToken token = tokenHandler.CreateJwtSecurityToken(new SecurityTokenDescriptor { Audience = _audience, Issuer = _issuer, SigningCredentials = new SigningCredentials(_key, _algorithm), Expires = expiry.ToUniversalTime(), Subject = identity }); return(new JsonWebToken { access_token = tokenHandler.WriteToken(token), expires_in = 3600, UserId = claims.Any(c => c.ClaimType == "UserId") ? int.Parse(claims.First(c => c.ClaimType == "UserId").ClaimValue) : 0 }); } else { throw new AccessViolationException("Invalid credentials"); } }
private UserLoginLog SaveLoginInfo(long userid, string sessionId, string deviceKey) { var userLoginLog = new UserLoginLog { UserId = userid, LogInDateTime = DateTime.Now, BrowserSession = sessionId, BrowserName = " ", SessionIP = ((HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.UserHostAddress, DeviceKey = deviceKey, RefferedUrl = Request.RequestUri }; return(_uniqueItemRepository.Save(userLoginLog)); }
public async Task <bool> DoWork(User user, UserLoginLog userLoginLog) { await _transactionalExecutor.ExecuteAsync <bool>(async connection => { _userRepository.SetSqlExecutorForTransaction(connection); _userLoginLogRepository.SetSqlExecutorForTransaction(connection); await _userRepository.Update(user.Id, user); await _userLoginLogRepository.Insert(user.Id, userLoginLog); return(true); }); return(true); }
public UserLoginLog CreateEntityFromRequest(LogOnRequest request, User user) { var entity = new UserLoginLog(); MapClientLogInfo(request.ClientLogInfo, entity); entity.OrganizationId = user.OrganizationId; entity.OrganizationUid = user.OrganizationUid; entity.OrganizationName = user.OrganizationName; entity.UserId = user.Id; entity.UserUid = user.Uid; entity.UserName = user.Name; return(entity); }
public UserLoginLog SaveLoginInfo(long userId, string userName, string browserSessionId, string browserName, string sessionIp, Uri refferedUrl) { var userLoginLog = new UserLoginLog { UserId = userId, LogInDateTime = DateTime.Now, BrowserSession = browserSessionId, BrowserName = browserName, SessionIP = sessionIp, RefferedUrl = refferedUrl }; _singleSessionHelper.CreateAndStoreSessionToken(userName, browserSessionId); return(_uniqueItemRepository.Save(userLoginLog)); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } UserLoginLog log = new UserLoginLog(); log.AttempTime = DateTime.Now; log.IP = Request.ServerVariables["REMOTE_ADDR"]; log.UserName = model.UserName; var user = UserManager.FindByName(model.UserName); if (user != null && user.IsEnabled == false) { ModelState.AddModelError("", "此帳號已經被取消啟用,請聯絡管理人員來啟用帳號"); SaveUserLoginLog(log, Core.Common.Security.EnumLoginStatus.NotEnabled); return(View(model)); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: SaveUserLoginLog(log, Core.Common.Security.EnumLoginStatus.Success); return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "帳號密碼錯誤"); SaveUserLoginLog(log, Core.Common.Security.EnumLoginStatus.WrongPassword); return(View(model)); } }
/// <summary> /// 创建注册日志 /// </summary> /// <param name="context">当前请求上下文应答实例</param> /// <param name="acount">账号信息</param> /// <param name="uAccount">用户账户信息</param> private static void CreateSignUpLog(DataContext context, Account acount, UserAccount uAccount) { UserLoginLog log = new UserLoginLog { UserId = uAccount.UserId, LogType = 1, NetworkType = (int)acount.NetworkType, AccountChannel = (int)acount.AccountChannel, AppChannel = context.ReqChannel, AppVersion = acount.Version, DeviceId = context.DeviceId, LoginAccount = uAccount.UserName, CreateDate = DateTime.Now }; LogsBiz.CreateLogs <UserLoginLog>(log); }
public LoginOM Login(LoginIM im, string deviceNumber, string ip) { var user = CheckUser(im.CountryId, im.Cellphone, im.Password); var isNeedGoogleVerify = ValidationFlagComponent.CheckSecurityOpened(user.ValidationFlag, ValidationFlag.GooogleAuthenticator); var deviceList = new UserDeviceDAC().GetUserDeviceByAccountId(user.Id); var isNewDevice = deviceList.All(item => item.DeviceNumber != deviceNumber); if (!deviceList.Any()) { if (!string.IsNullOrEmpty(user.Pin) && !user.IsBindingDevice) { new UserDeviceDAC().Insert(new UserDevice() { DeviceNumber = deviceNumber, Name = " ", UserAccountId = user.Id, LastActiveTime = DateTime.UtcNow }); new UserAccountDAC().UpdateIsBindingDevice(user.Id); isNewDevice = false; } } if ((isNewDevice && !string.IsNullOrEmpty(user.Pin)) || isNeedGoogleVerify) { return(new LoginOM() { IsNeedGoogleVerify = isNeedGoogleVerify, IsNewDevice = isNewDevice, UserInfo = GetUserVerifyItems(user) }); } Task.Factory.StartNew(() => { var model = new UserLoginLog { UserAccountId = user.Id, IP = ip, Timestamp = DateTime.UtcNow, }; new UserLoginLogDAC().Insert(model); }); return(IssueAccessToken(user)); }
public int IndexOf(UserLoginLog entity) { return base.IndexOf(entity); }
public void Add(UserLoginLog entity) { base.Add(entity); }
public bool Remove(UserLoginLog entity) { return base.Remove(entity); }
public void Insert(int index, UserLoginLog entity) { base.Insert(index, entity); }
/// <summary> /// 사용자 Login 이력을 DB에 기록합니다. (Sessionless를 사용하므로 함수명이 Insert 로 시작합니다) /// </summary> /// <param name="product">로그인한 제품 정보</param> /// <param name="user">로그인 사용자</param> /// <param name="department">로그인 사용자의 부서</param> /// <param name="localeKey">로그인 사용자의 Locale 정보</param> /// <param name="loginTime">로그인 시각</param> /// <param name="exAttr">확장 속성 정보</param> public void InsertUserLoginLog(Product product, User user, Department department = null, string localeKey = null, DateTime? loginTime = null, string exAttr = null) { product.ShouldNotBeNull("product"); user.ShouldNotBeNull("user"); var loginLog = new UserLoginLog(product.Code, user.Company.Code, user.LoginId, localeKey, loginTime) { ProductName = product.Name, CompanyName = user.Company.Name, DepartmentCode = (department != null) ? department.Code : null, DepartmentName = (department != null) ? department.Name : null, UserCode = user.Code, UserName = user.Name, ExAttr = exAttr }; if(log.IsDebugEnabled) log.Debug(@"사용자 로그인 이력 정보를 생성합니다... " + loginLog); // NOTE : Log 정보를 기록할 때에는 Session에 저장할 필요없고, 성능을 위해서 StatelessSession를 사용합니다. // loginLog.InsertStateless(Session); }
/// <summary> /// 사용자 Login 이력을 DB에 기록합니다. (Sessionless를 사용하므로 함수명이 Insert 로 시작합니다) /// </summary> /// <param name="productCode">제품 코드</param> /// <param name="companyCode">사용자 소속 회사 코드</param> /// <param name="loginId">로그인 Id</param> /// <param name="localeKey">로그인 사용자의 Locale 정보</param> /// <param name="loginTime">로그인 시각</param> public void InsertUserLoginLog(string productCode, string companyCode, string loginId, string localeKey = null, DateTime? loginTime = null) { var loginLog = new UserLoginLog(productCode, companyCode, loginId, localeKey, loginTime); if(log.IsDebugEnabled) log.Debug(@"사용자 로그인 이력 정보를 생성합니다... " + loginLog); // NOTE : Log 정보를 기록할 때에는 Session에 저장할 필요없고, 성능을 위해서 StatelessSession를 사용합니다. // loginLog.InsertStateless(Session); }
public bool Contains(UserLoginLog entity) { return base.Contains(entity); }