public async Task <JwtDto> LoginWithFacebookAsync(string accessToken)
        {
            var validatedTokenResult = await _facebookAuthService.ValidateAccessTokenAsync(accessToken);

            if (!validatedTokenResult.FacebookTokenValidationData.IsValid)
            {
                throw new InvalidFacebookTokenException();
            }

            var userInfo = await _facebookAuthService.GetUserInfoAsync(accessToken);

            var user = await _userRepository.GetByEmailAsync(userInfo.Email);

            // if user does not exist create user and sign in
            // else user exists, just sign in
            if (user is null)
            {
                user = new User(userInfo.Email, userInfo.Email);

                await _userManager.CreateAsync(user);

                await _userManager.AddToRoleAsync(user, RoleId.User.ToString());

                await _athleteService.CreateAsync(user.Id);
            }

            var jwt = _jwtHandler.CreateToken(user.Id, user.UserName, RoleId.User.ToString());

            jwt.RefreshToken = await CreateRefreshTokenAsync(user.Id);

            return(jwt);
        }
        public async Task <IActionResult> SignInWithFb(string accessToken)
        {
            var validatedToken = await _facebookAuthService.ValidateAccessTokenAsync(accessToken);

            //invalid token
            if (!validatedToken.Data.IsValid)
            {
                TempData["Error"] = "An error occures. Please try again.";
                return(Json(new { Text = "An error occures. Please try again." }));
            }

            var userInfo = await _facebookAuthService.GetUserInfoAsync(accessToken);

            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            //user is not db we have to register
            if (user == null)
            {
                await CreateNewUserAndStudentForFbUser(userInfo);

                return(RedirectToAction("Edit"));
            }

            //user is registered already we just log him in
            await _signInManager.SignInAsync(user, true);

            return(RedirectToAction("Edit", "Account"));
        }
Esempio n. 3
0
        public async Task <AuthenticationResult> LoginWithFacebookAsync(string accessToken)
        {
            var validatedToken = await _facebookAuthService.ValidationAccessTokenAsync(accessToken);

            if (!validatedToken.Data.IsValid)
            {
            }

            var userInfo = await _facebookAuthService.GetUserInfoAsync(accessToken);

            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                var identityUser = new IdentityUser
                {
                    Id       = Guid.NewGuid().ToString(),
                    Email    = userInfo.Email,
                    UserName = userInfo.Email
                };
                var createdUser = await _userManager.CreateAsync(identityUser);

                if (!createdUser.Succeeded)
                {
                }

                return(await GenerateAuthenticationResultForUseAsync(user));
            }
            return(await GenerateAuthenticationResultForUseAsync(user));
        }
