private async Task <IActionResult> GetToken(TokenRequestViewModel viewModel)
        {
            var user = await _userAndRoleRepository.GetUserByNameAsync(viewModel.Username);

            if (user == null && viewModel.Username.Contains("@"))
            {
                user = await _userAndRoleRepository.GetUserByEmailAsync(viewModel.Username);
            }

            if (user == null || !await _userAndRoleRepository.CheckPasswordAsync(user, viewModel.Password))
            {
                return(new UnauthorizedResult());
            }

            var token = _tokenService.GenerateRefreshToken(viewModel.ClientId, user.Id);

            await _tokenRepository.AddRefreshToken(token);

            var accessTokenData = _tokenService.CreateAccessToken(user.Id);

            var response = new TokenResponseViewModel
            {
                Token        = accessTokenData.EncodedToken,
                Expiration   = accessTokenData.ExporationTimeInMinutes,
                RefreshToken = token.Value
            };

            return(Json(response));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Post([FromBody] UserViewModel viewModel)
        {
            if (viewModel == null)
            {
                return(new BadRequestResult());
            }

            try
            {
                ApplicationUser user = await _userAndRoleRepository.GetUserByNameAsync(viewModel.UserName);

                if (user != null)
                {
                    return(BadRequest("User with given username already exists"));
                }

                user = await _userAndRoleRepository.GetUserByEmailAsync(viewModel.Email);

                if (user != null)
                {
                    return(BadRequest("User with given e-mail already exists"));
                }

                var createdUser = await _userAndRoleRepository.CreateUserAndAddToRolesAsync(
                    viewModel.Adapt <ApplicationUser>(),
                    new[] { UserRoles.RegisteredUser });

                return(Json(createdUser.Adapt <UserViewModel>(), JsonSettings));
            }
            catch (Exception e)
            {
                return(new StatusCodeResult(500));
            }
        }