public async Task <Guid> AddUser(Register register) { if (await _context.Users.AnyAsync(u => u.UserName == register.UserName)) { throw new Exception("Username already exists"); } var user = new User() { FirstName = register.FirstName, LastName = register.LastName, UserName = register.UserName.ToLower(), EmailAddress = register.EmailAddress, CreatedDate = DateTime.UtcNow }; _passwordHasher.CreatePasswordHash(register.Password, out byte[] passwordHash, out byte[] passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; await _context.Users.AddAsync(user); await _context.SaveChangesAsync(); return(user.UserId); }
public async Task <IActionResult> PutApplicationRole(string id, ApplicationRole applicationRole) { if (id != applicationRole.Id) { return(BadRequest()); } _context.Entry(applicationRole).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ApplicationRoleExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <AuthResult> RefreshTokenAsync(RefreshTokenRequest refreshToken) { var validatedToken = GetPrincipalFromToken(refreshToken.Token); if (validatedToken == null) { throw new BadRequestException("Invalid Token"); } var expiryDateUnix = long.Parse(validatedToken.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Exp).Value); var expiryDateTimeUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) .AddSeconds(expiryDateUnix); if (expiryDateTimeUtc > DateTime.UtcNow) { throw new BadRequestException("This token hasn't expired yet"); } var jti = validatedToken.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Jti).Value; var storedRefreshToken = await _context.RefreshTokens.SingleOrDefaultAsync(x => x.Token == refreshToken.RefreshToken); if (storedRefreshToken == null) { throw new BadRequestException("This refresh token does not exist"); } if (DateTime.UtcNow > storedRefreshToken.ExpiryDate) { throw new BadRequestException("This refresh token has expired"); } if (storedRefreshToken.Invalidated) { throw new BadRequestException("This refresh token has been invalidated"); } if (storedRefreshToken.Used) { throw new BadRequestException("This refresh token has been used"); } if (storedRefreshToken.JwtId != jti) { throw new BadRequestException("This refresh token does not match this JWT"); } storedRefreshToken.Used = true; _context.RefreshTokens.Update(storedRefreshToken); await _context.SaveChangesAsync(); var user = await _userManager.FindByIdAsync(validatedToken.Claims.Single(x => x.Type == "id").Value); return(await GenerateAuthResultForUserAsync(user)); }
public async Task <IHttpActionResult> PostApplicationResource(ApplicationResource applicationResource) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } applicationResource.Id = Guid.NewGuid().ToString(); db = Request.GetOwinContext().Get <SecurityDbContext>(); db.Resources.Add(applicationResource); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (ApplicationResourceExists(applicationResource.Id)) { return(Conflict()); } throw; } return(Ok(applicationResource.Id)); }
public async Task <IHttpActionResult> PutApplicationResource(ApplicationResource applicationResource) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (applicationResource.Id == null) { return(BadRequest()); } db = Request.GetOwinContext().Get <SecurityDbContext>(); db.Entry(applicationResource).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ApplicationResourceExists(applicationResource.Id)) { return(NotFound()); } throw; } return(Ok(applicationResource)); }
public override async Task <AddUserResponse> AddUser(AddUserRequest request, ServerCallContext context) { if (!Guid.TryParse(request.CustomerId.Value, out Guid customerId)) { throw new RpcException( Status.DefaultCancelled, $"Could not parse {nameof(request.CustomerId)}" ); } var user = new User { Id = Guid.NewGuid(), CustomerId = customerId, Username = request.Username, Firstname = request.Firstname, Lastname = request.Lastname, StatusId = request.StatusId }; using (var dbContext = new SecurityDbContext(this.securityDbContextOptions)) { await dbContext.AddAsync(user); await dbContext.SaveChangesAsync(); } return(await Task.FromResult(new AddUserResponse { Id = new UUID { Value = user.Id.ToString() } })); }
public async Task Update(Truck value) { SecurityDbContext dbContext = _securityDbContextFactory.CreateDbContext(); dbContext.Trucks.Update(value); await dbContext.SaveChangesAsync(); }
public async Task <IHttpActionResult> PostApplicationRole(ApplicationRole applicationRole) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } applicationRole.Id = Guid.NewGuid().ToString(); db = Request.GetOwinContext().Get <SecurityDbContext>(); db.ApplicationRoles.Add(applicationRole); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (ApplicationRoleExists(applicationRole.Id)) { return(Conflict()); } throw; } return(Ok(applicationRole.Id)); // return CreatedAtRoute("DefaultApi", new { id = applicationRole.Id }, applicationRole); }
public async Task <bool> UpdateUserRoles(IEnumerable <UserRoleModel> newValues) { var existing = await _securityDbContext.UserRoles.ToListAsync(); foreach (var e in existing) { if (!newValues.Any(x => x.RoleId == e.RoleId && x.UserId == e.UserId)) { _securityDbContext.UserRoles.Remove(e); } } foreach (var x in newValues) { if (!existing.Any(e => x.RoleId == e.RoleId && x.UserId == e.UserId)) { _securityDbContext.UserRoles.Add(new UserRole { RoleId = x.RoleId, UserId = x.UserId }); } } try { await _securityDbContext.SaveChangesAsync(); } catch { return(false); } return(true); }
public async Task <Truck> CreateAsync(Truck value) { SecurityDbContext dbContext = _securityDbContextFactory.CreateDbContext(); var newTruck = (await dbContext.Trucks.AddAsync(value)).Entity; await dbContext.SaveChangesAsync(); return(newTruck); }
public async Task UpdateSecurityStatusAsync(string plate, SecurityStatus securityStatus) { SecurityDbContext dbContext = _securityDbContextFactory.CreateDbContext(); Truck existingTruck = await this.GetAsync(plate); existingTruck.SecurityStatus = securityStatus; await dbContext.SaveChangesAsync(); }
// POST: api/ApplicationUserRoles public async Task <IHttpActionResult> Post(AppUserRolesViewModel vm) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } IdentityUserRole userRole = db.ApplicationUserRoles.FirstOrDefault(x => x.UserId == vm.UserId && x.RoleId == vm.RoleId); if (userRole == null) { userRole = db.ApplicationUserRoles.Add(new IdentityUserRole { RoleId = vm.RoleId, UserId = vm.UserId }); await db.SaveChangesAsync(); } return(Ok(userRole.UserId)); }
public async Task DeleteAsync(string plate) { SecurityDbContext dbContext = _securityDbContextFactory.CreateDbContext(); Truck truckToDelete = new Truck() { LicensePlate = plate }; dbContext.Entry(truckToDelete).State = EntityState.Deleted; await dbContext.SaveChangesAsync(); }
public async Task <IHttpActionResult> Post(ApplicationPermission permission) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ApplicationPermission applicationPermission = db.Permissions.FirstOrDefault(x => x.ResourceId == permission.ResourceId && x.RoleId == permission.RoleId); if (applicationPermission == null) { permission.Id = Guid.NewGuid().ToString(); db.Permissions.Add(permission); await db.SaveChangesAsync(); } else { ModelState.AddModelError("Duplicate", "This resource is already assigned with this role"); } return(Ok(permission.Id)); }
public async Task <IHttpActionResult> DeleteApplicationRole(string id) { ApplicationRole applicationRole = await db.ApplicationRoles.FindAsync(id); if (applicationRole == null) { return(NotFound()); } db.ApplicationRoles.Remove(applicationRole); await db.SaveChangesAsync(); return(Ok(applicationRole)); }
public async Task <IHttpActionResult> DeleteApplicationResource(string id) { db = Request.GetOwinContext().Get <SecurityDbContext>(); ApplicationResource applicationResource = await db.Resources.FindAsync(id); if (applicationResource == null) { return(NotFound()); } db.Resources.Remove(applicationResource); await db.SaveChangesAsync(); return(Ok(applicationResource)); }
public async Task <IHttpActionResult> PutApplicationUser(AppUserViewModel viewModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (viewModel.Id == null) { return(BadRequest()); } // IdentityResult result = await manager.UpdateAsync(applicationUser); db = Request.GetOwinContext().Get <SecurityDbContext>(); manager = Request.GetOwinContext().Get <ApplicationUserManager>(); ApplicationUser user = manager.FindByEmail(viewModel.Email); user.Id = viewModel.Id; user.Email = viewModel.Email; user.FirstName = viewModel.FirstName; user.LastName = viewModel.LastName; user.IsActive = true; user.EmailConfirmed = true; user.PhoneNumber = viewModel.PhoneNumber; user.ShopId = viewModel.ShopId; user.UserName = viewModel.Email; db.Entry(user).State = EntityState.Modified; try { IdentityUserRole entity = db.ApplicationUserRoles.FirstOrDefault(x => x.UserId == user.Id); db.ApplicationUserRoles.Remove(entity); db.SaveChanges(); var identityUserRole = db.ApplicationUserRoles.Add(new IdentityUserRole { RoleId = viewModel.RoleId, UserId = user.Id }); int i = await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ApplicationUserExists(user.Id)) { return(NotFound()); } throw; } return(Ok(user)); }
public async Task <IHttpActionResult> DeleteApplicationUser(string id) { db = Request.GetOwinContext().Get <SecurityDbContext>(); manager = Request.GetOwinContext().Get <ApplicationUserManager>(); ApplicationUser applicationUser = db.Users.Find(id); if (applicationUser == null) { return(NotFound()); } db.Users.Remove(applicationUser); await db.SaveChangesAsync(); return(Ok(applicationUser)); }
public async Task <Truck> UpdateAsync(Truck value) { SecurityDbContext dbContext = _securityDbContextFactory.CreateDbContext(); var exists = await dbContext.Trucks.AnyAsync(r => r.LicensePlate == value.LicensePlate); if (!exists) { throw new KeyNotFoundException($"Truck with license plate: {value.LicensePlate} not found."); } Truck existingTruck = await this.GetAsync(value.LicensePlate); existingTruck.Container = value.Container; existingTruck.SecurityStatus = value.SecurityStatus; await dbContext.SaveChangesAsync(); return(existingTruck); }
public async Task <IHttpActionResult> PostApplicationUser(AppUserViewModel viewModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db = Request.GetOwinContext().Get <SecurityDbContext>(); manager = Request.GetOwinContext().Get <ApplicationUserManager>(); ApplicationUser user = manager.FindByEmail(viewModel.Email); if (user != null) { return(Conflict()); } user = new ApplicationUser { Email = viewModel.Email, FirstName = viewModel.FirstName, LastName = viewModel.LastName, IsActive = true, EmailConfirmed = true, PhoneNumber = viewModel.PhoneNumber, ShopId = viewModel.ShopId, UserName = viewModel.Email }; IdentityResult result = await manager.CreateAsync(user, "MyPass@123"); if (result.Succeeded) { var identityUserRole = db.ApplicationUserRoles.Add(new IdentityUserRole { RoleId = viewModel.RoleId, UserId = user.Id }); await db.SaveChangesAsync(); } return(Ok(user.Id)); }
public async Task <IActionResult> Post([FromBody] RegistrationViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var userIdentity = _mapper.Map <AppUser> (model); var result = await _userManager.CreateAsync(userIdentity, model.Password); if (!result.Succeeded) { return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState))); } await _context.Customers.AddAsync(new Customer { user_id = userIdentity.Id, Location = model.Location }); await _context.SaveChangesAsync(); return(new OkObjectResult("Account created")); }
public Task <int> SaveChangesAsync() { return(_context.SaveChangesAsync()); }
public async Task <ActionResult> Post([FromBody] LoginViewModel loginViewModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ClaimsIdentity identity = await GetClaimsIdentity(loginViewModel.Username, loginViewModel.Password); if (identity == null) { return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState))); } Claim claim = identity.Claims.First(x => x.Type == Constants.Strings.JwtClaimIdentifiers.Id); var userId = claim.Value.ToString(); ApplicationUser user = securityDb.Users.First(x => x.Id == userId); if (user == null) { logger.LogError("Invalid login attempt for {UserName}", loginViewModel.Username); return(BadRequest("The user name or password is incorrect.")); } if (user.IsActive == false) { logger.LogError("Invalid login attempt for {UserName}", user.UserName); return(BadRequest("User is Deactivated")); } var userRoles = securityDb.ApplicationUserRoles.Where(x => x.UserId == user.Id).Select(x => x.RoleId).ToList(); var roles = securityDb.ApplicationRoles.Where(x => userRoles.Contains(x.Id)).Select(x => (dynamic) new { x.Id, x.Name }).ToList(); dynamic jwt = await Tokens.GenerateJwt( identity, jwtFactory, jwtOptions, user, roles, new JsonSerializerSettings { Formatting = Formatting.None }, securityDb); var jtiClaim = identity.Claims.First(x => x.Type == JwtRegisteredClaimNames.Jti); var token = new ApplicationUserToken() { UserId = user.Id, Name = user.UserName, LoginProvider = jtiClaim.Value, Value = true.ToString(), Jti = jtiClaim.Value }; await securityDb.UserTokens.AddAsync(token); await securityDb.SaveChangesAsync(); await redisService.Set($"{token.Name}", token, jwt, jwtOptions.ValidFor); return(Ok(jwt)); }
public async Task <ActionResult> Post([FromBody] LoginViewModel loginViewModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ClaimsIdentity identity = await GetClaimsIdentity(loginViewModel.Username, loginViewModel.Password); if (identity == null) { return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState))); } Claim claim = identity.Claims.First(x => x.Type == Constants.Strings.JwtClaimIdentifiers.Id); var userId = claim.Value.ToString(); ApplicationUser user = securityDb.Users.First(x => x.Id == userId); if (user == null) { logger.LogError("Invalid login attempt for {UserName}", loginViewModel.Username); return(BadRequest("The user name or password is incorrect.")); } if (user.IsActive == false) { logger.LogError("Invalid login attempt for {UserName}", user.UserName); return(BadRequest("User is deactivated")); } var userRoles = securityDb.ApplicationUserRoles.Where(x => x.UserId == user.Id).Select(x => x.RoleId).ToList(); var roles = securityDb.ApplicationRoles.Where(x => userRoles.Contains(x.Id)).Select(x => x.Id).ToList(); //List<ApplicationPermissionViewModel> resources = new List<ApplicationPermissionViewModel>(); List <dynamic> resources = new List <dynamic>(); if (roles != null && roles.Count > 0) { resources = securityDb.Permissions.Include(x => x.Resource).Include(x => x.Role).Where(x => roles.Contains(x.RoleId) && x.IsAllowed).Select(x => x.GetMinimalViewModel()) .ToList(); } dynamic jwt = await Tokens.GenerateJwt( identity, jwtFactory, jwtOptions, user, roles, resources); var jtiClaim = identity.Claims.First(x => x.Type == JwtRegisteredClaimNames.Jti); var token = new ApplicationUserToken() { UserId = user.Id, Name = user.UserName, LoginProvider = jtiClaim.Value, Value = true.ToString(), Jti = jtiClaim.Value }; await securityDb.UserTokens.AddAsync(token); await securityDb.SaveChangesAsync(); await redisService.Set(token.Name, jwtOptions.ValidFor, token.Jti, JsonConvert.SerializeObject(resources)); return(Ok(jwt)); }
public async Task <IActionResult> PutApplicationUser(string id, ApplicationUser applicationUser) { if (id != applicationUser.Id) { return(BadRequest()); } bool modelIsInvalid = await ValidateUpdateModel(applicationUser); if (modelIsInvalid) { return(BadRequest(ModelState)); } bool isValidRole = await ValidateRole(applicationUser.RoleId); if (!isValidRole) { return(BadRequest(ModelState)); } var user = await this.userManager.FindByIdAsync(id); user.UserName = applicationUser.UserName; user.Email = applicationUser.Email; user.FirstName = applicationUser.FirstName; user.LastName = applicationUser.LastName; user.PhoneNumber = applicationUser.PhoneNumber; user.IsActive = applicationUser.IsActive; var updateUserResult = await this.userManager.UpdateAsync(user); if (!updateUserResult.Succeeded) { IActionResult actionResult = GetErrorResult(updateUserResult); return(actionResult); } if (!string.IsNullOrEmpty(applicationUser.Password) && !string.IsNullOrEmpty(applicationUser.NewPassword)) { var passwordUpdateResult = await this.userManager.ChangePasswordAsync(user, applicationUser.Password, applicationUser.NewPassword); if (!passwordUpdateResult.Succeeded) { IActionResult actionResult = GetErrorResult(passwordUpdateResult); return(actionResult); } } try { var applicationUserRole = await _context.ApplicationUserRoles.FirstOrDefaultAsync(x => x.UserId == applicationUser.Id); if (applicationUserRole == null) { applicationUserRole = new ApplicationUserRole() { RoleId = applicationUser.RoleId, UserId = applicationUser.Id, }; await _context.ApplicationUserRoles.AddAsync(applicationUserRole); } else { applicationUserRole.RoleId = applicationUser.RoleId; } await _context.SaveChangesAsync(); } catch (Exception ex) { ModelState.AddModelError("roleId", ex.Message); return(BadRequest(ModelState)); } return(CreatedAtAction("GetApplicationUser", new { id = applicationUser.Id }, applicationUser)); }