public async Task <IActionResult> DeleteDevice([FromRoute] string deviceId) { var user = await UserManager.GetUserAsync(User); if (user == null) { return(NotFound()); } var device = DbContext.UserDevices.SingleOrDefault(x => x.UserId == user.Id && x.DeviceId == deviceId); if (device is null) { return(NotFound()); } try { await PushNotificationService.UnRegister(deviceId); } catch (Exception exception) { Logger.LogError("An exception occurred when connection to Azure Notification Hubs. Exception is '{Exception}'. Inner Exception is '{InnerException}'.", exception.Message, exception.InnerException?.Message ?? "N/A"); throw; } DbContext.UserDevices.Remove(device); await DbContext.SaveChangesAsync(); var @event = new DeviceDeletedEvent(DeviceInfo.FromUserDevice(device), SingleUserInfo.FromUser(user)); await EventService.Publish(@event); return(NoContent()); }
/// <inheritdoc /> public override async Task <IdentityResult> AccessFailedAsync(TUser user) { var result = await base.AccessFailedAsync(user); if (await IsLockedOutAsync(user)) { var @event = new AccountLockedEvent(SingleUserInfo.FromUser(user)); await _eventService.Publish(@event); } return(result); }
/// <inheritdoc /> public async Task CreateDevice(UserDevice device) { GuardDevice(device); _dbContext.UserDevices.Add(device); await _dbContext.SaveChangesAsync(); var user = device.User; if (user == null) { user = await _dbContext.Users.SingleOrDefaultAsync(x => x.Id == device.UserId); } var @event = new DeviceCreatedEvent(DeviceInfo.FromUserDevice(device), SingleUserInfo.FromUser(user)); await _eventService.Publish(@event); }
public async Task <IActionResult> CreateUser([FromBody] CreateUserRequest request) { var user = new User { Id = $"{Guid.NewGuid()}", UserName = request.UserName, Email = request.Email, CreateDate = DateTime.UtcNow, PhoneNumber = request.PhoneNumber, PasswordExpirationPolicy = request.PasswordExpirationPolicy }; IdentityResult result = null; if (string.IsNullOrEmpty(request.Password)) { result = await _userManager.CreateAsync(user); } else { result = await _userManager.CreateAsync(user, request.Password, validatePassword : !request.BypassPasswordValidation.GetValueOrDefault()); } if (!result.Succeeded) { return(BadRequest(result.Errors.ToValidationProblemDetails())); } if (request.ChangePasswordAfterFirstSignIn.HasValue && request.ChangePasswordAfterFirstSignIn.Value == true) { await _userManager.SetPasswordExpiredAsync(user, true); } var claims = request?.Claims?.Count() > 0 ? request.Claims.Select(x => new Claim(x.Type, x.Value)).ToList() : new List <Claim>(); if (!string.IsNullOrEmpty(request.FirstName)) { claims.Add(new Claim(JwtClaimTypes.GivenName, request.FirstName)); } if (!string.IsNullOrEmpty(request.LastName)) { claims.Add(new Claim(JwtClaimTypes.FamilyName, request.LastName)); } if (claims.Any()) { await _userManager.AddClaimsAsync(user, claims); } var response = SingleUserInfo.FromUser(user); await _eventService.Publish(new UserCreatedEvent(response)); return(CreatedAtAction(nameof(GetUser), Name, new { userId = user.Id }, response)); }
public async Task <IActionResult> CreateDevice([FromBody] RegisterDeviceRequest request) { var user = await UserManager.GetUserAsync(User); if (user == null) { return(NotFound()); } var device = await DbContext.UserDevices.SingleOrDefaultAsync(x => x.UserId == user.Id && x.DeviceId == request.DeviceId); if (device is not null) { ModelState.AddModelError(nameof(request.DeviceId), $"A device with id {request.DeviceId} already exists."); return(BadRequest(new ValidationProblemDetails(ModelState))); } var shouldEnablePushNotifications = !string.IsNullOrWhiteSpace(request.PnsHandle); if (shouldEnablePushNotifications) { try { await PushNotificationService.Register(request.DeviceId, request.PnsHandle, request.Platform, user.Id, request.Tags?.ToArray()); } catch (Exception exception) { Logger.LogError("An exception occurred when connection to Azure Notification Hubs. Exception is '{Exception}'. Inner Exception is '{InnerException}'.", exception.Message, exception.InnerException?.Message ?? "N/A"); throw; } } device = new UserDevice { DeviceId = request.DeviceId, Name = request.Name, Platform = request.Platform, IsPushNotificationsEnabled = shouldEnablePushNotifications, UserId = user.Id, DateCreated = DateTimeOffset.UtcNow, Model = request.Model, OsVersion = request.OsVersion, Data = request.Data }; DbContext.UserDevices.Add(device); await DbContext.SaveChangesAsync(); var response = DeviceInfo.FromUserDevice(device); var @event = new DeviceCreatedEvent(response, SingleUserInfo.FromUser(user)); await EventService.Publish(@event); return(CreatedAtAction(nameof(GetDeviceById), new { deviceId = device.DeviceId }, response)); }
public async Task <IActionResult> Register([FromBody] ApiRegisterRequest request) { var user = CreateUserFromRequest(request); var requestClaimTypes = request.Claims.Select(x => x.Type); var claimTypes = await _configurationDbContext.ClaimTypes.Where(x => requestClaimTypes.Contains(x.Name)).ToListAsync(); var unknownClaimTypes = requestClaimTypes.Except(claimTypes.Select(x => x.Name)); if (unknownClaimTypes.Any()) { ModelState.AddModelError(string.Empty, $"The following claim types are not supported: '{string.Join(", ", unknownClaimTypes)}'."); return(BadRequest(new ValidationProblemDetails(ModelState))); } var canAddClaims = claimTypes.All(x => x.UserEditable) || User.IsSystemClient(); if (!canAddClaims) { ModelState.AddModelError(nameof(claimTypes), $"The following claims are not editable: '{string.Join(", ", claimTypes.Where(x => !x.UserEditable).Select(x => x.Name))}'."); return(BadRequest(new ValidationProblemDetails(ModelState))); } foreach (var claim in request.Claims) { user.Claims.Add(new IdentityUserClaim <string> { ClaimType = claim.Type, ClaimValue = claim.Value ?? string.Empty, UserId = user.Id }); } var result = await _userManager.CreateAsync(user, request.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.AddModelError(error.Code, error.Description); } return(BadRequest(new ValidationProblemDetails(ModelState))); } var createdUser = SingleUserInfo.FromUser(user); var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); await _eventService.Publish(new UserRegisteredEvent(createdUser, token)); return(NoContent()); }
public async Task <IActionResult> UpdateUserName([FromBody] UpdateUserNameRequest request) { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound()); } var result = await _userManager.SetUserNameAsync(user, request.UserName); if (!result.Succeeded) { return(BadRequest(result.Errors.ToValidationProblemDetails())); } var @event = new UserNameChangedEvent(SingleUserInfo.FromUser(user)); await _eventService.Publish(@event); return(Ok()); }
public async Task <IActionResult> UpdateDevice([FromRoute] string deviceId, [FromBody] UpdateDeviceRequest request) { var user = await UserManager.GetUserAsync(User); if (user == null) { return(NotFound()); } var device = await DbContext.UserDevices.SingleOrDefaultAsync(x => x.UserId == user.Id && x.DeviceId == deviceId); if (device is null) { return(NotFound()); } var shouldEnablePushNotifications = !string.IsNullOrWhiteSpace(request.PnsHandle); var shouldUnRegisterDevice = device.IsPushNotificationsEnabled && !shouldEnablePushNotifications; var shouldRegisterDevice = !device.IsPushNotificationsEnabled && shouldEnablePushNotifications; try { if (shouldUnRegisterDevice) { await PushNotificationService.UnRegister(deviceId); } if (shouldRegisterDevice) { await PushNotificationService.Register(device.DeviceId, request.PnsHandle, device.Platform, user.Id, request.Tags?.ToArray()); } } catch (Exception exception) { Logger.LogError("An exception occurred when connection to Azure Notification Hubs. Exception is '{Exception}'. Inner Exception is '{InnerException}'.", exception.Message, exception.InnerException?.Message ?? "N/A"); throw; } device.IsPushNotificationsEnabled = shouldEnablePushNotifications; device.Name = request.Name; device.Model = request.Model; device.OsVersion = request.OsVersion; device.Data = request.Data; await DbContext.SaveChangesAsync(); var @event = new DeviceUpdatedEvent(DeviceInfo.FromUserDevice(device), SingleUserInfo.FromUser(user)); await EventService.Publish(@event); return(NoContent()); }
public async Task <IActionResult> UpdatePassword([FromBody] ChangePasswordRequest request) { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound()); } var result = await _userManager.ChangePasswordAsync(user, request.OldPassword, request.NewPassword); if (!result.Succeeded) { return(BadRequest(result.Errors.ToValidationProblemDetails())); } var @event = new PasswordChangedEvent(SingleUserInfo.FromUser(user)); await _eventService.Publish(@event); return(NoContent()); }
public async Task <IActionResult> ForgotPasswordConfirmation([FromBody] ForgotPasswordVerifyModel request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _userManager.FindByEmailAsync(request.Email); if (user == null) { return(NoContent()); } var result = await _userManager.ResetPasswordAsync(user, request.Token, request.NewPassword); if (!result.Succeeded) { return(BadRequest(result.Errors.ToValidationProblemDetails())); } var @event = new PasswordChangedEvent(SingleUserInfo.FromUser(user)); await _eventService.Publish(@event); return(NoContent()); }
public async Task <IActionResult> SetPassword([FromRoute] string userId, [FromBody] SetPasswordRequest request) { var user = await _dbContext.Users.SingleOrDefaultAsync(x => x.Id == userId); if (user == null) { return(NotFound()); } var result = await _userManager.ResetPasswordAsync(user, request.Password, validatePassword : !request.BypassPasswordValidation.GetValueOrDefault()); if (!result.Succeeded) { return(BadRequest(result.Errors.ToValidationProblemDetails())); } var @event = new PasswordChangedEvent(SingleUserInfo.FromUser(user)); await _eventService.Publish(@event); if (request.ChangePasswordAfterFirstSignIn == true) { await _userManager.SetPasswordExpiredAsync(user, true); } return(NoContent()); }
/// <summary> /// Creates a new instance of <see cref="DeviceCreatedEvent"/>. /// </summary> /// <param name="device">The device created.</param> /// <param name="user">Related user.</param> public DeviceCreatedEvent(DeviceInfo device, SingleUserInfo user) { Device = device; User = user; }
/// <summary> /// Creates a new instance of <see cref="AccountLockedEvent"/>. /// </summary> /// <param name="user">Related user.</param> public AccountLockedEvent(SingleUserInfo user) { User = user; }
/// <summary> /// Creates a new instance of <see cref="UserCreatedEvent"/>. /// </summary> /// <param name="user"></param> public UserCreatedEvent(SingleUserInfo user) => User = user;
/// <summary> /// Creates a new instance of <see cref="PasswordChangedEvent"/>. /// </summary> /// <param name="user">Related user.</param> public PasswordChangedEvent(SingleUserInfo user) { User = user; }
/// <summary> /// Creates a new instance of <see cref="UserNameChangedEvent"/>. /// </summary> /// <param name="user">Related user.</param> public UserNameChangedEvent(SingleUserInfo user) { User = user; }
/// <summary> /// Creates a new instance of <see cref="UserRegisteredEvent"/>. /// </summary> /// <param name="user">The instance of the user that was registered.</param> /// <param name="confirmationToken">The generated email confirmation token.</param> public UserRegisteredEvent(SingleUserInfo user, string confirmationToken) { User = user ?? throw new ArgumentNullException(nameof(user)); ConfirmationToken = confirmationToken ?? throw new ArgumentNullException(nameof(confirmationToken)); }