public async Task <Guid> HandleAsync(CreateMenu command)
        {
            var id = Guid.NewGuid();

            // TODO: Check if the user owns the resource before any operation
            // if(command.User.TenantId != menu.TenantId)
            // {
            //     throw NotAuthorizedException()
            // }


            var newMenu = new Menu(
                id: id,
                name: command.Name,
                tenantId: command.TenantId,
                description: command.Description,
                categories: null,
                enabled: command.Enabled
                );

            await repository.SaveAsync(newMenu);

            await applicationEventPublisher.PublishAsync(new MenuCreated(command, id));

            return(id);
        }
Exemplo n.º 2
0
        public async Task <bool> HandleAsync(DeleteMenu command)
        {
            var menu = await repository.GetByIdAsync(command.MenuId);

            if (menu == null)
            {
                MenuDoesNotExistException.Raise(command, command.MenuId);
            }

            // TODO: Check if the user owns the resource before any operation
            // if(command.User.TenantId != menu.TenantId)
            // {
            //     throw NotAuthorizedException()
            // }

            var successful = await repository.DeleteAsync(command.MenuId);

            if (!successful)
            {
                OperationFailedException.Raise(command, command.MenuId, "Unable to delete menu");
            }

            await applicationEventPublisher.PublishAsync(
                new MenuDeleted(command, command.MenuId)
                );

            return(successful);
        }
        public async Task <ForgotPasswordCommandResult> Handle(ForgotPasswordCommand request,
                                                               CancellationToken cancellationToken)
        {
            var user = await _userManager.FindByEmailAsync(request.Email);

            if (user == null)
            {
                return new ForgotPasswordCommandResult
                       {
                           IsSuccess = false,
                           Message   = $"User {request.Email} not found."
                       }
            }
            ;

            var token = await _userManager.GeneratePasswordResetTokenAsync(user);

            var encodedToken = Base64UrlEncoder.Encode(token);

            _urlBuilder
            .Create(_interactionOptions.UserInteractionEndpoints.BaseUrl)
            .Path(_interactionOptions.UserInteractionEndpoints.ResetPassword)
            .AddQuery("userId", user.Id)
            .AddQuery("token", encodedToken)
            .AddQuery("returnUrl", request.ReturnUrl);


            var forgotPasswordRequestedEvent = new ForgotPasswordRequestedEvent
            {
                UserId = user.Id,
                Url    = _urlBuilder.ToString()
            };

            await _eventPublisher.PublishAsync(forgotPasswordRequestedEvent);

            return(new ForgotPasswordCommandResult
            {
                Token = token,
                IsSuccess = true
            });
        }
    }
Exemplo n.º 4
0
        public async Task <RegisterUserCommandResult> Handle(RegisterUserCommand request,
                                                             CancellationToken cancellationToken)
        {
            if (!string.IsNullOrWhiteSpace(request.Token))
            {
                var validationResult = await _tokenValidator.ValidateAccessTokenAsync(request.Token);

                if (validationResult.IsError)
                {
                    throw new DomainException(validationResult.Error);
                }

                if (!validationResult.Client?.RedirectUris.Any(url =>
                                                               url.Equals(request.ReturnUrl, StringComparison.OrdinalIgnoreCase)) ?? true)
                {
                    throw new DomainException($"Invalid return url: {request.ReturnUrl}");
                }
            }
            else if (!string.IsNullOrWhiteSpace(request.ReturnUrl))
            {
                var context = await _interactionService.GetAuthorizationContextAsync(request.ReturnUrl);

                if (context == null)
                {
                    throw new DomainException("Invalid context");
                }
            }

            var user = await _userService.GetByUsername(request.Email, cancellationToken);

            if (user != null)
            {
                return new RegisterUserCommandResult
                       {
                           IsSuccess = false,
                           Errors    = new List <string>
                           {
                               $"Email {request.Email} already exists."
                           }
                       }
            }
            ;

            user = new ApplicationUser
            {
                Id             = Guid.NewGuid().ToString(),
                Email          = request.Email,
                UserName       = request.Email,
                EmailConfirmed = !_options.RequireConfirmedEmail
            };

            var password = !string.IsNullOrWhiteSpace(request.PlainTextPassword)
                ? request.PlainTextPassword
                : Guid.NewGuid().ToString().ToSha256();

            var result = await _userManager.CreateAsync(user, password);

            var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var encodedToken = Base64UrlEncoder.Encode(token);

            var response = new RegisterUserCommandResult
            {
                Id        = result.Succeeded ? user.Id : string.Empty,
                IsSuccess = result.Succeeded,
                Errors    = result.Errors.Select(e => e.Description)
            };

            if (!result.Succeeded)
            {
                return(response);
            }

            _urlBuilder
            .Create(_interactionOptions.UserInteractionEndpoints.BaseUrl)
            .Path(_interactionOptions.UserInteractionEndpoints.ConfirmUser)
            .AddQuery("userId", user.Id)
            .AddQuery("token", encodedToken)
            .AddQuery("returnUrl", request.ReturnUrl);

            var userRegisteredEvent = new UserRegisteredEvent
            {
                UserId = user.Id,
                Url    = _urlBuilder.ToString()
            };

            await _eventPublisher.PublishAsync(userRegisteredEvent);

            return(response);
        }
    }
        public async Task <TResult> HandleAsync(TCommand command)
        {
            TResult result = default(TResult);

            var menu = await repository.GetByIdAsync(command.MenuId);

            if (menu == null)
            {
                MenuDoesNotExistException.Raise(command, command.MenuId);
            }

            // TODO: Check if the user owns the resource before any operation
            // if(command.User.TenantId != menu.TenantId)
            // {
            //     throw NotAuthorizedException()
            // }

            try
            {
                result = await HandleCommandAsync(menu, command);

                var issuccessful = await repository.SaveAsync(menu);

                if (!issuccessful)
                {
                    OperationFailedException.Raise(command, command.MenuId,
                                                   $"Unable to handle command {typeof(ICommand).Name}");
                }

                foreach (var appEvent in RaiseApplicationEvents(menu, command))
                {
                    await applicationEventPublisher.PublishAsync(appEvent);
                }
            }
            catch (DomainExceptionBase ex)
            {
                DomainRuleViolationException.Raise(command, command.MenuId, ex);
            }
            catch (ApplicationExceptionBase)
            {
                // TODO: handle applicaiton exception handling
                // possible failures is missing data or information, validations, and so on
                throw;
            }
            catch (InfrastructureExceptionBase)
            {
                //TODO: handle  infrastructure exception handling
                //possible failures is calling database, queue or any other dependency
                throw;
            }
            catch (Exception ex)
            {
                //TODO: Enrich the exception details with context information to track in the logs
                ex.Data["OperationCode"] = command.OperationCode;
                ex.Data["CorrelationId"] = command.CorrelationId;
                ex.Data["MenuId"]        = command.MenuId;

                throw;
            }

            return(result);
        }