Ejemplo n.º 1
0
        public IActionResult LoginWithSocial([FromBody] UserForSocialLoginDto userForSocial)
        {
            if (userForSocial == null)
            {
                return(BadRequest());
            }

            User user = new User
            {
                Name               = userForSocial.Name,
                Email              = userForSocial.Email,
                UserName           = userForSocial.Email,
                NormalizedEmail    = userForSocial.Email.ToUpper(new CultureInfo("en-Us")),
                NormalizedUserName = userForSocial.Email.ToUpper(new CultureInfo("en-Us")),
                EmailConfirmed     = true
            };

            IDataResult <UserLogin> userLoginResult = _userLoginService.GetByProviderKey(userForSocial.Id, userForSocial.Provider);

            if (userLoginResult.Success && userLoginResult.Data == null)
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    UserLogin userLogin = new UserLogin
                    {
                        LoginProvider       = userForSocial.Provider,
                        ProviderKey         = userForSocial.Id,
                        ProviderDisplayName = userForSocial.Provider
                    };

                    var userDb = _userService.GetByEmail(userForSocial.Email);
                    if (userDb == null)
                    {
                        _userService.RegisterForSocialLogin(user);
                        userLogin.UserId = user.Id;
                    }
                    else
                    {
                        userLogin.UserId = userDb.Id;
                    }


                    IResult userLoginAddResult = _userLoginService.Add(userLogin);
                    if (!userLoginAddResult.Success)
                    {
                        return(BadRequest());
                    }

                    transaction.Complete();
                }
            }


            IDataResult <AccessToken> createTokenResult = _userService.CreateAccessTokenForLogin(user, true);

            if (!createTokenResult.Success)
            {
                return(BadRequest(new ErrorResultDto
                {
                    Name = ErrorNames.DefaultError,
                    Type = ErrorTypes.Danger,
                    Value = SecurityMessages.SystemError
                }));
            }

            return(Ok(createTokenResult));
        }