Esempio n. 4
0
        public async Task <AuthenticationResponse> LoginWithFacebookAsync(string facebookAccessToken)
        {
            //request to facebook validate api
            var validatedToken = await facebookAuthService.VlidateAccessTokenAsync(facebookAccessToken);

            if (!validatedToken.Data.IsValid)
            {
                new AuthenticationResponse
                {
                    Errors = new[] { "Invalid facebook token" }
                }
            }
            ;
            //get useriformations from facebook kardeş
            var userInfo = await facebookAuthService.GetUserInfoAsync(facebookAccessToken);

            if (userInfo == null)
            {
                new AuthenticationResponse
                {
                    Errors = new[] { "Something went wrong try a few seconds later..." }
                }
            }
            ;

            var user = await userManager.FindByEmailAsync(userInfo.Email);

            // user not exist register it mofo
            if (user == null)
            {
                user = new AppUser
                {
                    Id       = Guid.NewGuid().ToString(),
                    Email    = userInfo.Email,
                    UserName = userInfo.Email
                };

                //creating without password user have to through facebook
                var createdResult = await userManager.CreateAsync(user);

                if (!createdResult.Succeeded)
                {
                    new AuthenticationResponse
                    {
                        Errors = new[] { "Something went wrong try a few seconds later..." }
                    };
                }
            }
            return(await GetAuthenticationResultAsync(user));
        }
    }
}
Esempio n. 5
0
        public async Task LoginWithFacebookAsync_ShouldAddNewUser_IfUserDoesNotExistAndTokenIsValid()
        {
            var accessToken = "EAABw3KiLV1QBACrZCNuvHBaijiPEURQzAhVqZCG";

            var facebookTokenValidationResult = new FacebookTokenValidationResult
            {
                FacebookTokenValidationData = new FacebookTokenValidationData
                {
                    IsValid = true
                }
            };

            var facebookInfoResult = new FacebookUserInfoResult
            {
                Id        = Guid.NewGuid().ToString(),
                FirstName = "test",
                LastName  = "user",
                Email     = "*****@*****.**",
            };

            _facebookAuthService.ValidateAccessTokenAsync(accessToken).Returns(facebookTokenValidationResult);

            _facebookAuthService.GetUserInfoAsync(accessToken).Returns(facebookInfoResult);

            var jwtDto = _fixture.Create <JwtDto>();

            _jwtHandler.CreateToken(Arg.Any <int>(), Arg.Any <string>(), Arg.Any <string>()).Returns(jwtDto);

            var jwt = await _sut.LoginWithFacebookAsync(accessToken);

            jwt.ShouldNotBeNull();
            jwt.ShouldBeOfType(typeof(JwtDto));
            jwt.UserId.ShouldBe(jwtDto.UserId);
            jwt.Username.ShouldBe(jwtDto.Username);
            jwt.Role.ShouldBe(jwtDto.Role);
            jwt.AccessToken.ShouldBe(jwtDto.AccessToken);
            jwt.Expires.ShouldBe(jwtDto.Expires);
            jwt.RefreshToken.ShouldBe(jwtDto.RefreshToken);
        }
Esempio n. 6
0
        public async Task <AuthenticationResult> LoginFacebookAsync(string accessToken)
        {
            var validatedTokenResponse = await _facebookAuthService.ValidateAccessTokenAsync(accessToken);

            if (!validatedTokenResponse.Success)
            {
                return(new AuthenticationResult()
                {
                    Errors = new[] { "Invalid Facebook token" }
                });
            }

            var userInfoResponse = await _facebookAuthService.GetUserInfoAsync(accessToken);

            if (!userInfoResponse.Success)
            {
                return(new AuthenticationResult()
                {
                    Errors = new[] { "Invalid user" }
                });
            }

            var user = await _userManager.FindByEmailAsync(userInfoResponse.Data.Email);

            if (user == null)
            {
                user = new ApplicationUser()
                {
                    Id       = Guid.NewGuid().ToString(),
                    Email    = userInfoResponse.Data.Email,
                    UserName = userInfoResponse.Data.Email
                };

                var createdResult = await _userManager.CreateAsync(user);

                if (!createdResult.Succeeded)
                {
                    return(new AuthenticationResult()
                    {
                        Errors = new[] { "Something went wrong" }
                    });
                }

                return(await GenerateTokenForUserAsync(user.Email));
            }

            return(await GenerateTokenForUserAsync(user.Email));
        }
        public async Task <AuthenticationResultViewModel> LoginWithFacebook(LoginWithFacebookViewModel input)
        {
            var validatedToken = await _facebookAuthService.ValidateAccessTokenAsync(input.AccessToken);

            if (!validatedToken.Data.IsValid)
            {
                throw new Exception("Couldn't obtain facebook data!");
            }
            var userInfo = await _facebookAuthService.GetUserInfoAsync(input.AccessToken);

            var userName = string.Concat(userInfo.FirstName, userInfo.LastName, userInfo.Id);
            var user     = await _userManager.FindByNameAsync(userName);

            if (user == null)
            {
                var result = await Register(new RegisterViewModel()
                {
                    FirstName = userInfo.FirstName,
                    LastName  = userInfo.LastName,
                    Email     = string.Concat(userName, "@mail.com"),
                    UserName  = userName,
                    Roles     = new List <string>
                    {
                        "User"
                    }
                }, true);

                return(result);
            }
            var accessToken = await GenerateJWT(user);

            return(new AuthenticationResultViewModel
            {
                FirstName = user.FirstName,
                LastName = user.LastName,
                Email = user.Email,
                UserId = user.Id,
                UserName = user.UserName,
                AccessToken = accessToken
            });
        }
