示例#1
0
        public async Task <ForgotPasswordResponse> ForgotPasswordAsync(string emailUser)
        {
            ForgotPasswordResponse response = new ForgotPasswordResponse();

            // E-mail validation
            Email            email          = new Email(emailUser);
            EmailValidator   emailValidator = new EmailValidator();
            ValidationResult emailResult    = await emailValidator.ValidateAsync(email);

            if (!emailResult.IsValid)
            {
                response.AddErrorValidationResult(emailResult);
                return(response);
            }

            // Verify is e-mail not exist
            bool emailExist = await _unitOfWork.UserRepository.IsEmailExistsAsync(emailUser);

            if (emailExist == false)
            {
                response.SetError(new ErrorResponse("Email", Msg.EmailDoesnotExist));
                return(response);
            }

            // Persistence
            UserSecurity security = await _unitOfWork.UserSecurityRepository.GetByEmailAsync(email.EmailAddress);

            security.GenerateTokenForgotPassword();
            _unitOfWork.UserSecurityRepository.Update(security);

            // Send mail
            //emailService.SendEmailForgotPassword(email.EmailAddress, security.TokenForgotPassword.Value);

            return(response);
        }
示例#2
0
        public async Task <CreateAccountResponse> CreateAccountAsync(CreateAccountRequest request)
        {
            CreateAccountResponse response = new CreateAccountResponse();

            // E-mail validation
            Email            email          = new Email(request.Email);
            EmailValidator   emailValidator = new EmailValidator();
            ValidationResult emailResult    = await emailValidator.ValidateAsync(email);

            if (!emailResult.IsValid)
            {
                response.AddErrorValidationResult(emailResult);
                return(response);
            }

            bool emailExiste = await _unitOfWork.UserRepository.IsEmailExistsAsync(request.Email);

            if (emailExiste)
            {
                response.SetError(new ErrorResponse("Email", Msg.EmailExists));
                return(response);
            }

            // User validation
            User             user          = new User(request.Name, email, request.Password);
            UserValidator    userValidator = new UserValidator();
            ValidationResult userResult    = await userValidator.ValidateAsync(user);

            if (!userResult.IsValid)
            {
                response.AddErrorValidationResult(userResult);
                return(response);
            }

            // Crypt
            user.CryptPassword(user.Password);

            // Persistence
            await _unitOfWork.UserRepository.CreateAsync(user);

            await _unitOfWork.SaveAsync();

            // Send mail
            //emailService.SendEmailNewUser(user.Email.EmailAddress, user.UserSecurity.TokenCreateConfirmed, user.FisrtName);

            response.IdUser = user.UserId;
            return(response);
        }
        private async Task <IdentityUser> GetUserByEmailOrUserName(string usernameOrEmail)
        {
            //check if login by email or by empSn
            var emailValidator = new EmailValidator();

            if (!(await emailValidator.ValidateAsync(usernameOrEmail.Trim())).IsValid)
            {
                return(await _userManager.FindByNameAsync(usernameOrEmail));
            }
            //login by email - get employee's Sn
            var email = usernameOrEmail.Trim().ToLower();
            var empSn = (await _dalService.CreateUnitOfWork().Employees
                         .SingleOrDefaultAsync(x => x.IsActive && x.Email.ToLower() == email))?.Sn;

            var user = await _userManager.Users.SingleOrDefaultAsync(x => x.EmpId == empSn);

            //check whether the user exists
            return(user);
        }
示例#4
0
        public async Task <IActionResult> OnPostAsync()
        {
            var result = await _validator.ValidateAsync(Email);

            if (result.IsValid)
            {
                await _smtpClient.SendEmail(Email.EmailAddress, Email.Subject, Email.Message);

                ViewData["FormMessage"] = "Message sent comrade!";
                ViewData["FormSuccess"] = result.IsValid;
            }
            else
            {
                ViewData["FormMessage"] = result.Errors.First().ErrorMessage;
                ViewData["FormSuccess"] = result.IsValid;
            }

            return(Page());
        }
示例#5
0
        public async Task <IActionResult> Register([FromBody] RegisterDto registerDto, [FromServices] IRegisterAccountService service)
        {
            var registerValidator = new EmailValidator();
            var validatorResult   = await registerValidator.ValidateAsync(registerDto);

            if (validatorResult.IsValid)
            {
                await service.RegisterAccount(registerDto);

                if (!service.Status.HasErrors)
                {
                    return(Ok());
                }
                return(BadRequest(service.Status.Errors));
            }

            var validationErrors = validatorResult.Errors.Select(error => new ValidationResult(error.ErrorMessage))
                                   .ToImmutableList();

            return(BadRequest(validationErrors));
        }
