protected override AuthenticationResult Authenticate(UnitOfWork UoW, LoginParameters LoginParameters) { AuthenticationResult authenticationResult = new AuthenticationResult(); try { PermissionPolicyUser User = UoW.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", LoginParameters.Username)); if (User == null) { authenticationResult.LastError = "User not found"; return(authenticationResult); } if (!User.ComparePassword(LoginParameters.Password)) { authenticationResult.LastError = "Password do not match"; return(authenticationResult); } authenticationResult.Authenticated = true; authenticationResult.UserId = User.Oid.ToString(); authenticationResult.Username = User.UserName; return(authenticationResult); } catch (Exception exception) { authenticationResult.LastError = exception.Message; return(authenticationResult); } }
public async Task <IActionResult> Login(LoginParameters parameters) { await EnsureAdmin(); if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.SelectMany(state => state.Errors) .Select(error => error.ErrorMessage) .FirstOrDefault())); } var user = await _userManager.FindByNameAsync(parameters.UserName); if (user == null) { return(BadRequest("User does not exist")); } var singInResult = await _signInManager.CheckPasswordSignInAsync(user, parameters.Password, false); if (!singInResult.Succeeded) { return(BadRequest("Invalid password")); } await _signInManager.SignInAsync(user, parameters.RememberMe); return(Ok()); }
public async Task <ResultData <IAuthResult> > LoginAsync(LoginParameters parameters = null) { parameters = parameters ?? new LoginParameters { Username = Api.Connection.Settings.Username, Password = Api.Connection.Settings.Password }; _sessionNumber = parameters.SessionName; Api.Connection.Logger.LogDebug($"Logging in as {parameters.Username} for session {_sessionNumber}"); var result = await this.GetDataAsync <AuthResult>(new SynologyRequestParameters(this) { Version = 4, Additional = parameters }); if (result.Success && !string.IsNullOrWhiteSpace(result.Data?.Sid)) { Api.Connection.SetSid(result.Data?.Sid); } return(ResultData <IAuthResult> .From(result)); }
public void Login([FromBody] LoginParameters loginParameters) { bool valid = false; var userLoginService = new UserLoginService(new Rock.Data.RockContext()); var userLogin = userLoginService.GetByUserName(loginParameters.Username); if (userLogin != null && userLogin.EntityType != null) { var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name); if (component != null && component.IsActive) { if (component.Authenticate(userLogin, loginParameters.Password)) { valid = true; Rock.Security.Authorization.SetAuthCookie(loginParameters.Username, loginParameters.Persisted, false); } } } if (!valid) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } }
public async Task <UserInfo> Login(LoginParameters loginParameters) { // Todo Handle StatusCodes?? var result = await _httpClient.PostJsonAsync <UserInfo>("api/Authorize/Login", loginParameters); return(result); }
/// <summary> /// Copies the base properties from a source LoginParameters object /// </summary> /// <param name="source">The source.</param> public void CopyPropertiesFrom(LoginParameters source) { this.Authorization = source.Authorization; this.Password = source.Password; this.Persisted = source.Persisted; this.Username = source.Username; }
public async Task<IActionResult> Login(LoginParameters parameters) { if (!ModelState.IsValid) return BadRequest(ModelState.Values.SelectMany(state => state.Errors) .Select(error => error.ErrorMessage) .FirstOrDefault()); var user = await _userManager.FindByNameAsync(parameters.UserName); if (user == null) { _logger.LogInformation("User does not exist: {0}", parameters.UserName); return BadRequest("User does not exist"); } var singInResult = await _signInManager.CheckPasswordSignInAsync(user, parameters.Password, false); if (!singInResult.Succeeded) { _logger.LogInformation("Invalid password: {0}, {1}", parameters.UserName, parameters.Password); return BadRequest("Invalid password"); } _logger.LogInformation("Logged In: {0}, {1}", parameters.UserName, parameters.Password); await _signInManager.SignInAsync(user, parameters.RememberMe); return Ok(BuildUserInfo(user)); }
public async Task <ActionResult> Index(LoginParameters model) { var data = await restClientContainer.SendRequest <ResponseResult>("Accounts/Login", RestSharp.Method.POST, model); if (data.Data != null) { string json = JsonConvert.SerializeObject(data.Data); var dataRet = Helper <UserLoginReturn> .Convert(json); Session["userId"] = dataRet.UserId; if (model.IsSavedPassword) { Response.Cookies["userId"].Value = dataRet.UserId; Response.Cookies["userId"].Expires = DateTime.Now.AddDays(6); } Session["userName"] = model.Username; Response.Cookies["token"].Value = dataRet.Token; Response.Cookies["token"].Expires = DateTime.Now.AddDays(7); // add expiry time return(RedirectToAction("Index", "Home")); } return(View(new LoginParameters() { Status = false })); }
public async Task <IActionResult> Login(LoginParameters parameters) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.SelectMany(state => state.Errors) .Select(error => error.ErrorMessage) .FirstOrDefault())); } var user = await _userManager.FindByNameAsync(parameters.UserName); if (user == null) { return(BadRequest("El usuario no existe")); } var singInResult = await _signInManager.CheckPasswordSignInAsync(user, parameters.Password, false); if (!singInResult.Succeeded) { return(BadRequest("Contraseña incorrecta")); } await _signInManager.SignInAsync(user, parameters.RememberMe); return(Ok()); }
public async Task <ClientApiResponse> Login(LoginParameters loginParameters) { ClientApiResponse apiResponse = await _authorizeApi.Login(loginParameters); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); return(apiResponse); }
/// <summary> /// Check if the login parameters are valid /// </summary> /// <param name="loginParameters"></param> /// <returns></returns> private bool IsLoginValid(LoginParameters loginParameters) { if (loginParameters == null || loginParameters.Username.IsNullOrWhiteSpace()) { return(false); } UserLogin userLogin; using (var rockContext = new RockContext()) { var userLoginService = new UserLoginService(rockContext); userLogin = userLoginService.GetByUserName(loginParameters.Username); if (userLogin == null || userLogin.EntityType == null) { return(false); } } var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name); if (component == null || !component.IsActive) { return(false); } return(component.Authenticate(userLogin, loginParameters.Password)); }
public async Task <IActionResult> Login(LoginParameters parameters) { var authenticationContext = await _accountProxy.Authenticate(new AuthenticationParameters { AreaCode = parameters.AreaCode, Identifier = parameters.MobileNumber, Password = _protectionService.ComputeHash(parameters.Password), Type = UserType.Client }); if (authenticationContext != null) { if (!authenticationContext.RequiredMethods.Any()) { var token = await _accountProxy.GenerateToken(authenticationContext); if (string.IsNullOrWhiteSpace(token)) { TempData["errorMessage"] = "Something went wrong, please try again."; return(View()); } var options = new CookieOptions { Expires = DateTime.Now.AddMinutes(30) }; Response.Cookies.Append("Token", token, options); return(RedirectToAction("Index", "Home")); } } TempData["errorMessage"] = "Your email or password is wrong, please try again"; return(View()); }
public async Task <string> Login(LoginParameters loginParameters) { var error = await _authorizationApi.Login(loginParameters); SignalStateChange(); return(error); }
public async Task <AuthenticationResponse> Login(LoginParameters loginParameters) { var dict = new Dictionary <string, string>(); dict.Add("grant_type", "password"); dict.Add("username", loginParameters.UserName); dict.Add("password", loginParameters.Password); var request = new HttpRequestMessage(HttpMethod.Post, _httpClient.BaseAddress + "/token") { Content = new FormUrlEncodedContent(dict) }; var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { //this contains the token, we'll save it to sessionStorage. var result = await response.Content.ReadAsStringAsync(); var authResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <AuthenticationResponse>(result); authResponse.StatusCode = System.Net.HttpStatusCode.OK; return(authResponse); } return(new AuthenticationResponse { StatusCode = response.StatusCode }); }
public async Task <IActionResult> Login(LoginParameters parameters) { var user = await _userManager.FindByNameAsync(parameters.UserName); if (user == null) { // user = await CreateUserFromPin(parameters); if (user == null) { return(BadRequest("User does not exist")); } } var singInResult = await _signInManager.CheckPasswordSignInAsync(user, parameters.Password, false); if (!singInResult.Succeeded) { return(BadRequest("Invalid password")); } await _signInManager.SignInAsync(user, parameters.RememberMe); return(Ok()); }
private void OnLoginUser(object obj) { if (StrUser == null || StrUser == String.Empty) { StrNotifications = "Debe escribir su Usuario."; return; } if (StrPassword == null || StrPassword == String.Empty) { StrNotifications = "Debe escribir su Contraseña."; return; } this.EnableLoginButton = false; LoginParameters lp = new LoginParameters(StrUser, StrPassword); try { WebContext.Current.Authentication.Login(lp, LoginOperationCompleted, null); } catch (Exception ex) { MessageBox.Show("Error de Autenticación: " + ex.Message); } }
public async Task <ActionResult <WebApiLoginResult> > ChangePassword(LoginParameters parameters, CancellationToken token) { var result = new WebApiLoginResult { LoginResult = (int)LoginResult.Failed, PasswordChangeResult = (int)PasswordChangeResult.Failed, }; var company = (await companyProcessor.GetAsync(new CompanySearch { Code = parameters.CompanyCode }, token))?.FirstOrDefault(); if (company == null) { return(result); } var loginUser = (await loginUserProcessor.GetAsync(new LoginUserSearch { CompanyId = company.Id, Codes = new[] { parameters.UserCode }, }, token))?.FirstOrDefault(); if (loginUser == null) { return(result); } var changeResult = await loginUserPasswordProcessor.ChangeAsync(company.Id, loginUser.Id, parameters.OldPassword, parameters.Password, token); result.PasswordChangeResult = (int)changeResult; return(result); }
public IActionResult Post([FromBody] LoginParameters login) { User user = new User(); if ((user = Udbl.LogInUser(login.Username, login.Password)) != null) { var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345")); var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var claims = new List <Claim> { new Claim(ClaimTypes.Name, login.Username), new Claim(ClaimTypes.Role, user.Role) }; var tokenOptions = new JwtSecurityToken( issuer: "https://localhost:44325", audience: "https://localhost:44325", claims: claims, expires: DateTime.Now.AddSeconds(147), signingCredentials: signingCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions); return(Ok(new { Token = tokenString })); } return(Unauthorized()); }
public IHttpActionResult Login([FromBody] LoginParameters loginParameters) { var authController = new AuthController(); var site = MobileHelper.GetCurrentApplicationSite(); if (site == null) { return(StatusCode(System.Net.HttpStatusCode.Unauthorized)); } // // Chain to the existing login method for actual authorization check. // Throws exception if not authorized. // authController.Login(loginParameters); // // Find the user and translate to a mobile person. // var userLoginService = new UserLoginService(new Rock.Data.RockContext()); var userLogin = userLoginService.GetByUserName(loginParameters.Username); var mobilePerson = MobileHelper.GetMobilePerson(userLogin.Person, site); mobilePerson.AuthToken = MobileHelper.GetAuthenticationToken(loginParameters.Username); return(Ok(mobilePerson)); }
public ActiveDirectoryUserDto LoginAsync(LoginParameters parameters) { try { var username = _configuration["ActiveDirectory:ADUserName"]; var password = _configuration["ActiveDirectory:AdPassword"]; var container = _configuration["ActiveDirectory:ADContainer"]; var domain = _configuration["ActiveDirectory:ADDomain"]; using var context = new PrincipalContext(ContextType.Domain, domain, container, username, password); if (context.ValidateCredentials(parameters.Username, parameters.Password)) { using var userPrincipal = new UserPrincipal(context) { SamAccountName = parameters.Username }; using var principalSearcher = new PrincipalSearcher(userPrincipal); var result = principalSearcher.FindOne(); if (result != null) { DirectoryEntry de = (DirectoryEntry)result.GetUnderlyingObject(); string fName = de.Properties["givenName"]?.Value != null ? de.Properties["givenName"].Value.ToString() : ""; string lName = de.Properties["sn"]?.Value != null ? de.Properties["sn"].Value.ToString() : ""; string uName = de.Properties["samAccountName"]?.Value != null ? de.Properties["samAccountName"].Value.ToString() : ""; string principal = de.Properties["userPrincipalName"]?.Value != null ? de.Properties["userPrincipalName"].Value.ToString() : ""; string employeeId = de.Properties["employeeId"]?.Value != null ? de.Properties["employeeId"].Value.ToString() : ""; var user = new ActiveDirectoryUserDto { FirstName = fName, LastName = lName, LogonName = uName, EmployeeId = employeeId, Principal = principal }; return(user); } } return(null); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task <IActionResult> Login(LoginParameters parameters) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.SelectMany(state => state.Errors) .Select(error => error.ErrorMessage) .FirstOrDefault())); } var user = await _userManager.FindByNameAsync(parameters.UserName); if (user == null) { return(BadRequest("Taki użytkownik nie istnieje")); } var singInResult = await _signInManager.CheckPasswordSignInAsync(user, parameters.Password, false); if (!singInResult.Succeeded) { return(BadRequest("Niepoprawne hasło")); } await _signInManager.SignInAsync(user, parameters.RememberMe); return(Ok()); }
/// <summary> /// Webservice call to get user details. /// </summary> private void GetUserDetailsWebService() { string apiUrl = RxConstants.getUserDetails; try { LoginParameters objLoginparameters = new LoginParameters { Mail = App.LoginEmailId, Pharmacyid = App.LoginPharId.ToUpper(), Pin = App.HashPIN, system_version = "android", app_version = "1.6", branding_version = "MLP" }; WebClient userdetailswebservicecall = new WebClient(); var uri = new Uri(apiUrl, UriKind.RelativeOrAbsolute); var json = JsonHelper.Serialize(objLoginparameters); userdetailswebservicecall.Headers["Content-type"] = "application/json"; userdetailswebservicecall.UploadStringCompleted += userdetailswebservicecall_UploadStringCompleted; userdetailswebservicecall.UploadStringAsync(uri, "POST", json); } catch (Exception) { } }
public async void btnLogin_Clicked(object sender, EventArgs e) { var user = new LoginParameters(); user.Username = userNameEntry.Text; user.Password = passwordEntry.Text; user.Persisted = true; Login login = new Login(); if (!login.Authenticate(user)) { App.IsUserLoggedIn = false; statusLabel.Text = "Login Failed Please Try Again"; passwordEntry.Text = string.Empty; statusLabel.TextColor = Color.Red; } else { App.CurrentPerson = await Rock.People.GetCurrentPerson(); if (Device.OS == TargetPlatform.iOS) { await Navigation.PopToRootAsync(); } Application.Current.MainPage = new NavPage(); } }
public async Task <HttpResponseMessage> Login(LoginParameters LoginParameters) { var cts = new CancellationTokenSource(); var task = RemoteRequestAsync <HttpResponseMessage>(myBakeryApi.GetApi(Priority.UserInitiated).Login(LoginParameters)); runningTasks.Add(task.Id, cts); return(await task); }
public void Login(string peerId) { var peerOptions = new LoginParameters(peerId); var json = peerOptions.JsonObject(); Debug.Log(json); this.socket_.Emit("register", json); }
public static UserData_VM FromLoginResponse(LoginResponse loginResponse, LoginParameters loginParams) => new UserData_VM { UserID = int.Parse(loginResponse.UserID), Email = loginResponse.Email, Token = loginResponse.Token, PasswordHashCode = loginParams.Password.GetHashCode() };
public async Task <IResult> Login(LoginParameters parameter) { var repositoryResult = await _loginServices.Login(parameter); var result = ResponseHandler.GetResult(repositoryResult); return(result); }
public virtual IDataResult ExecuteFunction(IDataParameters Parameters) { DataResult dataResult = new DataResult(); LoginParameters LoginParameters = objectSerializationService.GetObjectsFromByteArray <LoginParameters>(Parameters.ParametersValue); dataResult.ResultValue = objectSerializationService.ToByteArray(this.Authenticate(LoginParameters)); return(dataResult); }
private void OnLogin(object parameter) { RaiseEvent(LoggingIn); var loginParms = new LoginParameters(UserName, Password, false, null); WebContext.Current.Authentication.Login(loginParms, LoginCallback, null); }
private static void SetAuth(IConfiguration configuration, LoginParameters loginParameters) { var hashProvider = HashProvider.GetDefault(); configuration.UserName = loginParameters.UserName; configuration.Password = hashProvider.ComputeHash(loginParameters.Password); configuration.Save(); }
public void NullParameters() { LoginParameters parameters = new LoginParameters(); Assert.IsNull(parameters.UserName, "UserName should be null."); Assert.IsNull(parameters.Password, "Password should be null."); }
internal void Login(string userName, string password, bool isPersistent, Action<LoginOperation> completedAction, object userState) { LoginParameters login = new LoginParameters(userName, password, isPersistent, null); CheckOKtoStartOperation(); m_Operation = UserContext.Authentication.Login(login, completedAction, userState); m_Operation.Completed += delegate(object sender, EventArgs e) { UpdateLastUserName(); }; }
public void Parameters() { string userName = "******"; string password = "******"; bool isPersistent = true; string customData = "customData"; LoginParameters parameters = new LoginParameters(userName, password, isPersistent, customData); Assert.AreEqual(userName, parameters.UserName, "UserNames should be equal."); Assert.AreEqual(password, parameters.Password, "Passwords should be equal."); Assert.AreEqual(isPersistent, parameters.IsPersistent, "IsPersistent states should be equal."); Assert.AreEqual(customData, parameters.CustomData, "CustomData should be equal."); }
public void LoginFailedAsync() { LoginParameters parameters = new LoginParameters(AuthenticationDomainClient.InvalidUserName, string.Empty); this.AsyncTemplate( (mock, service, callback, state) => { return service.BeginLoginMock(parameters, callback, state); }, (mock, service, asyncResult) => { LoginResult result = service.EndLoginMock(asyncResult); Assert.IsNotNull(result, "LoginResults should not be null."); Assert.IsFalse(result.LoginSuccess, "LoginSuccess should be false."); Assert.IsNull(result.User, "User should be null."); }); }
public IAsyncResult BeginLoginMock(LoginParameters parameters, AsyncCallback callback, object state) { return base.BeginLogin(parameters, callback, state); }
public void LoginCancel() { LoginParameters parameters = new LoginParameters(AuthenticationDomainClient.ValidUserName, string.Empty); this.CancelTemplate( (mock, service, callback, state) => { return service.BeginLoginMock(parameters, callback, state); }, (mock, service, asyncResult) => { service.CancelLoginMock(asyncResult); }, (mock, service, asyncResult) => { ExceptionHelper.ExpectException<InvalidOperationException>( () => Assert.IsNull(service.EndLoginMock(asyncResult), "This should fail.")); }); }
/// <summary> /// Copies the base properties from a source LoginParameters object /// </summary> /// <param name="source">The source.</param> public void CopyPropertiesFrom( LoginParameters source ) { this.Password = source.Password; this.Persisted = source.Persisted; this.Username = source.Username; }
public void LoginError() { LoginParameters parameters = new LoginParameters(AuthenticationDomainClient.ValidUserName, string.Empty); this.ErrorTemplate( (mock, service, callback, state) => { return service.BeginLoginMock(parameters, callback, state); }, (mock, service, asyncResult) => { ExceptionHelper.ExpectException<DomainOperationException>( () => Assert.IsNull(service.EndLoginMock(asyncResult), "This should fail."), string.Format(Resource.DomainContext_LoadOperationFailed, "Login", WebAuthenticationServiceTest.ErrorMessage)); }); }
protected override IAsyncResult BeginLogin(LoginParameters parameters, AsyncCallback callback, object state) { throw new NotSupportedException(WebContext_AuthenticationNotSet); }
public void LoginAsync() { LoginParameters parameters = new LoginParameters(AuthenticationDomainClient.ValidUserName, string.Empty); this.AsyncTemplate( (mock, service, callback, state) => { return service.BeginLoginMock(parameters, callback, state); }, (mock, service, asyncResult) => { LoginResult result = service.EndLoginMock(asyncResult); Assert.IsNotNull(result, "LoginResults should not be null."); Assert.IsTrue(result.LoginSuccess, "LoginSuccess should be true."); Assert.AreEqual(UserType.LoggedIn, ((MockUser)result.User).Type, "User should be of type LoggedIn."); }); }
public void LoginAsync(LoginParameters loginParameters) { AuthService.Login(loginParameters, LoginOperation_Completed, null); }
// private LoginOperation loginOperation; // private bool isSuccessful; public void Login(string userName, string password,Action<bool> onCompleted) { LoginParameters loginParameters = new LoginParameters(userName, password); WebContextBase.Current.Authentication.Login(loginParameters,loginOperation_Completed,onCompleted); }