public void Register(RegisterTicketCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            TicketCategory     category = _categoryRepository.GetById(command.CategoryId);
            LedgerIdentityUser user     = _identityResolver.GetUser();

            if (NotifyNullCategory(category))
            {
                return;
            }

            Ticket ticket = _factory.OpenTicket(command.Title, command.Details, command.CategoryId, user.Id);

            _ticketRepository.Register(ticket);

            if (Commit())
            {
                PublishLocal(new TicketRegisteredEvent(ticket.Id, ticket.Title, ticket.Details));
            }
        }
Exemple #2
0
        public void ShouldFailToAddMessageFromSupport()
        {
            LedgerIdentityUser user = new LedgerIdentityUser(Guid.NewGuid());

            ticket.AddMessage("Olá, mundo!", user.Id);
            Assert.AreEqual("Não possui acesso às mensagens", ticket.GetNotifications().First().Title);
        }
        public async Task RemoveFromRole(RemoveUserFromRoleCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            LedgerIdentityUser user = await GetByEmail(command.Email);

            if (NotifyNullUser(user))
            {
                return;
            }

            if (await NotifyNullRole(command.RoleName))
            {
                return;
            }

            IdentityResult result = await _userManager.RemoveFromRoleAsync(user, command.RoleName);

            if (!result.Succeeded)
            {
                AddNotifications(result);
            }
            else
            {
                await Publish(new UserRemovedFromRoleIntegrationEvent(user.Id, command.RoleName));
            }
        }
        //Accessible only through a user with Support role on controller
        public void AssignSupport(AssignSupportCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            Ticket             ticket = _ticketRepository.GetById(command.TicketId);
            LedgerIdentityUser user   = _identityResolver.GetUser();

            if (NotifyNullTicket(ticket))
            {
                return;
            }

            ticket.AssignSupportUser(user.Id);

            if (AddNotifications(ticket))
            {
                return;
            }

            _ticketRepository.Update(ticket);

            if (Commit())
            {
                PublishLocal(new AssignedTicketSupportEvent(ticket.Id, user.Id));
            }
        }
        public void AddMessage(AddMessageCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            Ticket             ticket = _ticketRepository.GetById(command.TicketId);
            LedgerIdentityUser user   = _identityResolver.GetUser();

            if (NotifyNullTicket(ticket))
            {
                return;
            }

            //User authenticity threated inside AddMessage() method
            ticket.AddMessage(command.Body, user.Id);

            if (AddNotifications(ticket))
            {
                return;
            }

            _ticketRepository.Update(ticket);

            if (Commit())
            {
                PublishLocal(new AddedTicketMessageEvent(command.Body, ticket.Id, user.Id));
            }
        }
        public void RemoveComment(RemoveArticleCommentCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            Article            article = _articleRepository.GetById(command.ArticleId);
            LedgerIdentityUser user    = _identityResolver.GetUser();

            if (NotifyNullArticle(article))
            {
                return;
            }

            Comment comment = article.Comments.FirstOrDefault(c => c.Id == command.CommentId);

            if (comment == null || comment.AuthorId != user.Id)
            {
                AddNotification("Erro na remoção", "Não foi possível remover esse comentário.");
                return;
            }

            _articleRepository.Update(article);

            Commit();
        }
        public async Task <LedgerIdentityUser> Register(RegisterUserCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return(null);
            }

            LedgerIdentityUser user = new LedgerIdentityUser(command.Email);

            IdentityResult result = await _userManager.CreateAsync(user, command.Password);

            if (result.Succeeded)
            {
                string confirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                await PublishLocal(new UserRegisteredEvent(user.Email, confirmationToken));
                await Publish(new UserRegisteredIntegrationEvent(user.Id, user.Email));

                return(user);
            }

            AddNotifications(result);
            return(null);
        }
        public async Task ResetPassword(ResetUserPasswordCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            LedgerIdentityUser user = await GetByEmail(command.Email);

            if (NotifyNullUser(user))
            {
                return;
            }

            IdentityResult result = await _userManager.ResetPasswordAsync(user, command.ResetToken, command.NewPassword);

            if (!result.Succeeded)
            {
                AddNotifications(result);
            }
            else
            {
                await PublishLocal(new UserResetedPasswordEvent(user.Email));
            }
        }
Exemple #9
0
        public TicketTests()
        {
            Guid userId = Guid.NewGuid();

            category = new TicketCategory("Problemas de ativação");
            user     = new LedgerIdentityUser(userId);
            ticket   = new Ticket("Não consigo anexar documentos", "Meus documentos falham ao serem anexados para enviar e ativar a conta", category.Id, user.Id);
        }
