public async Task <JsonResult> Submit(UserLoginInput model) { model.Password = _3DESEncrypt.Encrypt(model.Password); var info = await _systemUserLogic.CheckUserByCodeAndPwdAsync(model); if (info.Data != null) { var prin = new PrincipalUser() { UserId = Guid.Parse(info.Data.UserId), Code = info.Data.Code, Name = info.Data.Name, IsAdmin = info.Data.IsAdmin, RoleName = info.Data.RoleName, ImgUrl = info.Data.ImgUrl }; if (prin.Code == "admin") { prin.RoleName = "超级管理员"; } //写入Cookie信息 AuthenticationExtension.SetAuthCookie(prin); //写入日志 var logHandler = new LoginLogHandler(info.Data.UserId, info.Data.Code, info.Data.Name, (int)EnumLoginType.账号密码登录); logHandler.WriteLog(); } return(Json(info)); }
//Purpose: To proces the login requests of clients into our application. //Input: 'userInfo' object of type 'UserInput.cs' //Output: a boolean variable representing the status of the login request. public dynamic Login(UserLoginInput userInfo) { ILoginRepository objLoginRepository = new LoginRepository(); var result = objLoginRepository.Login(userInfo.uName, userInfo.uPassword); return(result); }
public async Task <string> login(UserLoginInput _input) { using (NpgsqlConnection connection = new NpgsqlConnection(_config.GetConnectionString("postgres"))) { string sql = "Select * from \"user\" where email= @email"; User resultUser = await connection.QueryFirstOrDefaultAsync <User>(sql, new { email = _input.email }); if (resultUser == null) { throw new UnauthorizedAccessException("Incorrect Credentials"); } else { byte[] hashbytes = Convert.FromBase64String(resultUser.password); byte[] salt = new byte[16]; Array.Copy(hashbytes, 0, salt, 0, 16); Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(_input.password, salt); byte[] inputPasswordBytes = generator.GetBytes(16); for (int i = 0; i < 16; i++) { if (hashbytes[16 + i] != inputPasswordBytes[i]) { throw new UnauthorizedAccessException("Incorrect Credentials"); } } //generate token and store user id in it return(_jwtService.generateToken(resultUser.id.ToString())); } } }
/// <summary> /// 根据用户名和密码查询用户信息 /// 1:用户登录使用 /// </summary> /// <param name="input">用户名、密码等</param> /// <returns></returns> public Task <UserLoginOutput> CheckUserByCodeAndPwd(UserLoginInput input) { var sql = @"select sysUser.UserId,sysUser.Code,sysUser.Name,sysUser.IsAdmin,role.Name RoleName,sysUser.IsFreeze,sysUser.FirstVisitTime,sysUser.ImgUrl from Sys_User sysUser left join Sys_PermissionUser per on sysUser.UserId=per.PrivilegeMasterUserId left join Sys_Role role on role.RoleId=per.PrivilegeMasterValue where sysUser.Code=@Code and sysUser.Password=@pwd"; return(SqlMapperUtil.FirstOrDefault <UserLoginOutput>(sql, new { Code = input.Code, pwd = input.Password })); }
public ActionResult Login(UserLoginInput userInput) { if (!userLogic.IsValid(userInput)) { return(Content("Login Failed! Incorrect username or password.")); } Session["username"] = userInput.UserName; FormsAuthentication.SetAuthCookie(userInput.UserName, true); return(Content("Y")); }
public void TestLogin_Controller() { var testLogin = GetTestLogin(); var controller = new LoginController(testLogin); UserLoginInput user = new UserLoginInput(); user.uName = testLogin[0].name; user.uPassword = testLogin[0].pwd; var result = controller.Login(user); Assert.IsNull(result); }
public UserLoginOutput GetUserInformation(UserLoginInput userInput) { UserLoginOutput result = new UserLoginOutput(); // check user db.Configuration.LazyLoadingEnabled = true; var user = db.Users.FirstOrDefault(x => x.LoginName == userInput.UserName && x.Password == userInput.Password); result.GetTransferData(user); result.Roles = db.Database.SqlQuery <string>("sp_GetUserPermission @UserID, @ApplicationCode", new SqlParameter("UserID", user.UserID), new SqlParameter("ApplicationCode", userInput.ApplicationCode)).ToList(); return(result); }
public async Task <IActionResult> Login(UserLoginInput model) { model.Password = _3DESEncrypt.Encrypt(model.Password); var info = await _systemUserLogic.CheckUserByCodeAndPwdAsync(model); if (info.Data != null) { var prin = new PrincipalUser() { UserId = info.Data.Id, Code = info.Data.Code, Name = info.Data.Name, IsAdmin = info.Data.IsAdmin, //TODO先注释 //RoleName = info.Data.RoleName, ImgUrl = info.Data.ImgUrl }; if (prin.Code == "admin") { prin.RoleName = "超级管理员"; } //写入Cookie信息 AuthenticationExtension.SetAuthCookie(prin); //写入日志 var logHandler = new LoginLogHandler(info.Data.Id.ToString(), info.Data.Code, info.Data.Name, (int)EnumLoginType.账号密码登录); logHandler.WriteLog(); } if (info.ResultSign == ResultSign.Successful) { if (Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } else if (string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect("~/")); } else { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } } else { ModelState.AddModelError(string.Empty, info.Message); } return(View()); }
public ActionResult <UserLoginOutput> Login(UserLoginInput input) { if (input.Username.Equals("admin") && input.Password.Equals("admin")) { var(expire, accessToken) = GetToken(input.Username); var output = new UserLoginOutput { AccessToken = accessToken, Expire = expire }; return(output); } return(Unauthorized()); }
public async Task <JsonResult> Submit(UserLoginInput input) { var operateStatus = new OperateStatus(); try { //获取生成验证码的结果值 var verifyCode = VerifyCodeUtil.GetVerifyCode(); //判断录入验证码和生成的验证码值是否相等 if (input.Verify != verifyCode) { operateStatus.ResultSign = ResultSign.Error; operateStatus.Message = "验证码错误"; return(Json(operateStatus)); } //验证数据库信息 var info = await _userInfoLogic.CheckUserByCodeAndPwd(input); if (info.Data != null) { var principalUser = new PrincipalUser { UserId = info.Data.UserId, Code = info.Data.Code, Name = info.Data.Name, OrganizationId = info.Data.OrganizationId, OrganizationName = info.Data.OrganizationName }; principalUser.LoginId = Guid.NewGuid(); //写入Cookie信息 FormAuthenticationExtension.SetAuthCookie(principalUser.UserId.ToString(), principalUser, input.Remberme); //是否具有返回路径 if (Url.IsLocalUrl(input.ReturnUrl) && input.ReturnUrl.Length > 1 && input.ReturnUrl.StartsWith("/") && !input.ReturnUrl.StartsWith("//") && !input.ReturnUrl.StartsWith("/\\")) { info.ResultSign = ResultSign.Successful; info.Message = input.ReturnUrl; } //写入日志 WriteLoginLog(principalUser.LoginId); } return(Json(info)); } catch (Exception ex) { operateStatus.Message = ex.Message; return(Json(operateStatus)); } }
/// <summary> /// 根据用户名和密码查询用户信息 /// 1:用户登录使用 /// </summary> /// <param name="input">登录名、密码等</param> /// <returns></returns> public Task <SystemUserOutput> CheckUserByCodeAndPwd(UserLoginInput input) { var sql = new StringBuilder(); sql.Append(@"SELECT UserId,userInfo.Code,userInfo.Name,FirstVisitTime,userInfo.IsFreeze,userInfo.State,org.Name OrganizationName,org.OrganizationId FROM [System_UserInfo] userInfo LEFT JOIN System_PermissionUser perUser on userInfo.UserId=perUser.PrivilegeMasterUserId and perUser.PrivilegeMaster=1 LEFT JOIN System_Organization org on perUser.PrivilegeMasterValue=org.OrganizationId "); sql.Append("WHERE userInfo.Code=@code AND userInfo.Password=@pwd"); return(SqlMapperUtil.SqlWithParamsSingle <SystemUserOutput>(sql.ToString(), new { code = input.Code, pwd = input.Pwd })); }
/// <summary> /// 登陆 /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <UserLoginOutput> LoginAsync(UserLoginInput input) { User user = await CurrentRepository .FirstOrDefaultAsync(u => u.UserName == input.UserName) ?? throw new UserFriendlyException("用户名和密码不匹配"); if (user.Password != input.Password) { throw new UserFriendlyException("用户名和密码不匹配"); } if (!user.CanUse) { throw new UserFriendlyException("当前账号不可用,请联系管理员"); } return(_mapper.Map <UserLoginOutput>(user)); }
public async Task <IActionResult> Login( [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] UserLoginInput input ) { var user = await GetUserToLogin(input); if (user == null) { return(NotFound()); } var sessionId = Guid.NewGuid().ToString("N"); var issueTimestamp = DateTime.UtcNow; var expirationTimestamp = issueTimestamp.AddDays(1); var securityHandler = new JwtSecurityTokenHandler(); var jwtKey = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("JWT_USER_TOKEN_SECRET")); var jwtDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.GivenName, user.Name), new Claim(ClaimTypes.Surname, user.Surname), new Claim(JwtRegisteredClaimNames.Jti, sessionId) }), Issuer = Startup.GetJwtIssuerName(), IssuedAt = issueTimestamp, Expires = expirationTimestamp, SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(jwtKey), SecurityAlgorithms.HmacSha512Signature ) }; var token = securityHandler.CreateToken(jwtDescriptor); Logger.LogDebug("Login performed for user {0} with session ID {1}", user.Id, sessionId); return(Ok(new UserLoginOutput( user.Id.ToString(), securityHandler.WriteToken(token), expirationTimestamp, user.VerificationToken == null ))); }
public async Task <IActionResult> Login(UserLoginInput input) { if (!ModelState.IsValid) { return(View(input)); } UserLoginOutput output; try { output = await _userService.LoginAsync(input); } catch (UserFriendlyException ue) { ModelState.AddModelError("UserName", ue.Message); return(View(input)); } var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, output.ID.ToString()), new Claim(ClaimTypes.Name, output.Name), new Claim("UserName", output.UserName) }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); AuthenticationProperties authProperties = new AuthenticationProperties(); if (input.RememberMe) { authProperties.IsPersistent = true; } else { authProperties.ExpiresUtc = DateTime.UtcNow.AddMinutes(20); } HttpContext.Session.Set <UserLoginOutput>("LoginUser", output); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return(Redirect("/Home")); }
public ActionResult <Player> login([FromBody] UserLoginInput userLogin) { PlayerManager PM = new PlayerManager(); Player player = PM.selectPlayerByUsername(userLogin.Username); if (player == null) { return(NotFound()); } if (player.Password == userLogin.Password) { return(player); } else { return(NotFound()); } }
public ResultMessage <UserLoginOutput> Login(UserLoginInput loginInput) { try { var loginResult = GetLoginResult( loginInput.AccountName, loginInput.Password ); return(ResponseUtils.DataResult(new UserLoginOutput() { LoginResultMsg = loginResult.LoginResultMsg, Ticket = loginResult.Token })); } catch (Exception ex) { return(ResponseUtils.ErrorResult <UserLoginOutput>(ex.Message)); } }
public UserLoginOutput Login(UserLoginInput input) { return(base.ExecuteWithExceptionHandledOperation(() => { //throw new ArgumentNullException(); if (input.Email == "*****@*****.**" && input.Password == "123") { return new UserLoginOutput() { Id = "1", OperationResult = new OperationResult() }; } else { throw new CustomException("200", "Kullanıcı adı veya şifre yanlış"); } })); }
public async Task <IActionResult> Login(UserLoginInput userLoginInput) { var userFromRepo = await _repo.Login(userLoginInput.UserName.ToLower(), userLoginInput.Password); if (userFromRepo == null) { return(Unauthorized()); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), new Claim(ClaimTypes.Name, userFromRepo.UserName) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptior = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptior); var ppUrl = await _mediator.Send(new UserProfilePhotoQuery { UserId = userFromRepo.Id }); return(Ok(new { token = tokenHandler.WriteToken(token), ppUrl, gender = userFromRepo.Gender })); }
public OutPutDTO Login([FromBody] UserLoginInput user) { if (!ModelState.IsValid) { return(new OutPutDTO(false, Constants.STATUS_CODE.FAILURE, Constants.STATUS_MESSAGE.FAILURE, null)); } try { if (userBusiness.CheckLogin(user)) { var output = userBusiness.GetUserInformation(user); return(new OutPutDTO(true, Constants.STATUS_CODE.SUCCESS, Constants.STATUS_MESSAGE.SUCCESS, output)); } else { return(new OutPutDTO(false, Constants.STATUS_CODE.FAILURE, Constants.STATUS_MESSAGE.FAILURE, null)); } } catch (Exception ex) { return(new OutPutDTO(false, Constants.STATUS_CODE.EXCEPTION, Constants.STATUS_MESSAGE.EXCEPTION + ex.Message, null)); } }
/// <summary> /// 根据登录代码和密码查询用户信息 /// </summary> /// <param name="input">登录名、密码等</param> /// <returns></returns> public async Task <OperateStatus <SystemUserOutput> > CheckUserByCodeAndPwd(UserLoginInput input) { var operateStatus = new OperateStatus <SystemUserOutput>(); //将传入的密码加密 var encryptPwd = DEncryptUtil.Encrypt(input.Pwd, GlobalParams.Get("pwdKey").ToString()); //查询信息 input.Pwd = encryptPwd; var data = await _userInfoRepository.CheckUserByCodeAndPwd(input); //是否存在 if (data == null) { operateStatus.ResultSign = ResultSign.Error; operateStatus.Message = ResourceSystem.用户名或密码错误; return(operateStatus); } //是否冻结 if (data.IsFreeze) { operateStatus.ResultSign = ResultSign.Error; operateStatus.Message = ResourceSystem.登录用户已冻结; return(operateStatus); } //成功 operateStatus.ResultSign = ResultSign.Successful; operateStatus.Message = "/"; operateStatus.Data = data; if (data.FirstVisitTime == null) { //更新用户最后一次登录时间 _userInfoRepository.UpdateFirstVisitTime(new IdInput(data.UserId)); } //更新用户最后一次登录时间 _userInfoRepository.UpdateLastLoginTime(new IdInput(data.UserId)); return(operateStatus); }
/// <summary> /// Gets the user to login, either through login data or through the already authenticated basic authentication. /// </summary> private async Task <User> GetUserToLogin(UserLoginInput input) { if (User.GetUserId(out var loggedInUser)) { Logger.LogDebug("User {0} already logged in", loggedInUser); return(await Mongo.GetUserById(loggedInUser)); } if (input == null) { return(null); } var user = await Mongo.GetUserByEmail(input.Email); if (user == null) { Logger.LogTrace("User {0} does not exist", input.Email); // Delay response to throttle await Task.Delay(1050); return(null); } if (!BCrypt.Net.BCrypt.Verify(input.Password, user.PasswordHash)) { Logger.LogTrace("User {0} password not correct", input.Email); // Delay response to throttle await Task.Delay(1000); return(null); } return(user); }
public async Task <ActionResult <UserLoginResponse> > Login(UserLoginInput _input) { try{ string token = await userService.login(_input); return(Ok(new UserLoginResponse { isSuccess = true, payload = new UserLoginResponseData { token = token } })); }catch (UnauthorizedAccessException ex) { return(Unauthorized(new UserLoginResponse { error = new ApiError { msg = ex.Message } })); }catch (Exception ex) { return(BadRequest(new UserLoginResponse { error = new ApiError { msg = ex.Message } })); } }
public bool IsValid(UserLoginInput userInput) { return(userDao.GetUser(userInput).Count > 0 ? true : false); }
public UserLoginOutput Login(UserLoginInput userLoginInput) { return(_business.Login(userLoginInput)); }
public async Task <IActionResult> ProcessLogin(UserLoginInput input) { //if the ModelState is invalid return the user to the CreateProject page and show them the validation errors if (!ModelState.IsValid) { List <string> errors = ModelState.Values.SelectMany(p => p.Errors.Select(x => x.ErrorMessage)).ToList(); TempData.Add("ProcessLoginError", errors); return(RedirectTo("Home", "UserLogin")); } var resultList = new WorkHourTrackerListResult() { Errors = new List <string>(), WorkHourTrackList = new List <dynamic>() }; try { //Transform the object into it's Model.Entities counter part for the other layers var userLoginDatabaseInput = new UserLoginDatabaseInput() { UserName = input.UserName, Password = input.Password }; var result = await _IUserAccount.UserLogin(userLoginDatabaseInput); //set up a dictionary containing the user's information var userDictionary = new Dictionary <string, object>() { { "userName", result.UserName }, { "userPassword", result.UserPassword }, { "userGuid", result.UserGuid.ToString() }, { "userRole", result.UserRole }, { "employeeGuid", result.EmployeeGuid }, { "firstName", result.FirstName }, { "lastName", result.LastName } }; //Clear out the TempData before adding to avoid Key collisions TempData.Clear(); //foreach through the userDictionary and add the key/value to the TempData foreach (var keyValuePair in userDictionary) { TempData.Add(keyValuePair.Key, keyValuePair.Value); } //Mark all of the data inside TempData for rentention TempData.Keep(); } catch (InvalidLoginException) { resultList.Errors.Add("The user name or password you entered is incorrect, please try again."); TempData.Add("LoginErrors", resultList.Errors); return(RedirectTo("Home", "UserLogin")); } catch (Exception ex) { resultList.Errors.Add("An unexpected error occured."); resultList.Errors.Add($"Exception Message: {ex.Message}"); resultList.Errors.Add($"Base Exception: {ex.GetBaseException()}"); TempData.Add("LoginErrors", resultList.Errors); return(RedirectTo("Home", "UserLogin")); } //Login successful redirect to the index return(RedirectTo("Home", "Index")); }
public void UserLogin_StateUnderTest_ExpectedBehavior() { // Arrange var unitUnderTest = this.CreateService(); LoginAsHost("85261107946"); unitUnderTest.ObjectMapper = LocalIocManager.Resolve <Abp.ObjectMapping.IObjectMapper>(); unitUnderTest.UnitOfWorkManager = Resolve <IUnitOfWorkManager>(); unitUnderTest.UnitOfWorkManager.Begin(); UserLoginInput input1 = new UserLoginInput() { OTP = "1111", TelAreaCode = "852", PhoneNumber = "61107946", Password = "******" }; UserLoginInput input2 = new UserLoginInput() { OTP = null, TelAreaCode = null, PhoneNumber = null, Password = null }; UserLoginInput input3 = new UserLoginInput() { OTP = "1111", TelAreaCode = null, PhoneNumber = null, Password = null }; UserLoginInput input4 = new UserLoginInput() { OTP = "1111", TelAreaCode = "852", PhoneNumber = null, Password = null }; UserLoginInput input5 = new UserLoginInput() { OTP = "1111", TelAreaCode = "852", PhoneNumber = "61107946", Password = null }; UserLoginInput input6 = new UserLoginInput() { OTP = "", TelAreaCode = "", PhoneNumber = "", Password = "" }; UserLoginInput input7 = new UserLoginInput() { OTP = "1111", TelAreaCode = "", PhoneNumber = "", Password = "" }; UserLoginInput input8 = new UserLoginInput() { OTP = "1111", TelAreaCode = "852", PhoneNumber = "", Password = "" }; UserLoginInput input9 = new UserLoginInput() { OTP = "1111", TelAreaCode = "852", PhoneNumber = "61107946", Password = "" }; UserLoginInput input10 = new UserLoginInput() { OTP = null, TelAreaCode = "852", PhoneNumber = "61107946", Password = "******" }; // Act var result1 = unitUnderTest.UserLogin( input1); var result2 = unitUnderTest.UserLogin( input2); var result3 = unitUnderTest.UserLogin( input3); var result4 = unitUnderTest.UserLogin( input4); var result5 = unitUnderTest.UserLogin( input5); var result6 = unitUnderTest.UserLogin( input6); var result7 = unitUnderTest.UserLogin( input7); var result8 = unitUnderTest.UserLogin( input8); var result9 = unitUnderTest.UserLogin( input9); var result10 = unitUnderTest.UserLogin( input10); // Assert //Assert.True(result1.Status == TaskStatus.RanToCompletion && result1.Result.UserDto != null); Assert.True(result2.Status == TaskStatus.Faulted); Assert.True(result3.Status == TaskStatus.Faulted); Assert.True(result4.Status == TaskStatus.RanToCompletion && result4.Result.Message == "OTP validation fail"); Assert.True(result5.Status == TaskStatus.RanToCompletion && result5.Result.Message == "OTP validation fail"); Assert.True(result6.Status == TaskStatus.Faulted); Assert.True(result7.Status == TaskStatus.RanToCompletion && result7.Result.Message == "OTP validation fail"); Assert.True(result8.Status == TaskStatus.RanToCompletion && result8.Result.Message == "OTP validation fail"); Assert.True(result9.Status == TaskStatus.RanToCompletion && result9.Result.Message == "OTP validation fail"); Assert.True(result10.Status == TaskStatus.RanToCompletion && result10.Result.UserDto != null); }
public List <LAVA_USERS> GetUser(UserLoginInput userInput) { return(db.LAVA_USERS.Where(u => u.USERNAME == userInput.UserName && u.PASSWORD == userInput.Password).ToList()); }
/// <summary> /// 根据登录名和密码查询是否存在 /// </summary> /// <param name="input">登录名、密码等</param> /// <returns></returns> public async Task <OperateStatus <UserLoginOutput> > CheckUserByCodeAndPwdAsync(UserLoginInput input) { var operateStatus = new OperateStatus <UserLoginOutput>(); try { var data = await _systemUserRepository.CheckUserByCodeAndPwd(input); //是否存在 if (data == null) { operateStatus.ResultSign = ResultSign.Error; operateStatus.Message = ResourceSystem.用户名或密码错误; goto End; } if (data.IsFreeze) { operateStatus.ResultSign = ResultSign.Error; operateStatus.Message = ResourceSystem.登录用户已冻结; goto End; } operateStatus.ResultSign = ResultSign.Successful; operateStatus.Message = "登录成功!"; operateStatus.Data = data; if (data.FirstVisitTime == null) { //更新用户最后一次登录时间 await _systemUserRepository.UpdateFirstVisitTime(new IdInput(data.UserId)); } //更新用户最后一次登录时间 await _systemUserRepository.UpdateLastLoginTime(new IdInput(data.UserId)); } catch (Exception ex) { operateStatus.Message = string.Format(Chs.Error, ex.Message); operateStatus.ResultSign = ResultSign.Error; goto End; } End: return(operateStatus); }
public bool CheckLogin(UserLoginInput userInput) { bool isLoginSuccess = db.Users.Any(x => x.LoginName == userInput.UserName && x.Password == userInput.Password); return(isLoginSuccess); }
/// <summary> /// 用户登录信息 /// </summary> /// <param name="userInfo"></param> /// <returns></returns> public IHttpActionResult UserLogin([FromBody] UserLoginInput userInfo) { return(Ok()); }