public async Task AddClaimsAsync(ApplicationUser user, IEnumerable <Claim> claims, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); var taskList = new List <Task>(); foreach (Claim c in claims) { var userClaim = new ApplicationUserClaim { UserId = user.Id, ClaimType = c.Type, ClaimValue = c.Value }; taskList.Add(_unitOfWork.UserClaimRepository.Insert(userClaim)); } await Task.WhenAll(taskList); await _unitOfWork.CommitAsync(); } catch (Exception ex) { throw ex; } }
public async Task <ActionResult> Edit([Bind(Include = "Id,ClaimType,ClaimValue,IsActive,Discriminator")] ApplicationUserClaim claims) { if (ModelState.IsValid) { var claim = db.AspNetUserClaims.Find(claims.Id); claim.ClaimType = claims.ClaimType; claim.ClaimValue = claims.ClaimValue; claim.IsActive = claims.IsActive; await db.SaveChangesAsync(); this.AddNotification("Claims updated successfully.", NotificationType.SUCCESS); return(RedirectToAction("Index")); //var _controller = new AccountController(); //await _controller.UserManager.RemoveClaimAsync("", claims); //await _controller.UserManager.AddClaimAsync("", claims); //db.Entry(claims).State = EntityState.Modified; //await db.SaveChangesAsync(); //return RedirectToAction("Index"); } return(View(claims)); }
public async Task <IActionResult> Edit(int id, [Bind("Id,UserId,ClaimType,ClaimValue")] ApplicationUserClaim applicationUserClaim) { if (id != applicationUserClaim.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(applicationUserClaim); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ApplicationUserClaimExists(applicationUserClaim.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(applicationUserClaim)); }
public async Task <ActionResult <ApplicationUserClaim> > Delete(Int64 Id, ApplicationUserClaim _UserClaim) { try { string baseadress = config.Value.urlbase; HttpClient _client = new HttpClient(); _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token")); var result = await _client.PostAsJsonAsync(baseadress + "api/UserClaims/Delete", _UserClaim); string valorrespuesta = ""; if (result.IsSuccessStatusCode) { valorrespuesta = await(result.Content.ReadAsStringAsync()); _UserClaim = JsonConvert.DeserializeObject <ApplicationUserClaim>(valorrespuesta); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(BadRequest($"Ocurrio un error: {ex.Message}")); } return(new ObjectResult(new DataSourceResult { Data = new[] { _UserClaim }, Total = 1 })); }
protected override ApplicationUserClaim CreateUserClaim(TUser user, Claim claim) { var userClaim = new ApplicationUserClaim { UserId = user.Id }; userClaim.InitializeFromClaim(claim); return(userClaim); }
public async Task <IActionResult> Create([Bind("Id,UserId,ClaimType,ClaimValue")] ApplicationUserClaim applicationUserClaim) { if (ModelState.IsValid) { _context.Add(applicationUserClaim); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["UserId"] = new SelectList(_context.Users, "Id", "UserName", applicationUserClaim.UserId); return(View(applicationUserClaim)); }
public async Task <IActionResult> Create([Bind("Id,UserId,ClaimType,ClaimValue")] ApplicationUserClaim applicationUserClaim) { if (ModelState.IsValid) { applicationUserClaim.ClaimValue = applicationUserClaim.ClaimType; _context.Add(applicationUserClaim); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(applicationUserClaim)); }
public async Task <IActionResult> Create([Bind("Id,UserId,ClaimType,ClaimValue")] ApplicationUserClaim applicationUserClaim) { if (ModelState.IsValid) { var user = await _userManager.FindByIdAsync(applicationUserClaim.UserId.ToString()); await _userManager.AddClaimAsync( user, new Claim(applicationUserClaim.ClaimType, applicationUserClaim.ClaimValue)); return(RedirectToAction(nameof(Index))); } ViewData["UserId"] = new SelectList(_context.ApplicationUser, "Id", "Id", applicationUserClaim.UserId); return(View(applicationUserClaim)); }
// GET: /UserClaims/Edit/5 public async Task <ActionResult> Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ApplicationUserClaim claim = await db.AspNetUserClaims.FindAsync(id); if (claim == null) { return(HttpNotFound()); } return(View(claim)); }
public async Task <IActionResult> GetAspNetUserClaimsById(Int64 Id) { ApplicationUserClaim Items = new ApplicationUserClaim(); try { Items = await _context.UserClaims.Where(q => q.Id == Id).FirstOrDefaultAsync(); } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(BadRequest($"Ocurrio un error:{ex.Message}")); } return(await Task.Run(() => Ok(Items))); }
public async Task <ActionResult <ApplicationUserClaim> > Insert([FromBody] ApplicationUserClaim _AspNetUserClaims) { ApplicationUserClaim _AspNetUserClaimsq = new ApplicationUserClaim(); try { _AspNetUserClaimsq = _AspNetUserClaims; _context.UserClaims.Add(_AspNetUserClaimsq); await _context.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(BadRequest($"Ocurrio un error:{ex.Message}")); } return(await Task.Run(() => Ok(_AspNetUserClaimsq))); }
public int Update <TEntity>(TEntity entity, PrimaryKey key) { int rows = 0; ApplicationUser user = null; ApplicationUserClaim userClaim = null; if (typeof(TEntity) == typeof(ApplicationUser)) { user = users.FirstOrDefault(u => (int)u.PK.Key == (int)key.Key); //user = DeepCopy<ApplicationUser>(entity as ApplicationUser); user.PK = key; user.UserName = (entity as ApplicationUser).UserName; user.NormalizedUserName = (entity as ApplicationUser).UserName.ToUpper(); user.Email = (entity as ApplicationUser).Email; user.NormalizedEmail = (entity as ApplicationUser).Email.ToUpper(); user.EmailConfirmed = (entity as ApplicationUser).EmailConfirmed; user.PhoneNumber = (entity as ApplicationUser).PhoneNumber; user.PhoneNumberConfirmed = (entity as ApplicationUser).PhoneNumberConfirmed; user.PasswordHash = (entity as ApplicationUser).PasswordHash; user.TwoFactorEnabled = (entity as ApplicationUser).TwoFactorEnabled; user.Department = (entity as ApplicationUser).Department; user.DOB = (entity as ApplicationUser).DOB; user.Active = true; user.ModifiedDt = DateTime.Now; user.CreateDt = (entity as ApplicationUser).CreateDt; rows++; } else if (typeof(TEntity) == typeof(ApplicationUserClaim)) { userClaim = userClaims.FirstOrDefault(u => (int)u.PK.Key == (int)key.Key); //user = DeepCopy<ApplicationUser>(entity as ApplicationUser); userClaim.PK = key; userClaim.ClaimType = (entity as ApplicationUserClaim).ClaimType; userClaim.ClaimValue = (entity as ApplicationUserClaim).ClaimValue; userClaim.ClaimIssuer = (entity as ApplicationUserClaim).ClaimIssuer; userClaim.Active = true; userClaim.ModifiedDt = DateTime.Now; userClaim.CreateDt = (entity as ApplicationUserClaim).CreateDt; rows++; } return(rows); }
public async Task <ActionResult <ApplicationUserClaim> > SaveUserClaim([FromBody] UserClaimDTO _UserClaimS) { ApplicationUserClaim _UserClaim = _UserClaimS; try { // UserClaimDTO _li_UserClaim = new UserClaimDTO(); string baseadress = config.Value.urlbase; HttpClient _client = new HttpClient(); _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token")); var result = await _client.GetAsync(baseadress + "api/UserClaims/GetAspNetUserClaimsById/" + _UserClaim.Id); string valorrespuesta = ""; if (result.IsSuccessStatusCode) { valorrespuesta = await(result.Content.ReadAsStringAsync()); _UserClaim = JsonConvert.DeserializeObject <UserClaimDTO>(valorrespuesta); } if (_UserClaim == null) { _UserClaim = new Models.ApplicationUserClaim(); } if (_UserClaim.Id == 0) { var insertresult = await Insert(_UserClaimS); } else { var updateresult = await Update(_UserClaim.Id, _UserClaimS); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); throw ex; } return(Json(_UserClaim)); }
public async Task <IActionResult> Delete([FromBody] ApplicationUserClaim _AspNetUserClaims) { ApplicationUserClaim _AspNetUserClaimsq = new ApplicationUserClaim(); try { _AspNetUserClaimsq = _context.UserClaims .Where(x => x.Id == (Int64)_AspNetUserClaims.Id) .FirstOrDefault(); _context.UserClaims.Remove(_AspNetUserClaimsq); await _context.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(BadRequest($"Ocurrio un error:{ex.Message}")); } return(await Task.Run(() => Ok(_AspNetUserClaimsq))); }
public async Task SetClaimAsync(string userName, string claimType, string claimValue) { await InvokeUserManagerAsync(async (m, user) => { // Замена утверждения в коллекции пользователя var applicationUserClaims = user.Claims.Where(claim => !string.Equals(claim.Type.DisplayName, claimType, StringComparison.OrdinalIgnoreCase)).ToList(); var newClaim = new ApplicationUserClaim { Type = new ForeignKey { Id = claimType, DisplayName = claimType }, Value = claimValue }; applicationUserClaims.Add(newClaim); user.Claims = applicationUserClaims; return(await m.UpdateAsync(user)); }, userName); var currentIdentity = GetCurrentIdentity(); currentIdentity.SetClaim(claimType, claimValue); }
public int Delete <TEntity>(IPrimaryKey key) { int rows = 0; ApplicationUser user = null; ApplicationUserClaim userClaim = null; if (typeof(TEntity) == typeof(ApplicationUser)) { user = users.FirstOrDefault(u => u.Id == (int)key.Key); users.Remove(user); rows = 1; } else if (typeof(TEntity) == typeof(ApplicationUserClaim)) { userClaim = userClaims.FirstOrDefault(u => u.Id == (int)key.Key); userClaims.Remove(userClaim); rows = 1; } return(rows); }
public void ApplicationUserClaim_PublicProperties() { var testDate = DateTime.Today; var user = new ApplicationUser { Id = "123" }; var obj = new ApplicationUserClaim { CreatedAt = testDate, LastModifiedAt = testDate, CreatedBy = user, CreatedBy_Id = "123", LastModifiedBy = user, LastModifiedBy_Id = "123" }; Assert.AreEqual(testDate, obj.CreatedAt); Assert.AreEqual(testDate, obj.LastModifiedAt); Assert.AreEqual(user.Id, obj.CreatedBy_Id); Assert.AreEqual(user.Id, obj.LastModifiedBy_Id); }
public async Task <ActionResult <ApplicationUserClaim> > Update([FromBody] ApplicationUserClaim _AspNetUserClaims) { ApplicationUserClaim _AspNetUserClaimsq = new ApplicationUserClaim(); try { _AspNetUserClaimsq = await(from c in _context.UserClaims .Where(q => q.Id == _AspNetUserClaims.Id) select c ).FirstOrDefaultAsync(); _context.Entry(_AspNetUserClaimsq).CurrentValues.SetValues((_AspNetUserClaims)); //_context.UserClaims.Update(_AspNetUserClaimsq); await _context.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(BadRequest($"Ocurrio un error:{ex.Message}")); } return(await Task.Run(() => Ok(_AspNetUserClaimsq))); }
public object Add <TEntity>(TEntity entity, PrimaryKey key) { int newId = -1; ApplicationUser user = null; ApplicationUserClaim userClaim = null; ApplicationAuditLog auditLog = null; if (typeof(TEntity) == typeof(ApplicationUser)) { if (users == null) { newId = 1; } else { newId = users.Max(u => u.Id) + 1; } user = entity as ApplicationUser; key.Key = newId; user.PK = key; user.ModifiedDt = DateTime.Now; user.CreateDt = DateTime.Now; users.Add(user); } else if (typeof(TEntity) == typeof(ApplicationUserClaim)) { if (userClaims == null) { newId = 1; } else { newId = userClaims.Max(u => u.Id) + 1; } userClaim = entity as ApplicationUserClaim; key.Key = newId; userClaim.PK = key; userClaim.ModifiedDt = DateTime.Now; userClaim.CreateDt = DateTime.Now; userClaims.Add(userClaim); } else if (typeof(TEntity) == typeof(ApplicationAuditLog)) { if (logs.Count == 0) { newId = 1; } else { newId = logs.Max(u => u.Id) + 1; } auditLog = entity as ApplicationAuditLog; key.Key = newId; auditLog.PK = key; auditLog.CreateDt = DateTime.Now; logs.Add(auditLog); } return(newId); }
public async Task <ApplicationUser> RegisterUSer(RegisterDto request) { return(await ProcessRequest(async() => { if (request.Password != request.ConfirmPassword) { throw new AppException(_logger, "ConfirmPassword is not the same Password"); } var userName = await _unitOfWork.User.FindByNameAsync(request.UserName); if (userName != null) { throw new AppException(_logger, $"User Name: {request.UserName} is already taken"); } var userEmail = await _unitOfWork.User.FindByEmailAsync(request.Email); if (userEmail != null) { throw new AppException(_logger, $"User Email: {request.Email} is already taken"); } if (!request.Dob.HasValue) { throw new AppException(_logger, "Date of birth is required"); } var user = _mapper.Map <ApplicationUser>(request); if (user == null) { throw new AppException(_logger, "Register Failed"); } byte[] passwordHash, passwordSalt; CreatePasswordHash(request.Password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; user.NormalizedUserName = request.UserName.ToUpper(); user.NormalizedEmail = request.Email.ToUpper(); user.SecurityStamp = Guid.NewGuid().ToString("D"); await _unitOfWork.User.CreateAsync(user); var claims = new List <Claim>() { new Claim(ClaimTypes.GivenName, request.FirstName), new Claim(ClaimTypes.Surname, request.LastName), new Claim(ClaimTypes.Email, request.Email) }; foreach (var claim in claims) { var userClaim = new ApplicationUserClaim() { UserId = user.Id, ClaimType = claim.Type, ClaimValue = claim.Value }; await _unitOfWork.UserClaim.CreateAsync(userClaim); } await _unitOfWork.SaveAsync(); return user; })); }
public async Task <ActionResult> EditUser(ApplicationUserViewModel view) { ApplicationUserRepository userRepo; ApplicationRoleRepository roleRepo; ApplicationUserClaimRepository userClaimRepo; ApplicationAuditLogRepository logRepo; ApplicationUserClaim userClaim = null; IList <string> currentRoles = null; string role = String.Empty; int claimId = 0; int rows = 0; const string issuer = "Local Authority"; const string claimTypesDepartment = "Department"; bool isCurrentUser = view.User.UserName.ToUpper() == HttpContext.User.Identity.Name.ToUpper() ? true : false; try { userRepo = new ApplicationUserRepository(settings, logger, dbc); userClaimRepo = new ApplicationUserClaimRepository(settings, logger, dbc); roleRepo = new ApplicationRoleRepository(settings, logger, dbc); logRepo = new ApplicationAuditLogRepository(settings, logger, dbc); if (ModelState.IsValid) { // Update the user in the database userRepo.Update(view.User); //Add DOB claim to database and to claims list of the current user, if applicable userClaim = (userClaimRepo.FindAll()).FirstOrDefault(uc => uc.UserId == view.User.Id && uc.ClaimType == ClaimTypes.DateOfBirth); if (userClaim != null) { if (userClaim.ClaimValue != view.User.DOB.ToString("yyyy-MM-dd hh:mm:ss")) { userClaim.ModifiedDt = DateTime.Now; userClaim.ClaimValue = view.User.DOB.ToString("yyyy-MM-dd hh:mm:ss"); // Update the database userClaimRepo.Update(userClaim); logger.LogInformation($"Updated claim({ClaimTypes.DateOfBirth}) for user account: {view.User.UserName}"); } else { // Nothing changed, so no need to update the database } } else { // Add DOB claim to the database userClaim = new ApplicationUserClaim() { UserId = view.User.Id, ClaimType = ClaimTypes.DateOfBirth, ClaimValue = view.User.DOB.ToString("yyyy-MM-dd hh:mm:ss"), ClaimIssuer = issuer, Active = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now }; userClaimRepo.Add(userClaim); logger.LogInformation($"Added new claim({ClaimTypes.DateOfBirth}) to user account: {view.User.UserName}"); } //TODO: Department still has issues when transitioning from null to not null //Add Department claim to database and to claims list of the user userClaim = (userClaimRepo.FindAll()).FirstOrDefault(uc => uc.UserId == view.User.Id && uc.ClaimType == claimTypesDepartment); if (userClaim != null) { if (view.User.Department != null && userClaim.ClaimValue != view.User.Department) { userClaim.ModifiedDt = DateTime.Now; userClaim.ClaimValue = view.User.Department; userClaimRepo.Update(userClaim); logger.LogInformation($"Updated claim({claimTypesDepartment}) for user account: {view.User.UserName}"); } else { // Nothing changed, so no need to update the database } } else { if (view.User.Department != null) { userClaim = new ApplicationUserClaim() { UserId = view.User.Id, ClaimType = claimTypesDepartment, ClaimValue = view.User.Department, ClaimIssuer = issuer, Active = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now }; userClaimRepo.Add(userClaim); logger.LogInformation($"Assigned new claim({claimTypesDepartment}) to user account: {view.User.UserName}"); } } //Add Role claim to database and to claims list of the user // Process the roles and update the role store currentRoles = (userClaimRepo.FindAll()).Where(uc => uc.UserId == view.User.Id && uc.ClaimType == ClaimTypes.Role).Select(r => r.ClaimValue).ToList();; if (view.User.RoleBadges != null) { foreach (string r in view.User.RoleBadges.Split("|")) { if (r != String.Empty) { role = r.Substring(r.IndexOf('-') + 1, r.Length - r.IndexOf('-') - 1); // Add, if it's a new role if (!currentRoles.Contains(role)) { claimId = (int)userClaimRepo.Add(new ApplicationUserClaim() { UserId = view.User.Id, ClaimType = ClaimTypes.Role, ClaimValue = role, ClaimIssuer = issuer, Active = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now }); if (claimId > 0) { logger.LogInformation($"Assigned role({role}) to user account: {view.User.UserName}"); } else { logger.LogError($"Error assigning role({role}) to user account: {view.User.UserName}"); } } } } } // Remove any roles of which the user is no longer a member foreach (string r in currentRoles) { if (!view.User.RoleBadges.Contains(r)) { claimId = (userClaimRepo.FindAll()).FirstOrDefault(c => c.ClaimType == ClaimTypes.Role && c.UserId == view.User.Id).Id; rows = userClaimRepo.Delete(new PrimaryKey() { Key = (int)claimId, IsIdentity = true }); if (rows > 0) { logger.LogInformation($"Removed role({r}) from user account: {view.User.UserName}"); } else { logger.LogError($"Error removing role({r}) from account: {view.User.UserName}"); } } } // If we've updated the claims for the currently signed-in user, // then refresh Cookie by recreating the User Security Principal from the database if (isCurrentUser) { await identityManager.RefreshClaimsAsync(view.User, userClaimRepo.FindAll().Where(uc => uc.UserId == view.User.Id).ToList()); logRepo.Add(new ApplicationAuditLog() { CategoryId = 1, Description = $"User ({view.User.UserName}) logged into application with refreshed claims." }); logger.LogInformation($"Refreshed cookie for user: {view.User.UserName}"); } return(RedirectToAction("Index", "Account")); } else { userClaimRepo = new ApplicationUserClaimRepository(settings, logger, dbc); userRepo = new ApplicationUserRepository(settings, logger, dbc); view.User = userRepo.FindByPKView(new PrimaryKey() { Key = view.User.Id, IsIdentity = true }); view.Roles = roleRepo.FindAll(); // Update the RoleBadges foreach (ApplicationUserClaim uc in view.User.Claims.Where(uc => uc.UserId == view.User.Id)) { view.User.RoleBadges += String.Format("{0}-{1}|", uc.Id, uc.ClaimType); } return(View("EditUser", view)); } } catch (Exception ex) { throw (Exception)Activator.CreateInstance(ex.GetType(), ex.Message + ex.StackTrace); } }
public async Task <ActionResult> EditProfile(ApplicationUserViewModel view) { ApplicationUserRepository userRepo; ApplicationUserClaimRepository userClaimRepo; ApplicationAuditLogRepository logRepo; ApplicationUserClaim userClaim = null; ClaimsPrincipal userPrincipal = null; Claim dobClaim = null; Claim deptClaim = null; const string issuer = "Local Authority"; const string claimTypesDepartment = "Department"; try { userRepo = new ApplicationUserRepository(settings, logger, dbc); userClaimRepo = new ApplicationUserClaimRepository(settings, logger, dbc); logRepo = new ApplicationAuditLogRepository(settings, logger, dbc); if (ModelState.IsValid) { userRepo.Update(view.User); //Add DOB claim to database and to claims list of the user dobClaim = HttpContext.User.FindFirst(ClaimTypes.DateOfBirth); if (dobClaim != null) { ((ClaimsIdentity)HttpContext.User.Identity).RemoveClaim(dobClaim); userClaim = (userClaimRepo.FindAll()).FirstOrDefault(uc => uc.UserId == view.User.Id && uc.ClaimType == ClaimTypes.DateOfBirth); userClaim.ModifiedDt = DateTime.Now; userClaim.ClaimValue = view.User.DOB.ToString("yyyy-MM-dd hh:mm:ss"); userClaimRepo.Update(userClaim); } else { userClaimRepo.Add(new ApplicationUserClaim() { UserId = view.User.Id, ClaimType = ClaimTypes.DateOfBirth, ClaimValue = view.User.DOB.ToString("yyyy-MM-dd hh:mm:ss"), ClaimIssuer = issuer, Active = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now }); } ((ClaimsIdentity)HttpContext.User.Identity) .AddClaim(new Claim(ClaimTypes.DateOfBirth, view.User.DOB.ToString("yyyy-MM-dd hh:mm:ss"), ClaimValueTypes.String, issuer)); //Add Department claim to database and to claims list of the user if (view.User.Department != null) { deptClaim = HttpContext.User.FindFirst(claimTypesDepartment); if (deptClaim != null) { ((ClaimsIdentity)HttpContext.User.Identity).RemoveClaim(deptClaim); userClaim = (userClaimRepo.FindAll()).FirstOrDefault(uc => uc.UserId == view.User.Id && uc.ClaimType == claimTypesDepartment); userClaim.ModifiedDt = DateTime.Now; userClaim.ClaimValue = view.User.Department; userClaimRepo.Update(userClaim); } else { userClaimRepo.Add(new ApplicationUserClaim() { UserId = view.User.Id, ClaimType = claimTypesDepartment, ClaimValue = view.User.Department, ClaimIssuer = issuer, Active = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now }); } ((ClaimsIdentity)HttpContext.User.Identity) .AddClaim(new Claim(claimTypesDepartment, view.User.Department, ClaimValueTypes.String, issuer)); } // We've updated the claims for the currently signed-in user, // So refresh Cookie by recreating the User Security Principal from the database await identityManager.RefreshClaimsAsync(view.User, userClaimRepo.FindAll().Where(uc => uc.UserId == view.User.Id).ToList()); logRepo.Add(new ApplicationAuditLog() { CategoryId = 1, Description = $"User ({view.User.UserName}) logged into application with refreshed claims." }); // Refresh Cookie by recreating the User Security Principal from the current Identity Principal //userPrincipal = new ClaimsPrincipal(HttpContext.User.Identity); // Sign In User //await HttpContext.SignInAsync( // CookieAuthenticationDefaults.AuthenticationScheme, // userPrincipal, // new AuthenticationProperties() // { // IsPersistent = false // }); logger.LogInformation($"Refreshed cookie for user: {view.User.UserName}"); return(RedirectToAction("LoginSuccess", "Home")); } else { userClaimRepo = new ApplicationUserClaimRepository(settings, logger, dbc); userRepo = new ApplicationUserRepository(settings, logger, dbc); view.User = userRepo.FindByPKView(new PrimaryKey() { Key = view.User.Id, IsIdentity = true }); //view.Roles = ApplicationRole.Roles; return(View("EditProfile", view)); } } catch (Exception ex) { throw (Exception)Activator.CreateInstance(ex.GetType(), ex.Message + ex.StackTrace); } }
public async Task <object> UpdateUserAsync(ApplicationUserManager userManager, RhNetContext rhNetContext, ApplicationUserModel applicationUserModel) { ApplicationUser applicationUser = await userManager.FindByNameAsync(applicationUserModel.UserName); if (applicationUser == null) { return("Usuário não encontrado."); } applicationUser.Email = applicationUserModel.Email; applicationUser.Cpf = applicationUserModel.Cpf; List <ClientModel> clients = applicationUserModel.clients; List <ApplicationUserModel.UserRoleModel> roles = applicationUserModel.applicationRoles; List <ApplicationUserModel.UserPermissionModel> permissions = applicationUserModel.permissions; var result = await userManager.UpdateAsync(applicationUser); if (result.Succeeded) { var current_roles = await userManager.GetAllRolesAsync(applicationUserModel.UserName); var current_permissions = await userManager.GetAllClaimsAsync(applicationUserModel.UserName, "permission"); var current_clients = await userManager.GetClientsAsync(applicationUserModel.UserName); for (var i = 0; i < current_roles.Count(); i++) { if (roles.Where(e => e.ClientId == current_roles.ElementAt(i).ClientId&& e.RoleId == current_roles.ElementAt(i).RoleId).Count() == 0) { var client_id = current_roles.ElementAt(i).ClientId; ApplicationUserRole applicationUserRole = await(from x in rhNetContext.UserRoles where x.ClientId == client_id && x.RoleId == current_roles.ElementAt(i).RoleId&& x.UserId == applicationUserModel.UserId select x).FirstOrDefaultAsync(); if (applicationUserRole != null) { rhNetContext.Entry(applicationUserRole).State = EntityState.Deleted; } } } for (var i = 0; i < current_permissions.Count(); i++) { if (permissions.Where(e => e.ClientId == current_permissions.ElementAt(i).ClientId).Count() == 0) { var client_id = current_permissions.ElementAt(i).ClientId; var description = current_permissions.ElementAt(i).Description; ApplicationUserClaim applicationUserClaim = await(from x in rhNetContext.UserClaims where x.ClientId == client_id && x.ClaimValue == description && x.UserId == applicationUserModel.UserId select x).FirstOrDefaultAsync(); if (applicationUserClaim != null) { rhNetContext.Entry(applicationUserClaim).State = EntityState.Deleted; } } } for (var i = 0; i < current_clients.Count(); i++) { if (clients.Where(e => e.Id == current_clients.ElementAt(i).Id).Count() == 0) { var client_id = current_clients.ElementAt(i).Id; UserClient userClient = await(from x in rhNetContext.UserClients where x.ClientId == client_id && x.UserId == applicationUserModel.UserId select x).FirstOrDefaultAsync(); if (userClient != null) { rhNetContext.Entry(userClient).State = EntityState.Deleted; } } } for (var i = 0; i < roles.Count(); i++) { if (current_roles.Where(e => e.ClientId == roles.ElementAt(i).ClientId&& e.RoleId == roles.ElementAt(i).RoleId).Count() == 0) { ApplicationUserRole applicationUserRole = new ApplicationUserRole() { ClientId = roles[i].ClientId, UserId = applicationUser.Id, RoleId = roles[i].RoleId }; rhNetContext.Entry(applicationUserRole).State = EntityState.Added; } } for (var i = 0; i < permissions.Count(); i++) { if (current_permissions.Where(e => e.ClientId == permissions.ElementAt(i).ClientId&& e.Description == permissions.ElementAt(i).Description).Count() == 0) { ApplicationUserClaim applicationUserClaim = new ApplicationUserClaim() { ClientId = permissions[i].ClientId, UserId = applicationUser.Id, ClaimType = "permission", ClaimValue = permissions[i].Description }; rhNetContext.Entry(applicationUserClaim).State = EntityState.Added; } } for (var i = 0; i < clients.Count(); i++) { if (current_clients.Where(e => e.Id == clients.ElementAt(i).Id).Count() == 0) { UserClient userClient = new UserClient() { ApplicationUser = applicationUser, ClientId = clients[i].Id }; rhNetContext.Entry(userClient).State = EntityState.Added; } } await rhNetContext.SaveChangesAsync(); return(applicationUserModel); } else { var errorList = result.Errors.ToList(); string errors = ""; for (var i = 0; i < errorList.Count; i++) { errors += errorList.ElementAt(i) + " "; } return(errors); } }
public async Task <object> AddUserAsync(ApplicationUserManager userManager, RhNetContext rhNetContext, ApplicationUserModel applicationUserModel) { ApplicationUser applicationUser = new ApplicationUser() { UserName = applicationUserModel.UserName, Email = applicationUserModel.Email, Cpf = applicationUserModel.Cpf }; List <ClientModel> clients = applicationUserModel.clients; List <ApplicationUserModel.UserRoleModel> roles = applicationUserModel.applicationRoles; List <ApplicationUserModel.UserPermissionModel> permissions = applicationUserModel.permissions; var result = await userManager.CreateAsync(applicationUser, "Mm123456*"); if (result.Succeeded) { applicationUser = await userManager.FindByNameAsync(applicationUser.UserName); for (var i = 0; i < roles.Count(); i++) { ApplicationUserRole applicationUserRole = new ApplicationUserRole() { ClientId = roles[i].ClientId, UserId = applicationUser.Id, RoleId = roles[i].RoleId }; rhNetContext.Entry(applicationUserRole).State = EntityState.Added; } for (var i = 0; i < permissions.Count(); i++) { ApplicationUserClaim applicationUserClaim = new ApplicationUserClaim() { ClientId = permissions[i].ClientId, UserId = applicationUser.Id, ClaimType = "permission", ClaimValue = permissions[i].Description }; rhNetContext.Entry(applicationUserClaim).State = EntityState.Added; } for (var i = 0; i < clients.Count(); i++) { UserClient userClient = new UserClient() { ApplicationUser = applicationUser, ClientId = clients[i].Id }; rhNetContext.Entry(userClient).State = EntityState.Added; } await rhNetContext.SaveChangesAsync(); return(applicationUserModel); } else { var errorList = result.Errors.ToList(); string errors = ""; for (var i = 0; i < errorList.Count; i++) { errors += errorList.ElementAt(i) + " "; } return(errors); } }
public async Task <string> ExternalLoginCallback() { return(await ProcessRequest(async() => { ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { throw new AppException(_logger, "Failed to get information"); } ApplicationUser userEmailExists = await _unitOfWork.User.FindByEmailAsync(info.Principal.FindFirst(ClaimTypes.Email).Value); if (userEmailExists == null) { ApplicationUser appUser = new ApplicationUser() { Email = info.Principal.FindFirst(ClaimTypes.Email).Value, UserName = info.Principal.FindFirst(ClaimTypes.Email).Value, FirstName = info.Principal.FindFirst(ClaimTypes.GivenName).Value, LastName = info.Principal.FindFirst(ClaimTypes.Surname).Value, EmailConfirmed = true, }; await _unitOfWork.User.CreateAsync(appUser); await _unitOfWork.SaveAsync(); List <Claim> claims = new List <Claim>() { new Claim(ClaimTypes.GivenName, appUser.FirstName), new Claim(ClaimTypes.Surname, appUser.LastName), new Claim(ClaimTypes.Email, appUser.Email), }; AddToRoleDto role = new AddToRoleDto() { RoleName = "USER", UserName = appUser.UserName }; await _roleService.AddUserToRole(role); foreach (var claim in claims) { var userClaim = new ApplicationUserClaim() { UserId = appUser.Id, ClaimType = claim.Type, ClaimValue = claim.Value }; await _unitOfWork.UserClaim.CreateAsync(userClaim); } await _unitOfWork.SaveAsync(); return _tokenService.GenerateJWTToken(appUser, 1); } else { userEmailExists.Email = info.Principal.FindFirst(ClaimTypes.Email).Value; userEmailExists.FirstName = info.Principal.FindFirst(ClaimTypes.GivenName).Value; userEmailExists.LastName = info.Principal.FindFirst(ClaimTypes.Surname).Value; userEmailExists.UserName = info.Principal.FindFirst(ClaimTypes.Email).Value; userEmailExists.EmailConfirmed = true; _unitOfWork.User.Update(userEmailExists); await _unitOfWork.SaveAsync(); return _tokenService.GenerateJWTToken(userEmailExists, 1); } })); }