public async Task <IActionResult> RegisterUser([FromBody] RegisterUserViewModel registerUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequestDueToModelState());
            }

            try
            {
                var userIdentity = _mapper.Map <AppUser>(registerUser);

                var result = await _userManager.CreateAsync(userIdentity, registerUser.Password);

                if (!result.Succeeded)
                {
                    ModelState.AddErrorsToModelState(result);
                    return(BadRequestDueToModelState());
                }

                await _userContext.Users.AddAsync(new User { IdentityId = userIdentity.Id, FirstName = registerUser.FirstName, LastName = registerUser.LastName });

                await _userContext.SaveChangesAsync();

                return(new OkObjectResult("User registered successfully!"));
            }
            catch (Exception ex)
            {
                return(BadRequest(new ErrorResponseModel
                {
                    Message = ex.Message,
                    Exception = ex.GetType().Name,
                    Code = 400
                }));
            }
        }
Example #2
0
        public async Task <IActionResult> Create([FromBody] CreateUserModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User()
                {
                    Email    = model.Email,
                    UserName = model.UserName ?? model.Email
                };

                var createUser = await _userManager.CreateAsync(user, model.Password);

                if (createUser.Succeeded)
                {
                    var setRole = await _userManager.AddToRoleAsync(user, RoleConstants.User);

                    if (setRole.Succeeded)
                    {
                        return(Ok(_mapper.Map <CreateUserResponse>(user)));
                    }

                    ModelState.AddErrorsToModelState(setRole.Errors);
                }

                ModelState.AddErrorsToModelState(createUser.Errors);
            }

            return(BadRequest(ModelState));
        }
Example #3
0
        public async Task <IActionResult> Post([FromBody] CustomerRegistrationViewModel model)
        {
            _logger.LogInformation("Post");
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var userIdentity = _mapper.Map <AppUser>(model);
                var result       = await _userManager.CreateAsync(userIdentity, model.Password);

                if (!result.Succeeded)
                {
                    return(new BadRequestObjectResult(ModelState.AddErrorsToModelState(result)));
                }
                await _applicationDbContext.AddCustomer(userIdentity.Id);

                return(new OkObjectResult("Account created"));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Post");
                ModelState.AddErrorToModelState(e);
                return(BadRequest(ModelState));
            }
        }
Example #4
0
        public async Task <IActionResult> Facebook([FromBody] FacebookAuthViewModel model)
        {
            // 1.generate an app access token
            var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials");

            var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse);
            // 2. validate the user access token
            var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}");

            var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);

            if (!userAccessTokenValidation.Data.IsValid)
            {
                return(BadRequest(new ErrorResponseModel
                {
                    Message = $"{Constants.Errors.FbLoginFailed.Code},{Constants.Errors.FbLoginFailed.Desc}",
                    Code = 400,
                    Exception = nameof(Constants.Errors.FbLoginFailed)
                }));
            }

            // 3. we've got a valid token so we can request user data from fb
            var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={model.AccessToken}");

            var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse);

            // 4. ready to create the local user account (if necessary) and jwt
            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                var appUser = new AppUser
                {
                    FirstName  = userInfo.FirstName,
                    LastName   = userInfo.LastName,
                    FacebookId = userInfo.Id,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    PictureUrl = userInfo.Picture.Data.Url
                };

                var result = await _userManager.CreateAsync(appUser, (Guid.NewGuid().ToByteArray().ToBase64String()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    ModelState.AddErrorsToModelState(result);
                    return(BadRequestDueToModelState());
                }

                await _userContext.Users.AddAsync(new User { IdentityId = appUser.Id, Gender = userInfo.Gender });

                await _userContext.SaveChangesAsync();
            }

            // generate the jwt for the local user...
            var localUser = await _userManager.FindByNameAsync(userInfo.Email);

            if (localUser == null)
            {
                //mark modelstate as invalid
                //return BadRequest(ModelState.AddErrorToModelState(Constants.Errors.LoginFailed.Code,Constants.Errors.LoginFailed.Desc));
                return(BadRequest(new ErrorResponseModel
                {
                    Message = $"{Constants.Errors.LoginFailed.Code},{Constants.Errors.LoginFailed.Desc}",
                    Code = 400,
                    Exception = nameof(Constants.Errors.LoginFailed)
                }));
            }
            var identity = _tokenUtility.GenerateClaimsIdentity(localUser.UserName, localUser.Id);
            var jwt      = await identity.GenerateJwtJson(_tokenUtility, localUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

            return(new OkObjectResult(jwt));
        }