Exemple #10
0
        public void TicketShouldAttachASupportUserToHelp()
        {
            //Come from repository
            LedgerIdentityUser user = new LedgerIdentityUser(Guid.NewGuid());

            ticket.AssignSupportUser(user.Id);

            Assert.AreEqual(user.Id, ticket.SupportUserId);
            Assert.IsTrue(ticket.AlreadyHaveSupport());
        }
        private bool NotifyNullUser(LedgerIdentityUser user)
        {
            if (user == null)
            {
                AddNotification("Erro ao encontrar usuário", "Não existe nenhum usuário registrado com esse e-mail.");
                return(true);
            }

            return(false);
        }
Exemple #12
0
        public async Task<IActionResult> GetUserById(Guid id)
        {
            LedgerIdentityUser user = await _userApplicationService.GetById(id);

            return CreateResponse(new
            {
                id = user.Id,
                email = user.Email,
                userName = user.UserName,
            });
        }
        public IQueryable <Ticket> GetByUserId(Guid userId)
        {
            LedgerIdentityUser user = _identityResolver.GetUser();

            if (userId != user.Id)
            {
                AddNotification("Erro ao buscar", "O usuário atual não possui permissão para visualizar os dados.");
                return(Enumerable.Empty <Ticket>().AsQueryable());
            }

            return(_ticketRepository.GetByUserId(userId));
        }
Exemple #14
0
        public void TicketShouldFailToAttachASupportUserToHelp()
        {
            //Come from repository
            LedgerIdentityUser user = new LedgerIdentityUser(Guid.NewGuid());

            ticket.AssignSupportUser(user.Id);

            ticket.AssignSupportUser(user.Id);


            Assert.AreEqual("Suporte já definido", ticket.GetNotifications().First().Title);
        }
        private bool NotifyCantAccessTicket(Ticket ticket)
        {
            LedgerIdentityUser user        = _identityResolver.GetUser();
            LedgerIdentityRole supportRole = new LedgerIdentityRole(RoleTypes.Support);

            bool canAccessTicket = ticket.TicketUserId == user.Id || user.IsInRole(supportRole);

            if (!canAccessTicket)
            {
                AddNotification("Usuário inválido", "O usuário não tem autorização para acessar os dados.");
                return(true);
            }

            return(false);
        }
Exemple #16
0
        public async Task <IActionResult> Register([FromBody] RegisterUserCommand command)
        {
            LedgerIdentityUser user = await _userApplicationService.Register(command);

            if (user != null)
            {
                return(CreateResponse(new
                {
                    id = user.Id,
                    email = user.Email
                }));
            }

            return(CreateResponse());
        }
Exemple #17
0
        public void ShouldGetMessagesFromUser()
        {
            LedgerIdentityUser supportUser = new LedgerIdentityUser(Guid.NewGuid());

            ticket.AssignSupportUser(supportUser.Id);

            ticket.AddMessage("Olá, como eu posso te ajudar?", supportUser.Id);
            ticket.AddMessage("Estou com um problema para ativar minha conta.", user.Id);
            ticket.AddMessage("Qual problema você está tendo?", supportUser.Id);
            ticket.AddMessage("Não consigo anexar meus documentos para efetuar a ativação.", user.Id);
            ticket.AddMessage("Um momento enquanto eu faço alguns testes.", supportUser.Id);
            ticket.AddMessage("Pronto. Tente agora.", supportUser.Id);
            ticket.AddMessage("Consegui!", user.Id);

            Assert.AreEqual(3, ticket.GetMessages(user.Id).Count);
        }
        public async Task Handle(UserLoggedInEvent @event)
        {
            LedgerIdentityUser user = await _userManager.FindByIdAsync(@event.UserId.ToString());

            bool confirmedEmail = await _userManager.IsEmailConfirmedAsync(user);

            string confirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            if (!confirmedEmail)
            {
                EmailTemplate template = new EmailTemplate(@event.Email)
                                         .SetTemplate(EmailTemplateTypes.UserLoggedIn)
                                         .AddSubstitution("-code-", confirmationToken);

                await _emailDispatcher.SendEmailAsync(template);
            }
        }
