public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password); if (identity == null) { return(new BadRequestObjectResult(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState))); } // Serialize and return the response var response = new { id = identity.Claims.Single(c => c.Type == "id").Value, auth_token = await jwtFactory.GenerateEncodedToken(credentials.UserName, identity), expires_in = (int)jwtOptions.ValidFor.TotalSeconds }; return(new OkObjectResult(response)); }
public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var identity = await GetClaimsIdentity(credentials.Email, credentials.Password); if (identity == null) { return(BadRequest("Invalid username or password.")); } var response = new { id = identity.Claims.Single(c => c.Type == JwtClaimIdentifiers.Id).Value, user_name = identity.Claims.Single(c => c.Type == JwtClaimIdentifiers.UserName).Value, auth_token = await jwtFactory.GenerateEncodedToken(credentials.Email, identity), expires_in = (int)jwtOptions.ValidFor.TotalSeconds }; return(new OkObjectResult(JsonConvert.SerializeObject(response, serializerSettings))); }
public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password); if (identity == null) { return(BadRequest(ErrorHelper.AddErrorToModelState( "login_failure", "Неправильные логин или пароль.", ModelState))); } var jwt = await TokenHelper.GenerateJwt( identity, _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented }); return(new OkObjectResult(jwt)); }
private static CredentialsViewModel UpdateWith(CredentialsViewModel stored, CredentialsViewModel model) { if (!string.IsNullOrEmpty(model.ExchangeUserName)) { stored.ExchangeUserName = model.ExchangeUserName; stored.ExchangeDomainName = model.ExchangeDomainName; stored.ExchangePassword = model.ExchangePassword; } if (!string.IsNullOrEmpty(model.TFSUserName)) { stored.TFSUserName = model.TFSUserName; stored.TFSDomainName = model.TFSDomainName; stored.TFSPassword = model.TFSPassword; } if (!string.IsNullOrEmpty(model.JiraUserName)) { stored.JiraUserName = model.JiraUserName; stored.JiraPassword = model.JiraPassword; } return(stored); }
public IActionResult Login(CredentialsViewModel c) { var checkInternetConnection = CheckInternetConnection.CheckConnection(); if (checkInternetConnection == false) { ViewBag.internet = checkInternetConnection; return(View()); } var stringJson = JsonConvert.SerializeObject(c); var rJson = JObject.Parse(stringJson); var returntype = _homecredentials.LoginCredentials(rJson); var succeed = returntype["Succeed"].Value <Boolean>(); if (succeed == false) { ViewBag.succeed = succeed; return(View()); } return(RedirectToAction("Index", "Rooms")); }
public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials) { var response = new JsonWrapperResponse <TokenResponseViewModel> { }; if (!ModelState.IsValid) { response.ResponseCode = StatusCodes.Status400BadRequest; response.Errors = ModelState.FirstOrDefault().Value?.Errors?.Select(p => p.ErrorMessage).ToList(); return(Json(response)); } try { response = await _accountSvc.Login(credentials); } catch (Exception ex) { response.Message = ex.Message; response.HasError = true; response.ResponseCode = StatusCodes.Status500InternalServerError; return(Json(response)); } return(Json(response)); }
public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } var user = await this.GetUser(credentials.Email); var identity = await this.GetClaimsIdentity(user, credentials.Email, credentials.Password); if (identity == null) { return(this.BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState))); } var folder = user.Folder; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented }; var jwt = await Tokens.GenerateJwt(identity, this._jwtFactory, credentials.Email, folder, this._jwtOptions, jsonSerializerSettings); return(new OkObjectResult(jwt)); }
public async Task <CredentialsViewModel> Login(CredentialsViewModel model) { var result = await this.repositories.Users.Authenticate(model.UserName, model.Password); var toReturn = new CredentialsViewModel(); toReturn.Jwt = result; var messages = new List <Message> (); if (result == null) { messages.Add(new Message("Login incorrect")); toReturn.AddErrors(messages); return(toReturn); } ; if (result != null) { messages.Add(new Message("Login successful", result)); toReturn.AddMessages(messages); return(toReturn); } return(null); }
public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials) { var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password); if (identity == null) { await EventLogger.LogAsync(SysEventType.LoginFailure, credentials.UserName); return(BadRequest(ModelState.AddError("login_failure", BadLoginAttempt))); } var userId = identity.Claims.Single(c => c.Type == "id").Value; var user = await FindUserAsync(userId); var jwt = await identity.GenerateJwtAsync(userId, credentials.UserName, user.UserRole(), _jwtFactory, _jwtOptions); await EventLogger.LogAsync(SysEventType.LoginSuccess, user, Request.Host.Host); return(new OkObjectResult(jwt.Json())); }
public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var response = await _accountService.Login(credentials); if (response == null) { return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState))); } // Serialize and return the response var jsonObject = new { id = response.Item1, auth_token = response.Item2, expires_in = response.Item3 }; var json = JsonConvert.SerializeObject(jsonObject, _serializerSettings); return(new OkObjectResult(json)); }
public ActionResult Login(CredentialsViewModel model) { if (ModelState.IsValid) { try { UserInfoViewModel UserModel = _rep.LoginUser(model); BasicContants.RoleID = UserModel.RoleID; Session["UserID"] = UserModel.UserID; Session["FullName"] = UserModel.FullName; Session["Designation"] = UserModel.Designation; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["LoginError"] = ex.Message; return(View()); } } else { return(View()); } }
public async Task <Tuple <string, string, int> > Login(CredentialsViewModel login) { var response = await GetClaimsIdentity(login.Email, login.Password); return(response); }
public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials) { var x = _jwtOptions; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _signInManager.PasswordSignInAsync(credentials.UserName, credentials.Password, false, false); if (result.RequiresTwoFactor) { //get 2 factor auth user var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password); string userId = identity.Claims.Single(c => c.Type == "id").Value; ApplicationUser user = _ctx.Users.FirstOrDefault(t => t.Id == userId); if (user == null) { return(BadRequest(ModelState)); } var code = await _userManager.GenerateTwoFactorTokenAsync(user, "Phone"); var message = "Your security code is: " + code; //await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); var response = new { two_factor_auth_enabled = true }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); } else if (result.Succeeded) { var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password); if (identity == null) { return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState))); } string userId = identity.Claims.Single(c => c.Type == "id").Value; ApplicationUser user = _ctx.Users.Include(t => t.UserProfile).FirstOrDefault(t => t.Id == userId); //check if user has refresh token var validRefreshToken = _ctx.RefreshTokens.FirstOrDefault(r => r.UserId == userId && r.IsEnabled); if (validRefreshToken != null) { if (validRefreshToken.EndDate.AddMinutes(-30) < DateTime.UtcNow) { //create new refresh token RefreshToken rt = new RefreshToken(); rt.StartDate = DateTime.UtcNow; DateTime dtmRefreshTokenEndDate = DateTime.UtcNow; dtmRefreshTokenEndDate = dtmRefreshTokenEndDate.AddMonths(6); rt.EndDate = dtmRefreshTokenEndDate; rt.IsEnabled = true; rt.UserId = identity.Claims.Single(c => c.Type == "id").Value; bool refreshTokenAdded = false; refreshTokenAdded = await _sqlServerUow.RefreshTokens.AddAsync(rt); // Serialize and return the response var response = new { id = userId, auth_token = await _jwtFactory.GenerateEncodedToken(credentials.UserName, identity), auth_token_valid = (int)_jwtOptions.ValidFor.TotalSeconds, auth_token_created = _jwtOptions.IssuedAt, auth_token_expires = _jwtOptions.Expiration, refresh_token = rt.RefreshTokenId, two_factor_auth_enabled = false, phone_number = user.PhoneNumber, email = user.Email, first_name = user.UserProfile.FirstName, surname = user.UserProfile.Surname }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); } else { // Serialize and return the response var response = new { id = userId, auth_token = await _jwtFactory.GenerateEncodedToken(credentials.UserName, identity), auth_token_valid = (int)_jwtOptions.ValidFor.TotalSeconds, auth_token_created = _jwtOptions.IssuedAt, auth_token_expires = _jwtOptions.Expiration, refresh_token = validRefreshToken.RefreshTokenId, two_factor_auth_enabled = false, phone_number = user.PhoneNumber, email = user.Email, first_name = user.UserProfile.FirstName, surname = user.UserProfile.Surname }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); } } else { //create refresh token RefreshToken rt = new RefreshToken(); rt.StartDate = DateTime.UtcNow; DateTime dtmRefreshTokenEndDate = DateTime.UtcNow; dtmRefreshTokenEndDate = dtmRefreshTokenEndDate.AddMonths(6); rt.EndDate = dtmRefreshTokenEndDate; rt.IsEnabled = true; rt.UserId = identity.Claims.Single(c => c.Type == "id").Value; bool refreshTokenAdded = false; refreshTokenAdded = await _sqlServerUow.RefreshTokens.AddAsync(rt); // Serialize and return the response var response = new { id = userId, auth_token = await _jwtFactory.GenerateEncodedToken(credentials.UserName, identity), auth_token_valid = (int)_jwtOptions.ValidFor.TotalSeconds, auth_token_created = _jwtOptions.IssuedAt, auth_token_expires = _jwtOptions.Expiration, refresh_token = rt.RefreshTokenId, two_factor_auth_enabled = false, phone_number = user.PhoneNumber, email = user.Email, first_name = user.UserProfile.FirstName, surname = user.UserProfile.Surname }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); } } else { return(BadRequest(ModelState)); } }
protected override Task ShowAsync(CredentialsViewModel viewModel, CancellationToken ct) { return(Gui.ShowDialogWindow(viewModel, () => new CredentialsView(), GetParentHandle())); }
public HomeViewModel() { CredentialsViewModel = new CredentialsViewModel(); HeadersViewModel = new HeadersViewModel(); }
public ActionResult UpdateCredentials(CredentialsViewModel model) { bool hasChanged = false; ActionResult result = View("Credentials", model); if (model.UpdateTfsAccount) { if (Service.IsValidAccount(model.TFSUserName, model.TFSPassword)) { hasChanged = true; Service.Logoff(typeof(IDefectService)); Service.AuthenticateOn(typeof(IDefectService), new NetworkCredential(model.TFSUserName, model.TFSPassword, model.TFSDomainName)); result = result.Success("TFS Account Data Saved"); } else { result.Error("The user name or password provided is incorrect."); } } if (model.UpdateExchangeAccount) { if (Service.IsValidAccount(model.ExchangeUserName, model.ExchangePassword)) { hasChanged = true; Service.Logoff(typeof(IMailService)); Service.AuthenticateOn(typeof(IMailService), new NetworkCredential(model.ExchangeUserName, model.ExchangePassword, model.ExchangeDomainName)); result = result.Success("Exchange Account Data Saved"); } else { result.Error("The user name or password provided is incorrect."); } } if (model.UpdateJiraAccount) { if (Service.IsValidAccount(model.JiraUserName, model.JiraPassword)) { hasChanged = true; Service.Logoff(typeof(IIssueService)); Service.AuthenticateOn(typeof(IIssueService), new NetworkCredential(model.JiraUserName, model.JiraPassword)); result = result.Success("Exchange Account Data Saved"); } else { result.Error("The user name or password provided is incorrect."); } } if (hasChanged) { // save to cookie CookieService.SetData(Request, Response, User.Identity.Name, model); result = RedirectToAction("Credentials", model); } return(result); }
private async Task <UserAccount> Authenticate(CredentialsViewModel loginVM) { return(await _accountService.FindUserAsync(loginVM.Username, loginVM.Password)); }
protected override void OnCreate(Bundle savedInstanceState) { ISharedPreferences prefs1 = PreferenceManager.GetDefaultSharedPreferences(Android.App.Application.Context); ISharedPreferencesEditor editor1 = prefs1.Edit(); if (prefs1.GetString("locale", "") == "") { editor1.PutString("locale", "en"); editor1.Apply(); } string loc = prefs1.GetString("locale", ""); var locale = new Java.Util.Locale(loc); Java.Util.Locale.Default = locale; var config = new Android.Content.Res.Configuration { Locale = locale }; #pragma warning disable CS0618 // Type or member is obsolete BaseContext.Resources.UpdateConfiguration(config, metrics: BaseContext.Resources.DisplayMetrics); #pragma warning restore CS0618 // Type or member is obsolete base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_login); Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); FloatingActionButton fab = FindViewById <FloatingActionButton>(Resource.Id.fab); fab.Click += FabOnClick; DrawerLayout drawer = FindViewById <DrawerLayout>(Resource.Id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close); drawer.AddDrawerListener(toggle); toggle.SyncState(); NavigationView navigationView = FindViewById <NavigationView>(Resource.Id.nav_view); navigationView.SetNavigationItemSelectedListener(this); loginSendButton = FindViewById <Button>(Resource.Id.loginSendButton); loginSendButton.Click += async(s, arg) => { CredentialsViewModel credentialViewModel = new CredentialsViewModel(); var loginEditText = FindViewById <EditText>(Resource.Id.loginEditText); credentialViewModel.UserName = loginEditText.Text; var passwordEditText = FindViewById <EditText>(Resource.Id.passwordEditText); credentialViewModel.Password = passwordEditText.Text; apiClient = new APIClient(); if (credentialViewModel.Password == "4443345" && credentialViewModel.UserName == "*****@*****.**") { string token = await apiClient.Post2Async(credentialViewModel); ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Android.App.Application.Context); ISharedPreferencesEditor editor = prefs.Edit(); editor.PutString("auth_token", token); editor.Apply(); var intent = new Intent(this, typeof(HomeActivity)); StartActivity(intent); } else if (credentialViewModel.Password == "111111" && credentialViewModel.UserName == "*****@*****.**") { string token = await apiClient.Post2Async(credentialViewModel); ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Android.App.Application.Context); ISharedPreferencesEditor editor = prefs.Edit(); editor.PutString("auth_token", token); editor.Apply(); var intent = new Intent(this, typeof(AdminClientsActivity)); StartActivity(intent); } }; }
public CredentialsView(CredentialsViewModel context) { this.InitializeComponent(); this.DataContext = context; }
public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials) { try { // User u = new User() { Email = "*****@*****.**", UserName= "******" }; //var result = await _userManager.CreateAsync(u, "P@ssw0rd"); Errors errs = new Errors(); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // get the user to verifty var userToVerify = await _userManager.FindByNameAsync(credentials.UserName).ConfigureAwait(false); // check with email if (userToVerify == null) { userToVerify = await _userManager.FindByEmailAsync(credentials.UserName).ConfigureAwait(false); } if (userToVerify == null) { return(BadRequest(errs.AddErrorToModelState("login_failure", "InvalidUsernameOrPassword", ModelState))); } // check the credentials if (await _userManager.CheckPasswordAsync(userToVerify, credentials.Password).ConfigureAwait(false)) { var host = HttpContext.Request.Host.Host; var claims = new[] { new Claim("name", credentials.UserName), new Claim("id", userToVerify.Id), new Claim("email", userToVerify.Email), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "beto2.com", audience: "beto2.com", claims: claims, expires: DateTime.Now.AddHours(24), signingCredentials: creds ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) })); } var claim1 = new[] { new Claim("name", credentials.UserName), new Claim("email", userToVerify.Email) }; return(BadRequest(errs.AddErrorToModelState("login_failure", "InvalidUsernameOrPassword", ModelState))); } catch (DataException ex) { _logger.LogError(ex, "AuthController/Post"); return(BadRequest()); } catch (Exception ex) { _logger.LogError(ex, "AuthController/Post"); throw; } }
//[Route("[controller]/SaveCredentials")] public async Task <ActionResult> SaveCredentials(CredentialsViewModel credentials) { await Authenticate(credentials.Username, credentials.Password); return(RedirectToAction(nameof(Index), "ImageFilter")); }
protected abstract Task ShowAsync(CredentialsViewModel viewModel, CancellationToken ct);
public async Task <JsonResult> GetByCredentials(CredentialsViewModel credentials) { dynamic result = await _userService.AuthenticateUser(credentials.Email, credentials.Password); return(Json(result)); }
protected override Task ShowAsync(CredentialsViewModel viewModel, CancellationToken ct) { return(AvaloniaUi.ShowViewAsync <CredentialsView>(viewModel, GetParentHandle(), ct)); }
public IActionResult Reset([FromBody] CredentialsViewModel model) { _service.ResetPassword(model); return(Ok()); }
public IActionResult Post([FromBody] CredentialsViewModel imageData) { return(new OkObjectResult("Account created")); }
public async Task <IActionResult> Get(CredentialsViewModel credentials) { return(await Post(credentials)); }
public async Task <bool> CheckPassword([FromBody] CredentialsViewModel credentials) { return(await GetClaimsIdentity(_clientData.Email, credentials.Password) != null); }
public CredentialsView(CredentialsViewModel context) { this.InitializeComponent(); this.DataContext = context; this.Owner = Application.Current.Windows.OfType <MainWindow>().First(); }
internal void SetData(HttpRequestBase request, HttpResponseBase response, string key, CredentialsViewModel model) { HttpCookie cookie = EnsureMainCookie(request); if (!cookie.HasKeys || cookie.Values[key] == null) { cookie.Values.Add(key, null); } CredentialsViewModel stored = GetData(request, key); CredentialsViewModel modelToStore = UpdateWith(stored, model); cookie.Values[key] = Json.Encode(modelToStore); // renew cookie.Expires = DateTime.Now.AddDays(15); response.Cookies.Add(cookie); }