Esempio n. 8
0
        public async Task <AuthenticationResult> LoginWithFacebookAsync(string accessToken)
        {
            var validatedTokenResult = await _facebookAuthService.ValidateAccessTokenAsync(accessToken);

            if (!validatedTokenResult.Data.IsValid)
            {
                return(new AuthenticationResult
                {
                    Errors = new[] { "Invalid Facebook token" }
                });
            }

            var userInfo = await _facebookAuthService.GetUserInfoAsync(accessToken);

            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                var identityUser = new IdentityUser
                {
                    Id       = Guid.NewGuid().ToString(),
                    Email    = userInfo.Email,
                    UserName = userInfo.Email
                };

                var createdResult = await _userManager.CreateAsync(identityUser);

                var errors = createdResult.Errors;//errors of result
                if (!createdResult.Succeeded)
                {
                    return(new AuthenticationResult
                    {
                        Errors = new[] { "Something went wrong" }
                    });
                }

                return(await GenerateAuthentiicationResultForUserAsync(identityUser));
            }

            return(await GenerateAuthentiicationResultForUserAsync(user));
        }
Esempio n. 9
0
        public async Task <AuthenticationResponse> FacebookLoginStoreOwnerAsync(string accessToken)
        {
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                return new AuthenticationResponse {
                           Errors = new[] { "AccessToken cannot be empty." }
                }
            }
            ;

            var validateTokenResult = await _facebookAuthService.ValidateAccessTokenAsync(accessToken);

            if (validateTokenResult.Data != null)
            {
                if (!validateTokenResult.Data.IsValid)
                {
                    return new AuthenticationResponse {
                               Errors = new[] { "Invalid Facebook Token." }
                    }
                }
                ;

                var fbUserInfo = await _facebookAuthService.GetUserInfoAsync(accessToken);

                if (fbUserInfo.Id == "Failed")
                {
                    return new AuthenticationResponse {
                               Errors = new[] { "Failed to Get Facebook User. " }
                    }
                }
                ;

                var storeOwnerExist = await _dataContext.StoreOwners.FirstOrDefaultAsync(s => s.EmailAddress == fbUserInfo.Email);

                if (storeOwnerExist == null) //Register StoreOwner
                {
                    var newStoreOwner = new StoreOwner()
                    {
                        EmailAddress         = fbUserInfo.Email,
                        FirstName            = fbUserInfo.FirstName,
                        MiddleName           = fbUserInfo.MiddleName,
                        LastName             = fbUserInfo.LastName,
                        PhoneNumber          = string.Empty,
                        ProfilePicUrl        = fbUserInfo.Picture.FacebookPictureData.Url.ToString(),
                        IsVerified           = true,
                        DateRegistered       = DateTime.Now,
                        IsFacebookRegistered = true
                    };

                    await _dataContext.StoreOwners.AddAsync(newStoreOwner);

                    var created = await _dataContext.SaveChangesAsync();

                    if (created <= 0)
                    {
                        return new AuthenticationResponse {
                                   Errors = new[] { "Failed to create customer" }
                        }
                    }
                    ;

                    var token = GenerateAuthenticationTokenForStoreOwner(newStoreOwner);
                    return(new AuthenticationResponse {
                        Success = true, Token = token
                    });
                }
                else //Signin StoreOwner
                {
                    storeOwnerExist.LastLoginDate             = DateTime.Now;
                    _dataContext.Entry(storeOwnerExist).State = EntityState.Modified;
                    var updated = await _dataContext.SaveChangesAsync();

                    if (updated <= 0)
                    {
                        return new AuthenticationResponse {
                                   Errors = new[] { "Failed to signin." }
                        }
                    }
                    ;

                    var token = GenerateAuthenticationTokenForStoreOwner(storeOwnerExist);
                    return(new AuthenticationResponse {
                        Success = true, Token = token
                    });
                }
            }
            else
            {
                return(new AuthenticationResponse {
                    Errors = new[] { "Failed to Validate Facebook." }
                });
            }
        }
Esempio n. 10
0
 public async Task <IActionResult> GetUserInfo(string accesstoken)
 {
     return(Ok(await _facebookAuthService.GetUserInfoAsync(accesstoken)));
 }