def facebook_connect(request):
    if "code" in request.GET:
        accesstoken = get_access_token_from_code(
            request.GET["code"],
            request.scheme + "://" + request.META["HTTP_HOST"] +
            reverse("social:facebook_connect"),
            settings.FB_APP_ID,
            settings.FB_SECRET,
        )
        if "error" in accesstoken.keys():
            message = "Sorry, Your session has been expired"
            reason = "Please kindly try again login to update your profile"
            return render(request,
                          "404.html", {
                              "message": message,
                              "reason": reason
                          },
                          status=404)
        graph = GraphAPI(accesstoken["access_token"])
        accesstoken = graph.extend_access_token(
            settings.FB_APP_ID, settings.FB_SECRET)["accesstoken"]

        profile = graph.get_object(
            "me",
            fields="id, name, email",
        )
        # email = profile['email'] if 'email' in profile.keys() else ''
        if "email" not in profile.keys():
            message = "Sorry, We didnt find your email id through facebook"
            reason = "Please verify your email id in facebook and try again"
            return render(request,
                          "404.html", {
                              "message": message,
                              "reason": reason
                          },
                          status=404)

        if request.user.is_authenticated:
            Facebook.objects.create(
                user=request.user,
                facebook_id=profile.get("id", ""),
                name=profile.get("name", ""),
                email=profile["email"],
            )
            email_matches = UserEmail.objects.filter(user=request.user,
                                                     email=profile["email"])
            if not email_matches:
                UserEmail.objects.create(user=request.user,
                                         email=profile["email"])

        return HttpResponseRedirect(reverse("my:profile"))

    elif "error" in request.GET:
        return HttpResponseRedirect(reverse("my:profile"))
    else:
        # our code to fix it
        rty = ("https://graph.facebook.com/oauth/authorize?client_id=" +
               settings.FB_APP_ID + "&redirect_uri=" + request.scheme + "://" +
               request.META["HTTP_HOST"] + reverse("social:facebook_connect") +
               "&scope=email")
        return HttpResponseRedirect(rty)
def facebook_login(request):
    if "code" in request.GET:
        accesstoken = get_access_token_from_code(
            request.GET["code"],
            request.scheme + "://" + request.META["HTTP_HOST"] +
            reverse("social:facebook_login"),
            settings.FB_APP_ID,
            settings.FB_SECRET,
        )
        if "error" in accesstoken.keys(
        ) or not accesstoken.get("access_token"):
            return render(
                request,
                "404.html",
                {
                    "message": "Sorry, Your session has been expired",
                    "reason":
                    "Please kindly try again login to update your profile",
                    "email": settings.DEFAULT_FROM_EMAIL,
                    "number": settings.CONTACT_NUMBER,
                },
                status=404,
            )
        graph = GraphAPI(accesstoken["access_token"])
        accesstoken = graph.extend_access_token(
            settings.FB_APP_ID, settings.FB_SECRET)["accesstoken"]
        profile = graph.get_object(
            "me",
            fields="id, name, email",
        )
        email = profile.get("email", "")

        if "email" in profile.keys():
            email_matches = UserEmail.objects.filter(
                email__iexact=email).first()
            if email_matches:
                user = email_matches.user
                if user.is_recruiter or user.is_agency_recruiter:
                    user = authenticate(username=user.username)
                    login(request, user)
                    return HttpResponseRedirect(reverse("recruiter:index"))

                # Checking Email associated with the user but user is not connected to facebook
                if not user.is_fb_connected:
                    Facebook.objects.create(
                        user=user,
                        name=profile.get("name", ""),
                        email=profile.get("email", ""),
                    )
                    user.save()
                user = authenticate(username=user.email)
            else:
                user = User.objects.filter(
                    email__iexact=profile.get("email", "")).first()
                if user:
                    user.first_name = profile.get("name", "")
                    user.profile_updated = datetime.now(timezone.utc)
                    user.is_active = True
                    user.save()
                else:
                    user = User.objects.create(
                        username=profile.get("email", ""),
                        email=profile.get("email", ""),
                        first_name=profile.get("name", ""),
                        last_name=profile.get("name", ""),
                        user_type="JS",
                        profile_updated=datetime.now(timezone.utc),
                        is_active=True,
                        registered_from="Social",
                    )

                Facebook.objects.create(
                    user=user,
                    facebook_id=profile.get("id"),
                    name=profile.get("name", ""),
                    email=profile.get("email", ""),
                )
                UserEmail.objects.create(user=user,
                                         email=profile.get("email"),
                                         is_primary=True)
                user = authenticate(username=user.username)
                user.last_login = datetime.now()
                user.is_bounce = False
                user.referer = request.session.get("referer", "")
                user.save()
                login(request, user)
                return HttpResponseRedirect("/social/user/update/")
        else:
            return render(
                request,
                "404.html",
                {
                    "message":
                    "Sorry, We didnt find your email id through facebook",
                    "reason":
                    "Please verify your email id in facebook and try again",
                    "email": settings.DEFAULT_FROM_EMAIL,
                    "number": settings.CONTACT_NUMBER,
                },
                status=404,
            )

        login(request, user)
        if "design" in request.session.keys(
        ) and request.is_mobile == "mobile":
            if request.session.get("job_id"):
                post = JobPost.objects.filter(id=request.session["job_id"],
                                              status="Live")
                return HttpResponseRedirect(post[0].slug)
            return HttpResponseRedirect("/jobs/")
        # Apply job after login starts
        if request.session.get("job_id"):
            log_apply = login_and_apply(request)
            if log_apply:
                return HttpResponseRedirect(log_apply[0].slug + "?job_apply=" +
                                            log_apply[1])
        # Apply job after login ends
        if user.profile_completion_percentage < 50:
            return HttpResponseRedirect(reverse("my:profile"))
        return HttpResponseRedirect("/")
    elif "error" in request.GET:
        # TODO : llog the error and transfer to error page
        return HttpResponseRedirect("/jobs/")
    else:
        print(settings.FB_APP_ID)

        rty = ("https://graph.facebook.com/oauth/authorize?client_id=" +
               settings.FB_APP_ID + "&redirect_uri=" + request.scheme + "://" +
               request.META["HTTP_HOST"] + reverse("social:facebook_login") +
               "&scope=email")
        return HttpResponseRedirect(rty)