public dynamic Auth(AuthViewModel auth) { var _key = _configuration.GetSection("PasswordKey")?.Get <string>(); if (_key == null) { throw new Exception("Password não configurado."); } string _encryptedPassword = auth.Password.EncryptString(_key); User _user = _repositoryUser.Find(wh => wh.IsDeleted && wh.Email == auth.Email && wh.Password == _encryptedPassword); if (_user == null) { throw new Exception("Usuário não encontrado"); } return(new { token = _facadeToken.GenerateToken(_user), user = _user }); }
public async Task <ActionResult> Auth(AuthViewModel model) { if (!ModelState.IsValid) { return(View(model)); } Users user = await _systemService.Authenticate(model.UserName, model.Password); if (user == null || user.UserId <= 0 || user.ActiveStatus == false) { model.HasChecked = true; return(View(model)); } else { //_logger.LogInformation("before sign in"); Helper.Signin(user, HttpContext); //_logger.LogInformation("after sign in"); return(RedirectToAction(nameof(Index))); } }
public OperationResult Login(Login command) { var operation = new OperationResult(); var account = _accountRepository.GetBy(command.Username); if (account == null) { return(operation.Failed(ApplicationMessages.RecordNotFound)); } (bool Verified, bool NeedsUpgrade)result = _passwordHasher.Check(account.Password, command.Password); if (!result.Verified) { return(operation.Failed(ApplicationMessages.WrongUserPass)); } var permissions = _roleRepository .Get(account.RoleId) .Permissions .Select(x => x.Code) .ToList(); var authViewModel = new AuthViewModel(account.Id, account.RoleId, account.FullName, account.Username, account.ProfilePhoto, permissions, account.Mobile); _authHelper.SignIn(authViewModel); return(operation.Succedded()); }
public async Task <IActionResult> Login([Bind("Login, Password, ReturnUrl")] AuthViewModel model) { if (ModelState.IsValid) { var user = await _context.Users .Where(u => u.Login == model.Login && u.PasswordHash == CoreEditor.Models.User.HashPassword(model.Password)) .FirstOrDefaultAsync(); if (user != null) { await Authenticate(model.Login); //return Redirect("../Home/Index"); if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } else { return(Redirect("../Home/Index")); } } else { ModelState.AddModelError( string.Empty, "Неверное имя пользователя или пароль" ); } await _context.SaveChangesAsync(); } return(View(model)); }
public async Task <IActionResult> Index() { var viewModel = new AuthViewModel { PlexKey = HttpContext.Session.GetString("PlexKey"), TraktKey = HttpContext.Session.GetString("TraktKey"), PlexServerKey = HttpContext.Session.GetString("PlexServerKey") }; if (!string.IsNullOrEmpty(viewModel.PlexKey) && !string.IsNullOrEmpty(viewModel.TraktKey)) { _plexClient.SetAuthToken(viewModel.PlexKey); viewModel.PlexServers = (await _plexClient.GetServers()).Select(x => new SelectListItem { Value = x.Url, Text = x.Name }).ToList(); if (viewModel.PlexServers.Any()) { viewModel.PlexServers[0].Selected = true; } } var traktRedirectUrl = HttpUtility.UrlEncode(Url.AbsoluteAction("TraktReturn", "Home")); ViewData["TraktUrl"] = $"https://trakt.tv/oauth/authorize?client_id={_config["TraktConfig:ClientId"]}&redirect_uri={traktRedirectUrl}&response_type=code"; return(View(viewModel)); }
public OperationResult Login(Login command) { var operation = new OperationResult(); var account = _accountRepository.GetBy(command.Username); if (account == null) { return(operation.Failed(ApplicationMessages.UserOrPassWrong)); } var result = _passwordHasher.Check(account.Password, command.Password); if (!result.Verified) { return(operation.Failed(ApplicationMessages.UserOrPassWrong)); } var authViewModel = new AuthViewModel(account.Id, account.RoleId, account.Fullname, account.Username); _authHelper.Signin(authViewModel); return(operation.Succeed()); }
public ActionResult Login(AuthViewModel model) { UserDto dto = new UserDto(); dto.Id = model.Id; dto.UserName = model.UserName; dto.Password = model.Password; var user = UserService.Authentication(dto); if (user != null) { FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); if (Url.IsLocalUrl(model.returnUrl)) { return(Redirect(model.returnUrl)); } else { return(RedirectToAction("Index", "Admin")); } } else { ModelState.AddModelError("", "Неправильный логин или пароль"); } return(View(model)); }
public AuthViewModel Authenticate(User user) { var userLogin = _userServices.GetUserByName(user.Username); if (userLogin == null) { return(null); } var Verificado = _passwordHasher.Check(userLogin.Password, user.Password); if (!Verificado) { return(null); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Value.SecreteKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, userLogin.Username), new Claim("Store", userLogin.Role) }), Expires = DateTime.UtcNow.AddDays(2), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var authViewModel = new AuthViewModel(userLogin); authViewModel.Token = tokenHandler.WriteToken(token); return(authViewModel); }
public async Task Login(AuthModel authModel) { AuthViewModel authViewModel = new AuthViewModel(); authViewModel.Email = authModel.Email; authViewModel.Password = authModel.Password; await authViewModel.LoginUser(authModel); var viewModel = ServiceLocator.Current.GetInstance <MainNavigationViewModel>(); var typeValue = viewModel.ViewType; Type type = typeof(LoginPage); switch (typeValue) { case ViewType.LoginPage: type = typeof(LoginPage); await Navigation.PushAsync(new LoginPage()); break; case ViewType.RegisterPage: type = typeof(RegisterPage); await Navigation.PushAsync(new RegisterPage()); break; case ViewType.MainPage: type = typeof(MainPage); await Navigation.PushAsync(new MainPage()); break; } }
public DeviceListPage(AuthViewModel authViewModel) { DeviceListViewModel viewModel = new DeviceListViewModel(authViewModel); DataContext = viewModel; InitializeComponent(); }
public async void Execute(object parameter) { var displayRootRegistry = (Application.Current as App).DisplayRootRegistry; var dialogWindowViewModel = new AuthViewModel(); await displayRootRegistry.ShowModalPresentation(dialogWindowViewModel); if (dialogWindowViewModel.IsAccept) { _mainWindowVeiwModel.Auth = new AuthSerializer(); _mainWindowVeiwModel.Auth.username = dialogWindowViewModel.Login; _mainWindowVeiwModel.Auth.password = dialogWindowViewModel.Password; var checkProgram = new CheckUpdateProgramCommand(_mainWindowVeiwModel); checkProgram.Execute(null); _mainWindowVeiwModel.CheckProgramTimer.Tick += (s, e) => { var checkPrograms = new CheckUpdateProgramCommand(_mainWindowVeiwModel); checkPrograms.Execute(null); }; _mainWindowVeiwModel.CheckProgramTimer.Start(); _mainWindowVeiwModel.CheckStartProgramTimer.Start(); } else { Application.Current.Shutdown(); } }
public async Task <IHttpActionResult> EmailChangeSend(AuthViewModel model) { try { var slaveUser = await _auth.AccountGetAsync(model.Email, isIncludeSubEmails : true); if (!object.Equals(slaveUser, null) && slaveUser.Id != AccountId) { return(AccountExists()); } var masterUser = await GetAccountAsync(); if (string.Equals(masterUser.Email, model.Email, StringComparison.InvariantCultureIgnoreCase)) { await _auth.AccountSubEmailPendingDeleteAsync(masterUser.Id); } else { await NotificationManager.EmailChangeConfirmationNotification(masterUser, model.Email); } } catch (Exception exc) { return(Request.HttpExceptionResult(exc)); } return(Ok()); }
public IActionResult Register(AuthViewModel newUser) { ///if model state is not valid, back to the previous page if (!ModelState.IsValid) { return(View()); } else { User Usercheck = _context.Users.SingleOrDefault(u => u.Email == newUser.RegForm.Email); if (Usercheck != null) { ViewBag.EmailExists = "That user already exists."; return(View()); } else { PasswordHasher <RegisterViewModel> hasher = new PasswordHasher <RegisterViewModel>(); string HashedPW = hasher.HashPassword(newUser.RegForm, newUser.RegForm.Password); User NewUser = new User { FirstName = newUser.RegForm.FirstName, LastName = newUser.RegForm.LastName, Email = newUser.RegForm.Email, Password = HashedPW, }; _context.Add(NewUser); _context.SaveChanges(); User loggedin = _context.Users.SingleOrDefault(u => u.Email == newUser.RegForm.Email); HttpContext.Session.SetInt32("UserId", loggedin.UserId); return(RedirectToAction("Dash")); } } }
public async Task <ActionResult> Authenticate(AuthRequestModel model) { if (ModelState.IsValid) { var result = new AuthViewModel(); try { var auth_credentials = model.GetAuthorizationHeaderValue(); var token = await service.Authenticate(auth_credentials); result.Result = token; //create session HttpContext.Session[model.application_id] = token.access_token; TempData["model"] = result; return(RedirectToAction("AuthenticateResult")); } catch (Exception e) { result.Error = e.Message; TempData["model"] = result; return(RedirectToAction("AuthenticateResult")); } } return(View(model)); }
public async Task <ActionResult> Token([FromBody] AuthViewModel model) { var user = await _userManager.FindByNameAsync(model.Username); if (user != null && await _userManager.CheckPasswordAsync(user, model.Password)) { var claim = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName) }; var secKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(_configuration["Jwt:secKey"])); int expiryInMinutes = Convert.ToInt32(_configuration["Jwt:ExpiryInMinutes"]); var token = new JwtSecurityToken( issuer: _configuration["Jwt:issuer"], audience: _configuration["Jwt:audience"], expires: DateTime.UtcNow.AddMinutes(expiryInMinutes), signingCredentials: new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256) ); return(Ok( new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } return(Unauthorized()); }
public async Task <JsonRedirect> SignIn(AuthViewModel model) { var _validations = new AuthSignInModelValidator(); var results = _validations.Validate(model.SignIn); if (!results.IsValid) { var failure = results.Errors.FirstOrDefault(); return(new JsonRedirect(failure.ErrorMessage)); } var user = await _userManager.FindByNameAsync(model.SignIn.Name); if (user == null) { return(new JsonRedirect("User is not registered.")); } var result = await _signInManager.PasswordSignInAsync(user, model.SignIn.Password, false, false); if (!result.Succeeded) { return(new JsonRedirect("Login or password is invalid.")); } return(new JsonRedirect(new Link(nameof(StoreController), nameof(StoreController.Index)))); }
public bool GetCredentialsFromUser(IWin32Window owner, Uri translationProviderUri, string translationProviderState, ITranslationProviderCredentialStore credentialStore, string initialAuthToken) { var authViewModel = new AuthViewModel(_client); string existingToken = credentialStore.GetCredential(translationProviderUri)?.Credential ?? initialAuthToken; authViewModel.AuthToken = existingToken; var authView = new AuthWindow(authViewModel); bool success = authView.ShowDialog() == true; if (!success) { return(false); } string authToken = authViewModel.AuthToken; if (authToken != null) { credentialStore.AddCredential(translationProviderUri, new TranslationProviderCredential(authToken, true)); return(true); } else { // the user has deleted the token using the logout button credentialStore.RemoveCredential(translationProviderUri); // TODO: return something that will make Trados disable the plugin. Currently I don't think it's possible, though. // Returning false indicates that the settings haven't changed which isn't true but if true is returned the user // gets endless prompts from Trados to input credentials. This seems like a bug, though, so hopefully this will change. return(false); } }
public OperationResult Login(LoginVM command, bool keepMe) { OperationResult result = new OperationResult(); var user = _userRepository.GetUserBy(command.UserName); if (user == null) { return(result.Failed("کاربری با این مشخصات یافت نشد !")); } if (string.IsNullOrWhiteSpace(command.Password) || string.IsNullOrWhiteSpace(command.Email)) { return(result.Failed("تمام مقادیر را پر کنید")); } var passwordResult = _passwordHasher.Check(user.Password, command.Password); if (!passwordResult.Verified) { return(result.Failed("رمز عبور اشتباه می باشد!")); } if (!(user.Username == command.UserName.ToLower() && user.Email == command.Email)) { return(result.Failed("نام کاربری یا پست الکترونیک صحیح نمی باشد!")); } var authVM = new AuthViewModel(user.Id, user.Fullname, user.Username, user.Mobile, keepMe); _authHelper.Signin(authVM); return(result.Succeeded()); }
public async Task <IActionResult> Login([FromBody] LoginViewModel model) { if (string.IsNullOrWhiteSpace(model.UserName)) { throw new ApiException(HttpStatusCode.BadRequest, "required input parameter"); } //get application user by user name var appUser = await _userManager.FindByNameAsync(model.UserName.Trim()); if (appUser == null) { throw new ApiException(HttpStatusCode.Unauthorized, "User does not exists"); } AuthViewModel user = new AuthViewModel { }; //sign in to application var result = await _signInManager.PasswordSignInAsync(appUser.UserName, model.Password, false, false); if (result.Succeeded) { user.UserName = appUser.UserName; user.Token = await _jwtTokenCreator.CreateToken(appUser.UserName, appUser); user.RedirectUrl = RouteConstants.DashBoard; return(Ok(user)); } throw new ApiException(HttpStatusCode.BadRequest, "password is incorrect"); }
public OperationResult <AuthViewModel> Get(string userName, string password) { OperationResult <AuthViewModel> result = new OperationResult <AuthViewModel>(); try { IrrigationAdvisorWebApiEntities1 context = new IrrigationAdvisorWebApiEntities1(); AuthViewModel vw = new AuthViewModel() { Token = "ffdvskdidmf5656483" }; Authentication auth = new Authentication(userName, password); if (auth.IsAuthenticated()) { string cleanUserName = userName.ToLower().Trim(); var user = context.Users.Where(n => n.UserName == cleanUserName).Single(); var farms = from uf in context.UserFarms join iu in context.IrrigationUnits on uf.FarmId equals iu.FarmId join f in context.Farms on iu.FarmId equals f.FarmId join ciw in context.CropIrrigationWeathers on iu.IrrigationUnitId equals ciw.IrrigationUnitId where uf.UserId == user.UserId && iu.Show && ciw.SowingDate <= DateTime.Now && f.IsActive && ciw.HarvestDate >= DateTime.Now select uf; foreach (var f in farms.Distinct()) { FarmViewModel newFarm = new FarmViewModel() { Description = f.Name, FarmId = f.FarmId }; vw.Farms.Add(newFarm); } } else { throw new UnauthorizedAccessException("Usuario o contraseña invalido"); } result.IsOk = true; result.Data = vw; } catch (Exception ex) { result.IsOk = false; result.ErrorMessage = ex.Message; } return(result); }
public IActionResult Login(string returnUrl) { AuthViewModel model = new AuthViewModel(); model.ReturnUrl = returnUrl; return(View(model)); }
public async Task <IActionResult> LoginPage(AuthViewModel model) { if (model.UserName == "admin" && model.Password == "123") { //todo: logged as admin var principal = CreateAdmin(); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return(RedirectToAction("Index", "Admin")); } var user = _repository.SignIn(model.UserName, model.Password); if (user != null) { // todo: logged as operator var principal = CreatePrincipal(user); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return(RedirectToAction("Index", "Home")); } return(View()); }
public async Task <ActionResult <Recurso> > Auth([FromBody] AuthViewModel obj) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Recurso recurso = await _unitOfWork.RecursoRepository.GetByLoginAsync(obj.Usuario); if (recurso == null) { return(NotFound()); } bool valido = _cryptographyManager.VerifyPbkdf2(obj.Senha, recurso.Senha, recurso.Salt); recurso.Senha = null; recurso.Salt = null; if (!valido) { return(NotFound()); } else { int.TryParse(_configuration["Jwt:Expires"], out int jwtExpires); recurso.Token = TokenService.GenerateToken(recurso.Id.ToString(), _configuration["Jwt:Key"], _configuration["Jwt:Issuer"], jwtExpires); return(Ok(recurso)); } }
public async Task <IActionResult> Signup(AuthViewModel userData) { if (ModelState.IsValid) { var user = new TodoUser { Email = userData.Email, UserName = userData.Email }; var signupResult = await _userManager.CreateAsync(user, userData.Password); if (signupResult.Succeeded) { var signInResult = await _signInManager.PasswordSignInAsync(user.UserName, userData.Password, true, false); if (signInResult.Succeeded) { return(RedirectToAction("Todo", "Home")); } } else { _logger.LogError("Failed to create user"); ModelState.AddModelError("", "Failed to sign up"); } } _logger.LogError("Failed to create user and sign up"); return(View()); }
public IActionResult Login(AuthViewModel Auth) { string email = Auth.LogForm.Email; string password = Auth.LogForm.Password; int? UserId = HttpContext.Session.GetInt32("UserId"); if (UserId != null) { return(RedirectToAction("Result")); } string check = email == null ? null : email.ToLower(); UserModel Query = _context.Users.Where(user => user.Email.ToLower() == check).FirstOrDefault(); if (Query != null && password != null) { PasswordHasher <UserModel> Hasher = new PasswordHasher <UserModel> (); var result = Hasher.VerifyHashedPassword(Query, Query.Password, password); if (result != 0) { HttpContext.Session.SetInt32("UserId", Query.UserId); return(RedirectToAction("Result")); } } TempData["LoginError"] = "Wrong username or password."; return(RedirectToAction("Index")); }
public async Task <IActionResult> Login(AuthViewModel userData, string returnUrl) { if (ModelState.IsValid) { var signInResult = await _signInManager.PasswordSignInAsync(userData.Email, userData.Password, true, false); if (signInResult.Succeeded) { if (string.IsNullOrWhiteSpace(returnUrl)) { return(RedirectToAction("Todo", "Home")); } else { return(Redirect(returnUrl)); } } else { _logger.LogError("Failed to sign user in"); ModelState.AddModelError("", "Email or password incorrect"); } } _logger.LogError("Failed to create user and sign up"); return(View()); }
public async Task <IActionResult> Login([FromBody] AuthViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var signInResult = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, false); if (!signInResult.Succeeded) { return(Unauthorized()); } var usr = _repository.GetUserByEmail(model.Email); if (usr == null) { return(NotFound(new { Message = $"User {model.Email} not found" })); } return(Ok(Mapper.Map <UserViewModel>(usr))); } catch (HighFiveException ex) { _logger.LogError("Login Failed for user: {0} {1}", model.Email, ex); } return(BadRequest(new { Message = $"Login Failed for user: {model.Email}" })); }
public ActionResult Users() { AuthViewModel model = new AuthViewModel(); model.UserList = UserService.FullUserList; return(View(model)); }
public IActionResult Register(AuthViewModel authViewModel) { var user = _authService.Register(authViewModel.UserForRegisterDto); DelayedJobs.SendMailRegisterJobs(user.UserId); return(RedirectToAction("Index", "Home")); }
/// <summary> /// 获取用户权限表视图列表分页 /// </summary> /// <param name="model"></param> /// <returns></returns> public BaseResultModel <PageModel <AuthViewModel> > ListViewPageAuth(AuthViewModel model) { try { if (model == null) { model = new AuthViewModel() { PageNO = 1, PageSize = int.MaxValue }; } // 开启查询outModel里面的视图 using (this.AuthRepository.BeginSelView()) { using (this.AuthRepository.BeginLikeMode()) { return(new SuccessResultModel <PageModel <AuthViewModel> >(this.AuthRepository.ListViewPage(model))); } } } catch (Exception e) { LogWriter.WriteLog(EnumLogLevel.Fatal, "ListViewPageAuth", JsonConvert.SerializeObject(model), "Auth", "获取用户权限表视图列表分页查询数据时发生错误.", e); return(new ErrorResultModel <PageModel <AuthViewModel> >(EnumErrorCode.系统异常, "获取用户权限表视图列表分页查询数据时发生错误!")); } }