예제 #1
0
        public async Task <TokenResponseDTO> Register(RegistrationRequestDTO data)
        {
            var user = _userRepository
                       .FindByPredicate(u => u.Email == data.Email)
                       .FirstOrDefault();

            if (user != null)
            {
                throw new EntityAlreadyExistsException("User already exist");
            }

            var newUser = _mapper.Map <ApplicationUser>(data);

            newUser.Role     = "User";
            newUser.Password = _hasher.Hash(data.Password);

            await _userRepository.AddAsync(newUser);

            var tokenDescriptor = GetTokenDescriptor(newUser);

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(new TokenResponseDTO {
                Token = tokenHandler.WriteToken(token)
            });
        }
예제 #2
0
 public async Task <Admin> RegisterAsync(AdminDto adminDto)
 {
     if (await _repository.UserExistsAsync(adminDto.Username))
     {
         return(null);
     }
     return(await _repository.AddAsync(adminDto));
 }
예제 #3
0
        public async Task <AuthResponse> CreateUserAsync(User user, ERole[] userRoles, EType[] userTypes)
        {
            var existingUser = await _authRepository.FindByEmailAsync(user.Email);

            if (existingUser != null)
            {
                return(new AuthResponse("Email already in use."));
            }

            user.Password = _passwordHasher.HashPassword(user.Password);

            await _authRepository.AddAsync(user, userRoles, userTypes);

            return(new AuthResponse(user));
        }
예제 #4
0
        public async Task <IActionResult> Register([FromBody] UserRegister user)
        {
            if (ModelState.IsValid)
            {
                var userRegistered = await authRepository.AddAsync(new User(user.Name, user.Email, user.Password));

                if (userRegistered == null)
                {
                    return(BadRequest(authRepository.ObterErros()));
                }

                return(CreatedAtAction("Register", userRegistered));
            }

            return(BadRequest(ModelState.Values.FirstOrDefault().Errors.FirstOrDefault().ErrorMessage));
        }
예제 #5
0
        public async Task <(string newtoken, string newRefreshToken)> GetTokens(ClientUser user)
        {
            // Caso seja encontrado algum usuário com a combinação username e password
            if (user != null)
            {
                string newToken        = CreateToken(user);    // Cria o token de acesso
                string newRefreshToken = CreateRefreshToken(); // Cria o refresh token

                // Verifica se o usuário existe dentro dos usuários logados
                LoggedUser loggedUser =
                    (from current in _db.LoggedUsers
                     where current.Username == user.Username
                     select current).FirstOrDefault();

                if (loggedUser == null) // Se o usuário não existir, registrar login
                {
                    loggedUser = new LoggedUser()
                    {
                        Username     = user.Username,
                        RefreshToken = newRefreshToken,
                        LastLogin    = DateTime.Now,
                        ExpiresAt    = DateTime.Now.AddMinutes(30)
                    };

                    await loggedUserRepository.AddAsync(loggedUser);
                }
                else // Caso contrário, atualiza as informações
                {
                    loggedUser.RefreshToken = newRefreshToken;
                    loggedUser.LastLogin    = DateTime.Now;
                    loggedUser.ExpiresAt    = DateTime.Now.AddMinutes(30);

                    await loggedUserRepository.SaveAsync();
                }

                return(newToken, newRefreshToken);
            }

            return(string.Empty, string.Empty);
        }
예제 #6
0
        public async Task <ServiceResponse <Guid> > Register(User user, string password)
        {
            ServiceResponse <Guid> response = new ServiceResponse <Guid>();

            if (await UserExists(user))
            {
                response.Success = false;
                response.Message = "UserName or Email already exists.";
                return(response);
            }
            CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt);
            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;
            await _emailSender.SendEmailAsync("*****@*****.**", "Confim email", $"Hi {user.Name} {user.FirstName} please, confirm your email");

            await _authRepo.AddAsync(user);

            await _authRepo.SaveChangesAsync();

            response.Data = user.Id;

            return(response);
        }
        public async Task <IResult <AuthEntity> > AddAsync(AuthModel authModel)
        {
            var validation = new AuthModelValidator().Validate(authModel);

            if (validation.Failed)
            {
                return(Result <AuthEntity> .Fail(validation.Message));
            }

            if (await _authRepository.AnyByLoginAsync(authModel.Login))
            {
                return(Result <AuthEntity> .Fail(Texts.AuthError));
            }

            var authEntity = AuthFactory.Create(authModel);

            var password = _hashService.Create(authEntity.Password, authEntity.Salt);

            authEntity.ChangePassword(password);

            await _authRepository.AddAsync(authEntity);

            return(Result <AuthEntity> .Success(authEntity));
        }
예제 #8
0
    public async Task <IResult <Auth> > AddAsync(AuthModel model)
    {
        var validation = new AuthModelValidator().Validation(model);

        if (validation.Failed)
        {
            return(validation.Fail <Auth>());
        }

        if (await _authRepository.AnyByLoginAsync(model.Login))
        {
            return(Result <Auth> .Fail("Login exists!"));
        }

        var auth = _authFactory.Create(model);

        var password = _hashService.Create(auth.Password, auth.Salt);

        auth.UpdatePassword(password);

        await _authRepository.AddAsync(auth);

        return(auth.Success());
    }
예제 #9
0
        public async Task <IResult <Auth> > AddAsync(AuthModel model)
        {
            var validation = await new AuthModelValidator().ValidateAsync(model);

            if (validation.Failed)
            {
                return(Result <Auth> .Fail(validation.Message));
            }

            if (await _authRepository.AnyByLoginAsync(model.Login))
            {
                return(Result <Auth> .Fail(Texts.LoginAlreadyExists));
            }

            var auth = AuthFactory.Create(model);

            var password = _hashService.Create(auth.Password, auth.Salt);

            auth.ChangePassword(password);

            await _authRepository.AddAsync(auth);

            return(Result <Auth> .Success(auth));
        }