public LoginResponseModel AuthenticateUser(LoginRequestModel input) { var response = new LoginResponseModel(); if (!this.ModelState.IsValid) { var errorMessage = this.ModelState.Values.First().Errors.First().ErrorMessage; response.Status = new Status(102, errorMessage); return response; } if (input == null) { response.Status = Status.MISSING_PARRAMETERS; return response; } ////get user by email var existUser = this.Users.SingleOrDefault(a => a.Email == input.Email); bool isValidPassword = false; if (existUser != null) { isValidPassword = AuthenticationUtil.IsValidPassword(existUser.Token, input.Password); } if (!isValidPassword) { response.Status = Status.INVALID_PASSWORD; return response; } var recreateToken = AuthenticationUtil.Encrypt(input.Password); existUser.Token = recreateToken; if (!String.IsNullOrEmpty(input.FanApp)) { existUser.FanApps = input.FanApp; } this.Users.Update(existUser); response.Status = Status.LOGIN_SUCCESFULLY; response.Token = recreateToken; return response; }
public async Task <ActionResult <LoginResponseModel> > LoginAsync(LoginRequestModel request) { var response = new LoginResponseModel(); var user = await this.userService .GetUserByUsernameAsync(request.Username); if (Object.Equals(user, null)) { response.Status = -1; response.Message = "Invalid Username Or Password."; return(Ok(response)); } var isValidPassword = PasswordHasher .VerifyHashedPassword(user.HashedPassword, request.Password); if (!isValidPassword) { response.Status = -1; response.Message = "Invalid Username Or Password."; return(Ok(response)); } var id = user.Id.ToString(); var username = request.Username; var userRole = ((UserRole)user.UserRole).ToString(); var jwt = this.jwtService .GenerateJwt(id, username, userRole); response.Status = 1; response.Message = "Success."; response.Jwt = jwt; return(Ok(response)); }
public async Task <AuthResponse> Login(LoginRequestModel model) { AuthUser user = await this.userManager.FindByEmailAsync(model.Email); if (user == null) { return(ValidationResponseFactory <AuthResponse> .FailureAuthResponse("Invalid email or password", AuthErrorCodes.InvalidUsernameOrPassword)); } else { if (this.userManager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success) { IList <Claim> claims = await this.userManager.GetClaimsAsync(user); IList <string> roles = await this.userManager.GetRolesAsync(user); foreach (string role in roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } string token = this.jwtService.GenerateBearerToken( this.apiSettings.JwtSettings.SigningKey, this.apiSettings.JwtSettings.Audience, this.apiSettings.JwtSettings.Issuer, user.Id, user.Email, claims); return(ValidationResponseFactory <AuthResponse> .SuccessAuthResponseWithToken(token)); } else { return(ValidationResponseFactory <AuthResponse> .FailureAuthResponse("Invalid email or password", AuthErrorCodes.InvalidUsernameOrPassword)); } } }
public IActionResult Index(LoginRequestModel lrm, DataServices dataServices) { lrm.RequestTime = DateTime.Now; var Users = dataServices.GetUserData(); var user = Users.Where(u => u.Username.Equals(lrm.Username)); if (user == null || !user.Any()) { return(View()); } var userArray = user.ToArray(); if (!PasswordServices.CompareHash(userArray[0].PasswordHash, PasswordServices.HashGen(userArray[0].Salt, lrm.Password))) { return(View()); } var newData = new List <LogDataModel>(); newData.Add(new LogDataModel(userArray[0], DateTime.Now)); dataServices.SaveLogData(newData, false); /* * controller.Write(pinOut, PinValue.High); * Thread.Sleep(1000); * controller.Write(pinOut, PinValue.Low); */ TriggerServo(); return(RedirectToAction(actionName: "Unlocked", controllerName: "Home")); }
public async Task <IActionResult> Login() { var roleCount = await _userService.AddRoles(); var user = await _userService.GetAdminUser(); if (user is null) { User newUser = new User { UserName = "******", FullName = "Admin", Email = "*****@*****.**", EmailConfirmed = true, }; IdentityResult result = await _userManager.CreateAsync(newUser, "12345"); var model = new UserModel(); model.Email = newUser.Email; if (result.Succeeded) { var role = await _roleManager.FindByNameAsync("Admin"); if (role != null) { await _userManager.AddToRoleAsync(newUser, role.Name); } } } var resModel = new LoginRequestModel(); return(View(resModel)); }
/// <summary> /// Valida os dados do login /// </summary> /// <param name="loginRequest"></param> /// <param name="repository"></param> private static void CheckLogin(LoginRequestModel loginRequest, MainRepository repository) { LoginModel loginBD = repository.GetLoginData(loginRequest.Login); if (loginBD?.USUA_COD == null) { throw new Exception("Login não foi encontrado!"); } if (!repository.IsPasswordValid(loginRequest.Password, loginBD.USUA_TXT_SEN)) { throw new Exception("Senha informada incorretamente!"); } if (loginBD.USUA_DAT_FIM != null) { throw new Exception("Usuário está desativado!"); } if (!loginBD.SN_ACESIG) { throw new Exception("Usuário não tem acesso ao Signus-ERP!"); } }
public LoginResViewModel Login(LoginRequestModel reqModel) { var responseModel = new LoginResViewModel(); var foundUser = Data.UserData.GetUserByEmail(reqModel.UserName); if (foundUser == null) { responseModel.Success = false; return(responseModel); } var loginUser = new User { Password = reqModel.Password, Salt = foundUser.Salt }; loginUser = CryptoFunctions.CreateCryptoForPassword(loginUser); if (loginUser.Password.Equals(foundUser.Password)) { var session = new Session { User = foundUser, UserId = foundUser.Id, ExpireDateTime = DateTime.UtcNow.AddHours(8) }; responseModel.Token = DateTime.UtcNow.ToString() + new Guid() + new Guid(); session.Token = responseModel.Token; Data.SessionData.CreateSession(session); foreach (var role in Data.UsersRolesData.GetListOfAllUsersRolesesByUserId(foundUser.Id)) { responseModel.Roles.Add(role.Role); } responseModel.Success = true; return(responseModel); } responseModel.Success = false; return(responseModel); }
public async Task <ActionResult> Login(LoginRequestModel loginRequest, string returnUrl = null) { returnUrl ??= Url.Content("~/"); if (!ModelState.IsValid) { return(View()); } var user = await _userService.ValidateUser(loginRequest.Email, loginRequest.Password); if (user == null) { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(View()); } var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.Email), new Claim(ClaimTypes.GivenName, user.FirstName), new Claim(ClaimTypes.Surname, user.LastName), new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) }; if (user.Roles != null) { claims.AddRange(user.Roles.Select(role => new Claim(ClaimTypes.Role, role.Name))); } var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); return(LocalRedirect(returnUrl)); }
public async Task <LoginResponseModel> Put(string id, [FromBody] LoginRequestModel model) { var userId = _userService.GetProperUserId(User).Value; var login = await _cipherRepository.GetByIdAsync(new Guid(id), userId); if (login == null || login.Type != Core.Enums.CipherType.Login) { throw new NotFoundException(); } var modelOrgId = string.IsNullOrWhiteSpace(model.OrganizationId) ? (Guid?)null : new Guid(model.OrganizationId); if (login.OrganizationId != modelOrgId) { throw new BadRequestException("Organization mismatch. Re-sync if you recently shared this login, " + "then try again."); } await _cipherService.SaveDetailsAsync(model.ToCipherDetails(login), userId); var response = new LoginResponseModel(login); return(response); }
public IHttpActionResult getForAdmin([FromBody] LoginRequestModel user) { using (var baza = new PageBazaContext()) { List <Korisnici> korisnici = baza.Korisnici.ToList(); foreach (Korisnici k in korisnici) { if (user.Username == k.Username && user.Password == k.Password) { var identity = (ClaimsIdentity)User.Identity; var roles = identity.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value); foreach (var rol in roles) { if (rol == "admin") { return(Ok(true)); } } return(Ok(false)); } } return(Ok(false)); } }
public async Task <ResultModel <TokenResultModel> > Login(LoginRequestModel requestModel) { try { var model = _mapper.Map <LoginModel>(requestModel); UserDTO user = await _userService.LoginAsync(model); string token = GetToken(user); var result = new TokenResultModel { ExpiresSecond = _applicationConfig.JWTConfig.ExpiredTime, AccessToken = token }; return(ResultModel <TokenResultModel> .Success(result, "登录成功")); } catch (AspectInvocationException ex) { return(ResultModel <TokenResultModel> .Fail(ex.InnerException?.Message)); } catch (MateralConfigCenterException ex) { return(ResultModel <TokenResultModel> .Fail(ex.Message)); } }
//[ServiceFilter(typeof(ValidateTokenAttribute))] public IActionResult GetAuth([FromBody] LoginRequestModel loginRequest) { loginRequest.Username = loginRequest.Username.Trim(); loginRequest.Password = MD5Encrypting.MD5Encrypt64(MD5Encrypting.MD5Encrypt16(loginRequest.Password.Trim()));//两次加密安全性更高 ResponseResult responseResult = CommonFactory.CreateResponseResult; UserModel user = _userService.GetUser(loginRequest); if (user == null || user.IsDelete == DataStatusEnum.Delete) { return(Ok(responseResult.Failed("用户名或者密码错误"))); } if (user.AccountStatus == AccountStatusEnum.PendingReview) { return(Ok(responseResult.Failed("账号待审核通过中"))); } if (user.AccountStatus == AccountStatusEnum.Locked) { return(Ok(responseResult.Failed("账号已被锁定"))); } if (user.AccountStatus == AccountStatusEnum.Forbidden) { return(Ok(responseResult.Failed("账号已被禁用"))); } string token = _authService.CreateToken(new AuthContext() { ID = user.ID, Username = user.Username, Email = user.Email, Role = "testRole", }); return(Ok(responseResult.ResponseData(token))); }
public async Task <ActionResult <string> > Login(LoginRequestModel model) { var user = await this.userManager.FindByNameAsync(model.UserName); if (user == null) { return(this.Unauthorized()); } var passwordValid = await this.userManager.CheckPasswordAsync(user, model.Password); if (!passwordValid) { return(this.Unauthorized()); } var tokenHeader = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(this.appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("Id", user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(1), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key) , SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHeader.CreateToken(tokenDescriptor); var encryptedToken = tokenHeader.WriteToken(token); return(Json(encryptedToken)); }
/// <summary> /// Displays Login form and calls PerformLogin method /// </summary> public void ShowLogin() { Console.Clear(); Console.WriteLine("\n\t\tLog in to existing account."); // capture request info LoginRequestModel request = new LoginRequestModel(); Console.WriteLine("\nEnter Username:"******"\nEnter Password:"******"Login Success! Press Any Key to Continue..."); Console.ReadKey(true); ShowMenu(App.LoggedIn); } else { Console.WriteLine("Error. Invalid Username or Password. " + "\n\n(Press any key to Retry, Press Esc to return to Menu)"); if (Console.ReadKey(true).Key == ConsoleKey.Escape) { ShowMenu(App.LoggedIn); } else { ShowLogin(); } } Console.ReadLine(); ShowMenu(App.LoggedIn); }
public async Task <Result <LoginResponseModel> > LoginAsync(LoginRequestModel model) { //TODO add phone number identification var user = await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false); if (user == null) { return(InvalidLoginMessage); } var passwordValid = await _userManager.CheckPasswordAsync(user, model.Password).ConfigureAwait(false); if (!passwordValid) { return(InvalidLoginMessage); } var token = await _jwtGenerator.GenerateJwtAsync(user).ConfigureAwait(false); return(new LoginResponseModel { Token = token }); }
public IHttpActionResult registrujKorisnika([FromBody] LoginRequestModel user) { Boolean poklapanje = false; using (var baza = new PageBazaContext()) { List <Korisnici> korisnici = baza.Korisnici.ToList(); foreach (Korisnici k in korisnici) { if (user.Username == k.Username) { poklapanje = true; return(Ok("Username " + user.Username + " vec postoji!")); } } Korisnici kor = new Korisnici(); kor.Username = user.Username; kor.Password = user.Password; baza.Add(kor); baza.SaveChanges(); return(Ok(true)); } }
public async Task <IActionResult> Login(LoginRequestModel model) { User user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { //İlgili kullanıcıya dair önceden oluşturulmuş bir Cookie varsa siliyoruz. await _signInManager.SignOutAsync(); Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(user, model.Password, model.Persistent, model.Lock); //Lock:belirli bir sürede (mesela 5 dk) kullanıcı yanlıs girerse hesabı bloklasın mı(true,false) if (result.Succeeded) { return(FormResult.CreateSuccessResult("Success", Url.Action("Index", "Home"))); } else if (result.IsNotAllowed) { return(FormResult.CreateErrorResult("Email is not activated")); } } return(FormResult.CreateErrorResult("Email or password is wrong")); }
public async Task <LoginResponseModel> Login(LoginRequestModel loginModel, string secret) { var user = await this.userManager.FindByNameAsync(loginModel.UserName); if (user == null) { return(null); } var passwordValid = await this.userManager.CheckPasswordAsync(user, loginModel.Password); if (!passwordValid) { return(null); } var token = this.GenerateJwtToken( user.Id, user.UserName, secret); return(new LoginResponseModel(token, user.Id, loginModel.IsCurrentlyRegistered)); }
public async Task <ApiResponse> Login([FromBody] LoginRequestModel loginRequestModel) { var command = new LoginRequestCommand { Login = loginRequestModel.Username, Password = loginRequestModel.Password }; var commandResponse = await this._loginRequestCommandHandler.Handle(command); if (commandResponse.ValidationResult.IsValid) { var response = ApiResponse.CreateSuccess(new { token = commandResponse.AccessToken, refreshToken = commandResponse.RefreshToken }); return(response); } else { return(ApiResponse.CreateError(commandResponse.ValidationResult)); } }
public async Task <ActionResult <LoginResponseModel> > Login(LoginRequestModel loginRequestModel) { var user = await this.userManager.FindByNameAsync(loginRequestModel.Username); if (user == null) { return(Unauthorized()); } var passwordValid = await this.userManager.CheckPasswordAsync(user, loginRequestModel.Password); if (!passwordValid) { return(Unauthorized()); } var encryptedToken = this.identityService.GenerateJwtToken(user.Id, user.UserName, this.options.Secret); return(new LoginResponseModel { Token = encryptedToken }); }
public async Task <IActionResult> CreateAccount(LoginRequestModel model) { var user = await _userManager.FindByEmailAsync(model.Email); if (user == null || user.IsDeleted) { User newUser = new User { UserName = model.Email, Email = model.Email, FullName = model.Email, EmailConfirmed = true }; IdentityResult result = await _userManager.CreateAsync(newUser, model.Password); if (result.Succeeded) { var role = await _roleManager.FindByNameAsync(Constants.UserType.User.ToString()); if (role != null) { await _userManager.AddToRoleAsync(newUser, role.Name); } return(FormResult.CreateSuccessResult("Added user")); } else { return(FormResult.CreateErrorResult("An error occurred")); } } return(FormResult.CreateErrorResult("There is such a user")); }
//POST : /api/User/Login public async Task <IActionResult> Login(LoginRequestModel model) { var user = await _service.GetByEmail(model.Email); if (user != null) { try { IdentityOptions _options = new IdentityOptions(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("UserID", user.Id.ToString()), new Claim("Email", user.Email), new Claim("FullName", user.FirstName + " " + user.LastName), }), Expires = DateTime.UtcNow.AddDays(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567890123456")), SecurityAlgorithms.HmacSha256Signature) }; var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(securityToken); user.IsOnline = true; return(Ok(new { token, user })); } catch (Exception exp) { return(BadRequest(exp)); } } else { return(BadRequest(new { message = "Email is Not Valid." })); } }
public bool DoLogin(LoginRequestModel model) { return(_databaseController.CheckLogin(model.Username, model.Password)); }
public async Task <ActionResult <LoginResponseModel> > Login( LoginRequestModel model) => await this.identity .LoginAsync(model) .ToActionResult();
public FubuContinuation Login(LoginRequestModel model) { _session[CurrentLoginStatus.Key] = new CurrentLoginStatus {UserName = "******"}; return FubuContinuation.RedirectTo(new HomeInputModel()); }
public async Task <IActionResult> Login(LoginRequestModel loginRequest) { //07/21 //Http is stateless, each and every request is independent of each other //e.g //10 AM user1--> http:localhost / movies / index //10 AM user2--> http:localhost / movies / index //10 AM user3--> http:localhost / movies / index //10:01AM user1 go to / account / login, we can create an authenticate cookie //cookie is one way of string information on browser; others are local storage and session storage //if there are any cookies present then those cookies will be automatically sent to server. //think of this cookie as movie ticket, present it to cinema(server),and you can get in and watch. //10:02AM user1 go to / user / purchases->we are expecting a page that shows movies bought by user1; //but before that we need to check if the cookie is expired or valid or not. //Cookies is one way of state management, client side //07/20 if (ModelState.IsValid) { // call service layer to validate user var user = await _userService.ValidateUser(loginRequest.Email, loginRequest.Password); if (user == null) { ModelState.AddModelError(string.Empty, "Invalid Login"); } //07/21 //we want to show FirstName, LastName on header(Navigation) of cookie. //Claim can help us collect these information, and we can add Claims to the cookie //donot put sensitive information on cookie //create Claims based on you application needs var claims = new List <Claim> { //there are many options of ClaimTypes new Claim(ClaimTypes.GivenName, user.FirstName), new Claim(ClaimTypes.Surname, user.LastName), //ClaimTypes are all string, so we need to convert int to String here new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.Email), }; // we need to create an Identity Object to hold those claims var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); //finally we need to create a cookie that will be attached to the Http Response // ♥ HttpContext is probably most important class in ASP.NET, that holds all the information regarding that Http Request/Response //when creating a cookie, the following line will automatically encrypt all the claimsIdentity information await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); // Once ASP.NET Craetes Authntication Cookies, it will check for that cookie in the HttpRequest and see if the cookie is not expired // and it will decrypt the information present in the cookie to check whether User is Authenticated and will also get claims from the cookies //(the server will ask browser for cookie authentication) //to mannually add cookie //HttpContext.Response.Cookies.Append("userLanguage", "English"); //redirect to home page (from localhost:12312/account/ to localhost:12312 , 1 level up, so we use ~) return(LocalRedirect("~/")); } return(View()); }
public ActionResult Index() { LoginRequestModel model = new LoginRequestModel(); return(View(model)); }
/// <summary> /// Login process. /// </summary> /// <param name="request">RequestModel</param> /// <returns>ResponseModel</returns> public LoginResponseModel Invoke(LoginRequestModel request) { var responseModel = Execute(request); return(responseModel); }
public async Task <CoordinatorModel> FindUserByLoginTaskAsync(LoginRequestModel login) => await _context.Coordinators.SingleOrDefaultAsync(x => x.Email.ToLower() == login.Email.ToLower() && x.Password == login.Password);
public async Task <GenericResult <LoginResponseModel> > AuthenticateWithUserNamePassword(LoginRequestModel model) { try { var usr = _dwhContext.Users.ToList(); if (model == null) { return(GenericResult <LoginResponseModel> .Fail("Request is invalid.")); } throw new NotImplementedException(); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task <ResultModel <LoginResultModel> > LoginAsync(LoginRequestModel requestModel) { var resultModel = await SendPostAsync <ResultModel <LoginResultModel> >($"{_controllerUrl}Login", requestModel); return(resultModel); }
public async Task <ActionResult <BaseResponseModelGet <UserIdentityModel> > > Login([FromBody] LoginRequestModel value) { return(await _userService.CheckUser(value)); }