示例#1
0
def facebook_friends(accesstoken, user):
    user = User.objects.filter(id=user).first()
    '''
        1. getting the graph object by using the accesstoken
        2. getting the frieds list from graph object
        3. Removing friends data if the user previously connected to the site
        4. Creating facebook friends list
    '''

    graph = GraphAPI(accesstoken)
    friends = graph.get_object("me/friends")
    FacebookFriend.objects.filter(user=user).delete()
    for each in friends['data']:
        FacebookFriend.objects.create(
            user=user, facebook_id=each['id'], name=each['name'])
def add_facebook_friends_pages_groups(accesstoken, fid, user):
    graph = GraphAPI(accesstoken)
    friends = graph.get_object("me/friends")
    # TODO:
    # Facebook not giving all friends, we need to frinds in paging and insert.
    for friend in friends["data"]:
        FacebookFriend.objects.create(user=user,
                                      name=friend["name"],
                                      facebook_id=friend["id"])
    user_profile = requests.get("https://graph.facebook.com/me/accounts",
                                params={"access_token": accesstoken})
    pages = user_profile.json()["data"]

    for page in pages:
        url = ("https://graph.facebook.com/oauth/access_token?client_id=" +
               settings.FB_APP_ID + "&client_secret=" + settings.FB_SECRET +
               "&grant_type=fb_exchange_token&fb_exchange_token=" +
               accesstoken)
        import urllib.request as ur

        print(ur.urlopen(url).read())
        response = str(ur.urlopen(url).readline()).split("&")[0]
        if len(response.split("=")) > 2:
            access_token = response.split("=")[1]

            FacebookPage.objects.create(
                user=user,
                category=page["category"],
                name=page["name"],
                accesstoken=access_token,
                page_id=page["id"],
                permission=page["perms"],
            )

    user_groups = requests.get("https://graph.facebook.com/me/groups",
                               params={"access_token": accesstoken})
    groups = user_groups.json()["data"]
    for group in groups:
        FacebookGroup.objects.create(user=user,
                                     group_id=group["id"],
                                     name=group["name"])
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)