Exemple #19
0
        public void FactoryShouldReturnTicket()
        {
            Guid catId  = Guid.NewGuid();
            Guid userId = Guid.NewGuid();

            TicketFactory factory = new TicketFactory();

            //Come from repository
            TicketCategory category = new TicketCategory(catId, "Problemas de ativação");

            //Come from repository
            LedgerIdentityUser user = new LedgerIdentityUser(userId);

            Ticket ticket = factory.OpenTicket("Não consigo ativar minha conta", "Falha ao ativar minha conta", category.Id, user.Id);

            Assert.IsNotNull(ticket);
            Assert.AreEqual(userId, user.Id);
            Assert.AreEqual(catId, category.Id);
        }
        public async Task ForgotPassword(ForgotUserPasswordCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            LedgerIdentityUser user = await GetByEmail(command.Email);

            if (NotifyNullUser(user))
            {
                return;
            }

            string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

            await PublishLocal(new UserForgotPasswordEvent(user.Email, resetToken));
        }
        public async Task <ClaimsIdentity> Login(LoginUserCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return(null);
            }

            LedgerIdentityUser user = await GetByEmail(command.Email);

            if (NotifyNullUser(user))
            {
                return(null);
            }

            SignInResult result = await _signInManager.CheckPasswordSignInAsync(user, command.Password, true);

            if (result.Succeeded)
            {
                IEnumerable <Claim> claims = await _userManager.GetClaimsAsync(user);

                IEnumerable <string> roles = await _userManager.GetRolesAsync(user);

                List <Claim> userPermissions = new List <Claim>();
                userPermissions.AddRange(claims);
                userPermissions.AddRange(roles.Select(value => new Claim(ClaimTypes.Role, value)));

                GenericIdentity identity       = new GenericIdentity(user.Id.ToString());
                ClaimsIdentity  claimsIdentity = new ClaimsIdentity(identity, userPermissions);

                await PublishLocal(new UserLoggedInEvent(user.Id, user.Email));

                return(claimsIdentity);
            }

            AddNotification("Usuário inválido", "O usuário e/ou senha estão incorretos.");
            return(null);
        }
        public void Register(RegisterArticleCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            ArticleCategory    category = _categoryRepository.GetById(command.CategoryId);
            LedgerIdentityUser user     = _identityResolver.GetUser();

            if (NotifyNullCategory(category))
            {
                return;
            }

            Article article = new Article(command.Slug, command.Title, command.Body, command.CategoryId, user.Id);

            _articleRepository.Register(article);

            Commit();
        }
        public async Task ConfirmEmail(ConfirmUserEmailCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            LedgerIdentityUser user = await GetByEmail(command.Email);

            if (NotifyNullUser(user))
            {
                return;
            }

            IdentityResult result = await _userManager.ConfirmEmailAsync(user, command.ConfirmationToken);

            if (!result.Succeeded)
            {
                AddNotifications(result);
            }
            else
            {
                Claim          activatedAccountClaim = new Claim("activated-account", "true");
                IdentityResult claimResult           = await _userManager.AddClaimAsync(user, activatedAccountClaim);

                if (!claimResult.Succeeded)
                {
                    AddNotifications(claimResult);
                }
                else
                {
                    await PublishLocal(new UserEmailConfirmedEvent(user.Email));
                }
            }
        }
        public void AttachIssuePicture(AttachIssuePictureCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            Image issuePicture = new Image(command.IssuePicture.ToBytes());

            Ticket             ticket = _ticketRepository.GetById(command.TicketId);
            LedgerIdentityUser user   = _identityResolver.GetUser();

            if (NotifyNullTicket(ticket))
            {
                return;
            }

            if (ticket.TicketUserId != user.Id)
            {
                AddNotification("Erro ao anexar", "O usuário não tem permissão para anexar arquivos ao ticket.");
                return;
            }

            ticket.AttachIssuePicture(issuePicture);

            if (AddNotifications(ticket))
            {
                return;
            }

            _ticketRepository.Update(ticket);

            Commit();
        }
        public void AddComment(AddArticleCommentCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            Article            article = _articleRepository.GetById(command.ArticleId);
            LedgerIdentityUser user    = _identityResolver.GetUser();

            if (NotifyNullArticle(article))
            {
                return;
            }

            Comment comment = new Comment(article.Id, user.Id, command.Body);

            article.AddComment(comment);
            _articleRepository.Update(article);

            Commit();
        }
        public async Task <LedgerIdentityUser> GetByEmail(string email)
        {
            LedgerIdentityUser user = await _userManager.FindByEmailAsync(email);

            return(user);
        }
        public async Task <LedgerIdentityUser> GetById(Guid id)
        {
            LedgerIdentityUser user = await _userManager.FindByIdAsync(id.ToString());

            return(user);
        }