示例#6
0
        public async Task <ContactResponse> SendContactMessageAsync(ContactRequest request)
        {
            ContactResponse response = new ContactResponse();

            // E-mail validation
            Email            email          = new Email(request.Email);
            EmailValidator   emailValidator = new EmailValidator();
            ValidationResult emailResult    = await emailValidator.ValidateAsync(email);

            if (!emailResult.IsValid)
            {
                response.AddErrorValidationResult(emailResult);
            }

            if (string.IsNullOrEmpty(request.Name))
            {
                response.SetError(new ErrorResponse("Name", string.Format(Msg.RequiredFieldX, "Nome")));
            }

            if (string.IsNullOrEmpty(request.Subject))
            {
                response.SetError(new ErrorResponse("Subject", string.Format(Msg.RequiredFieldX, "Assunto")));
            }

            if (string.IsNullOrEmpty(request.Message))
            {
                response.SetError(new ErrorResponse("Message", string.Format(Msg.RequiredFieldX, "Mensagem")));
            }

            if (!response.IsValid())
            {
                return(response);
            }

            // Sending Email
            await _emailService.SendContactEmailAsync(request.Name, request.Email.Trim().ToLower(), request.Subject, request.Message);

            return(response);
        }
示例#7
0
        public async Task <LoginResponse> LoginAsync(LoginRequest request)
        {
            LoginResponse response = new LoginResponse();

            // E-mail validation
            Email            email          = new Email(request.Email);
            EmailValidator   emailValidator = new EmailValidator();
            ValidationResult emailResult    = await emailValidator.ValidateAsync(email);

            if (!emailResult.IsValid)
            {
                response.AddErrorValidationResult(emailResult);
                return(response);
            }

            // Verify if user exists
            User user = await _unitOfWork.UserRepository.AuthUserAsync(email.EmailAddress, request.Password.CryptPassword());

            if (user == null)
            {
                response.SetError(new ErrorResponse(string.Empty, Msg.InvalidAuth));
                return(response);
            }

            // Verify if user is active
            bool userActive = await _unitOfWork.UserRepository.VerifyUserIsActiveByEmailAsync(request.Email);

            if (userActive == false)
            {
                response.SetError(new ErrorResponse(string.Empty, Msg.AccountInactive));
                return(response);
            }

            response.IdUser    = user.UserId;
            response.FirstName = user.Name;

            return(response);
        }
        public async Task CreateUserAsync(string creatorUserName,
                                          UserRegistrationRequest userRegistrationRequest)
        {
            //check creator permissions
            var creator = await _userManager.FindByNameAsync(creatorUserName);

            if (creator == null)
            {
                throw new IllegalArgumentException(CreatorDontExistMsg);
            }


            //only manager or admin can create new user
            if (creator.Role != IdentityUser.UserRole.Admin && creator.Role != IdentityUser.UserRole.Manager)
            {
                throw new InvalidCredentialException(CreatorDontHavePermission);
            }

            //only admin can create new admin
            if (creator.Role != IdentityUser.UserRole.Admin &&
                userRegistrationRequest.Role == IdentityUser.UserRole.Admin)
            {
                throw new InvalidCredentialException(CreatorDontHavePermissionAdminCanCreateAdmin);
            }

            //check if the user already exist
            if (await _userManager.FindByNameAsync(userRegistrationRequest.Username) != null)
            {
                throw new IllegalArgumentException(UserAlreadyExist);
            }


            //check if register by email or by empSn
            var emailValidator = new EmailValidator();

            if ((await emailValidator.ValidateAsync(userRegistrationRequest.Username.Trim())).IsValid)
            {
                var email = userRegistrationRequest.Username.Trim();
                //register by email - get employee's Sn
                userRegistrationRequest.Username = (await _dalService.CreateUnitOfWork().Employees
                                                    .SingleOrDefaultAsync(x => x.IsActive && x.Email == email)).Sn.ToString();
            }

            //check if the user have matching employee
            var emp = await _dalService.CreateUnitOfWork()
                      .Employees.SingleOrDefaultAsync(x => x.Sn.ToString() == userRegistrationRequest.Username);

            if (emp == null)
            {
                throw new IllegalArgumentException(EmployeeNotExist);
            }


            var newUser = new IdentityUser
            {
                Role     = userRegistrationRequest.Role,
                UserName = userRegistrationRequest.Username,
                EmpId    = emp.Sn
            };

            var createdUserResult = await _userManager.CreateAsync(newUser, userRegistrationRequest.Password);

            if (!createdUserResult.Succeeded)
            {
                throw new IllegalArgumentException(createdUserResult.Errors
                                                   .Select(x => x.Description).Aggregate((s1, s2) => $"{s1},{s2}"));
            }


            //user created successfully
        }