示例#1
0
def user_get_token():
    #
    # GET AN AUTH CODE
    #
    CLIENT_ID = os.environ.get("LINKEDIN_CLIENT_ID", "OOPS")
    CLIENT_SECRET = os.environ.get("LINKEDIN_CLIENT_SECRET", "OOPS")
    REDIRECT_URL = os.environ.get("LINKEDIN_REDIRECT_URL", "http://localhost:8000")
    #print(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL)

    auth = linkedin.LinkedInAuthentication(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, PERMISSIONS)
    #print(type(auth)) #> <class 'linkedin_v2.linkedin.LinkedInAuthentication'>
    #print(auth.authorization_url)

    webbrowser.open_new(auth.authorization_url)
    # login, grant permissions, then you'll be redirected to a localhost url.
    # ... observe the "code" parameter, and enter it below
    # ... making sure to remove the "state" parameter part of the url, which might come at the end
    auth_code = input("The auth code was:")

    auth.authorization_code = auth_code

    #
    # GET AN ACCESS TOKEN
    #

    access_token = auth.get_access_token() # this is an AccessToken object with a access_token property, which should be stored in the env var

    return access_token
示例#2
0
def linkedAuthenticateAs(permissions):
    auth = linkedin.LinkedInAuthentication(
        keys.LINKEDIN_CLIENT_ID,
        keys.LINKEDIN_CLIENT_SECRET,
        keys.LINKEDIN_CALLBACK,
        permissions=["w_member_social", "r_liteprofile"])
    auth.state = f"{hex(random.getrandbits(128))}"
    session["linkedin-hash"] = auth.state
    return redirect(auth.authorization_url)
示例#3
0
def convert_v2(source, crossrefQuery='', token=''):
    global application

    if token == '':

        authentication = linkedin.LinkedInAuthentication(
            API_KEY, API_SECRET, RETURN_URL, PERMISSIONS.enums.values())

        authorization_url = authentication.authorization_url

        authorization_url = authorization_url.replace(
            '%20r_fullprofile', '').replace('%20rw_groups', '').replace(
                '%20w_messages',
                '').replace('%20r_contactinfo',
                            '').replace('%20r_network',
                                        '').replace('%20rw_nus', '%20w_share')

        #print authorization_url

        cmd = 'open "' + authorization_url + '"'
        print cmd
        msg = subprocess.check_output(cmd, shell=True)

    else:

        authentication = linkedin.LinkedInAuthentication(
            API_KEY, API_SECRET, RETURN_URL, PERMISSIONS.enums.values())

        authentication.authorization_code = token

        access_token = authentication.get_access_token()

        print access_token[0]
        application = linkedin.LinkedInApplication(
            authentication=authentication, token=access_token[0])

    if application != None:

        print application.get_profile()

        #print application.get_profile(member_id='%5B%2213609%22%5D')

    return ''
def save_linkedin_token(request):
    authentication = linkedin.LinkedInAuthentication(LINKEDIN_API_KEY,
                                                     LINKEDIN_API_SECRET,
                                                     LINKEDIN_RETURN_URL,
                                                     LINKEDIN_PERMISSIONS)
    authentication.authorization_code = request.GET['code']
    token = authentication.get_access_token()
    Channel.objects.filter(source='linkedin').update(
        user_secret=authentication.authorization_code,
        user_token=token.access_token)
    messages.success(request, _('LinkedIn Channel Token updated successfully'))
    return redirect('admin:socialfeedsparser_channel_changelist')
 def token_renew_link(self):
     ret = ''
     if self.source == 'linkedin':
         authentication = linkedin.LinkedInAuthentication(
             LINKEDIN_API_KEY, LINKEDIN_API_SECRET, LINKEDIN_RETURN_URL,
             LINKEDIN_PERMISSIONS)
         # Optionally one can send custom "state" value that will be returned from OAuth server
         # It can be used to track your user state or something else (it's up to you)
         # Be aware that this value is sent to OAuth server AS IS - make sure to encode or hash it
         # authorization.state = 'your_encoded_message'
         ret = authentication.authorization_url  # open this url on your browser
         linkedin.LinkedInApplication(authentication)
     return ret
def get_auth_url():
    API_KEY_1 = '771xglr54lroll'
    API_KEY_2 = '779u3cu8a069wz'
    API_SECRET_1 = '4najxXcpYZmwVIJT'
    API_SECRET_2 = 'bcDwGS7N3GxcuiYD'
    RETURN_URL_1 = 'http://kinglife.best/api.php'
    RETURN_URL_2 = 'http://localhost:8000/code'

    authentication = lin.LinkedInAuthentication(
        API_KEY_2,
        API_SECRET_2,
        RETURN_URL_2,
        permissions=["r_liteprofile", 'r_emailaddress', 'w_member_social'])
    return authentication.authorization_url
示例#7
0
文件: auth.py 项目: abhijeetdtu/TA
def authenticate():
    creds = getCreds()
    API_KEY = creds["client_id"]
    API_SECRET = creds["client_secret"]
    RETURN_URL = 'http://localhost:8000'
    authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL,["r_liteprofile"])

    print(authentication.authorization_url)  # open this url on your browser

    authentication.authorization_code = "AQTiVEHx5potAMyle43UKPKU8ObWt2z2tUI75E72b1RMgRwvs2ZJ97kC97hEKyX56Eostp7FxhRzbcXhugSfkUK28czXIuunoyIj6mo_hT-aYbWeUocBcCkeVQmEhznbIpgENQl3yj6h2FuIFPcXFqo737bZVEyyiZfgkYPV1IExCgRBo0xHzrtmzljw_A"
    token = authentication.get_access_token()
    token_str = "AQVIe5jsla4VrGMRDNCuEcWkZYZxD5e93TSEwZZXNpKANy74NgGctVaLKUG3UcGrAI1tM_aUBxga91jx301sXCA7ahR3yOgLBB_LvZf9NaEAXAEQfi_0CUVoNf8JUPcyr9jcNZXvFYQZ8Hv-lp0JPlUTwOHcaVFple8g58LUHA5hQpAlQHar97yIk6zLU6D6fr8-czngg0fuOJ2cYBehqJ-DrTJKvE3Q3FmJbTmdlujhYVm-9X0WLFdRL2gAchJhhxubRo-ilNDAvYRPUHfDa2st2eJ_5w5woiS4qjJcTwBlyOewLFoXpaAxLrKbEdO83m_vz9NiaayC3EdxzNflq4HomaKyZg"
    application = linkedin.LinkedInApplication(token=authentication.authorization_code)
    application.
    application.get_profile()
示例#8
0
def LinkedAuthURL(request, id):
    from django.conf import settings
    from linkedin_v2 import linkedin

    try:
        return_url = 'http://localhost:8000/api/linkedin/callback/'
        authentication = linkedin.LinkedInAuthentication(settings.LINKEDIN_API_KEY, settings.LINKEDIN_API_SECRET,
                                                         return_url,
                                                         [linkedin.PERMISSIONS.BASIC_PROFILE])
        authentication.state = authentication._make_new_state()
        url = authentication.authorization_url
        candidate = Candidate.objects.get(id=id)
        candidate.temporal_state = authentication.state
        candidate.save()
        return HttpResponseRedirect(url)

    except:
        return HttpResponse("Problems with LinkedinAPI", status=400)
示例#9
0
def loginToLinkedInCallback():
    code = request.args.get("code")
    csrf_state = request.args.get("state")
    error = request.args.get("error")

    if session["linkedin-hash"] != csrf_state:
        raise InvalidUsage("401 Unauthorized")
    if error is not None:
        raise InvalidUsage("Error occured")

    auth = linkedin.LinkedInAuthentication(
        keys.LINKEDIN_CLIENT_ID,
        keys.LINKEDIN_CLIENT_SECRET,
        keys.LINKEDIN_CALLBACK,
        permissions=["w_member_social", "r_liteprofile"])
    print(keys.LINKEDIN_CALLBACK)
    auth.state = csrf_state
    auth.authorization_code = code
    session["linkedin-access-token"] = auth.get_access_token()

    return redirect("/")
示例#10
0
def LinkedCallback(request):
    from django.conf import settings
    from linkedin_v2 import linkedin

    try:
        authentication = linkedin.LinkedInAuthentication(settings.LINKEDIN_API_KEY, settings.LINKEDIN_API_SECRET,
                                                         'http://localhost:8000/api/linkedin/callback/',
                                                         [linkedin.PERMISSIONS.BASIC_PROFILE])

        authentication.authorization_code = request.GET.get('code', '')
        accessToken = authentication.get_access_token()

        candidate = Candidate.objects.get(temporal_state=request.GET.get('state', 'dsdsds'))
        LinkedInProfile.objects.filter(candidate=candidate).delete()
        LinkedInProfile.objects.create(candidate=candidate, access_token=accessToken.access_token,
                                       expires_in=accessToken.expires_in)

        return HttpResponse('Todo fino', status=200)

    except Exception as error:
        return HttpResponse("Problems with LinkedinAPI" + repr(error), status=500)
    def __init__(self):
        self.RETURN_URL = 'http://localhost:8000'
        self.ID = '78089tqwivmp7p'
        self.secret = '2BFAmePySISPl6qz'

        url = requests.Request(
            'GET',
            'https://www.linkedin.com/oauth/v2/authorization',
            params={
                'response_type':
                'code',
                'client_id':
                self.ID,
                'redirect_uri':
                self.RETURN_URL,
                'state':
                secrets.token_hex(8).upper(),
                'scope':
                '%20'.join(
                    ['r_liteprofile', 'r_emailaddress', 'w_member_social']),
            },
        ).prepare().url

        self.auth = linkedin.LinkedInAuthentication(
            self.ID, self.secret, self.RETURN_URL,
            linkedin.PERMISSIONS.enums.values())
        self.app = linkedin.LinkedInApplication(self.auth)
        print(url)
        resp = requests.get(url).content

        if url.find('code=') != -1:
            code_str = url[url.find('code=') + 5:url.find('&state=')]
            self.auth.authorization_code = code_str
            self.token = self.auth.get_access_token()
            self.app = linkedin.LinkedInApplication(
                token=self.token.access_token)
            print(
                self.app.search_profile(params={'keywords': 'Damian Rusinek'}))
示例#12
0
import random
from datetime import datetime
from io import BytesIO

import yaml
import PyPDF2
from django.core.mail import send_mail
from linkedin_v2 import linkedin
from linkedin_v2.linkedin import LinkedInApplication

from OpenAlumni import settings
from OpenAlumni.settings import LINKEDIN_API_KEY, LINKEDIN_RETURN_URL, LINKEDIN_API_SECRET, DOMAIN_APPLI, DOMAIN_SERVER, \
    APPNAME, EMAIL_HOST_USER, STATIC_ROOT, EMAIL_TESTER,MYDICT

authentication = linkedin.LinkedInAuthentication(LINKEDIN_API_KEY,
                                                 LINKEDIN_API_SECRET,
                                                 LINKEDIN_RETURN_URL,
                                                 permissions="r_basicprofil")
print(authentication.authorization_url)
LinkedInApplication(authentication)


def to_xml(df, row_separator="row"):
    def row_to_xml(row):
        xml = ['<' + row_separator + '>']

        for i, col_name in enumerate(row.index):
            val = html.escape(str(row.iloc[i]))
            if len(col_name) > 0:
                xml.append('<field name="{0}">{1}</field>'.format(
                    col_name, val))
            else:
示例#13
0
def linkedInContentPostVideo():
    if "linkedin-access-token" not in session or session[
            "linkedin-access-token"] is None:
        return redirect("/loginToLinkedInAsUser")

    auth = linkedin.LinkedInAuthentication(
        keys.LINKEDIN_CLIENT_ID,
        keys.LINKEDIN_CLIENT_SECRET,
        keys.LINKEDIN_CALLBACK,
        permissions=["w_member_social", "r_liteprofile"])
    print(keys.LINKEDIN_CALLBACK)
    auth.token = linkedin.AccessToken(session["linkedin-access-token"][0],
                                      session["linkedin-access-token"][1])
    app = linkedin.LinkedInApplication(auth)

    # Get User ID
    response = app.make_request("GET",
                                "https://api.linkedin.com/v2/me",
                                params={"fields": "id"})
    user_id = response.json()['id']
    owner_urn = f"urn:li:person:{user_id}"

    upload_response_context = []
    for file in request.files.getlist("file"):
        if linkedin_utils.linkedInMediaFilterLogic(
                file, keys.LINKEDIN_ALLOWED_VIDEO_EXTENSION):
            response, asset_urn = linkedin_utils.uploadVideoToLinkedIn(
                app, owner=owner_urn, data=file.read())
            # Check if error occured in response
            response.raise_for_status()
            upload_response_context.append((response, asset_urn))

    # Make sure video content is uploaded and ready to serve
    # remaining_request = upload_response_context.copy()
    # remaining_request_next = []
    # while (len(remaining_request) > 0) :
    #     for response, asset_urn in remaining_request:
    #         status_response = app.make_request("GET", f"https://api.linkedin.com/v2/assets/{asset_urn}")
    #         status_response.raise_for_status()
    #         status_response = status_response.json()
    #         upload_status = status_response["recipes"]["status"]
    #         if upload_status == "AVAILABLE":
    #             continue
    #         elif upload_status == "PROCESSING" or upload_status == "NEW" or upload_status == "MUTATING" or upload_status == "WAITING_UPLOAD" or :
    #             remaining_request_next.append((response, asset_urn))
    #         else:
    #             raise InvalidUsage("Upload Error Occured")
    #     remaining_request = remaining_request_next.copy()
    #     remaining_request_next = []
    #     time.sleep(5)

    text = "VIDEO UPLOAD WORK2222!"
    context = {
        "author": owner_urn,
        "lifecycleState": "PUBLISHED",
        "specificContent": {
            "com.linkedin.ugc.ShareContent": {
                "media": [{
                    "media": assert_urn,
                    "status": "READY",
                    "title": {
                        "attributes": [],
                        "text": "Sample Video Create"
                    }
                } for upload_response, assert_urn in upload_response_context],
                "shareCommentary": {
                    "attributes": [],
                    "text": text
                },
                "shareMediaCategory":
                "VIDEO"
            }
        },
        "visibility": {
            "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
        }
    }

    response = app.make_request("POST",
                                "https://api.linkedin.com/v2/ugcPosts",
                                data=json.dumps(context))

    print(f"{response} {response.headers} {response.json()}")

    return "Post-Content-2"
示例#14
0
def linkedInContentPost():
    if session["linkedin-access-token"] is None:
        return redirect("loginToLinkedInAsUser")

    # Set up linkedin applicatiom
    auth = linkedin.LinkedInAuthentication(
        keys.LINKEDIN_CLIENT_ID,
        keys.LINKEDIN_CLIENT_SECRET,
        keys.LINKEDIN_CALLBACK,
        permissions=["w_member_social", "r_liteprofile"])
    print(keys.LINKEDIN_CALLBACK)
    auth.token = linkedin.AccessToken(session["linkedin-access-token"][0],
                                      session["linkedin-access-token"][1])
    app = linkedin.LinkedInApplication(auth)

    # Get User ID
    response = app.make_request("GET",
                                "https://api.linkedin.com/v2/me",
                                params={"fields": "id"})
    user_id = response.json()['id']
    owner_urn = f"urn:li:person:{user_id}"

    def filter_logic(file):
        filename = secure_filename(file.filename)
        if filename == "":
            return False
        _, extension = os.path.splitext(filename)
        if extension not in keys.LINKEDIN_ALLOWED_EXTENSION:
            return False
        return True

    upload_response_context = []
    for file in request.files.getlist("file"):
        if linkedin_utils.linkedInMediaFilterLogic(
                file, keys.LINKEDIN_ALLOWED_IMAGE_EXTENSION):
            data = file.read()
            upload_response_context.append(
                linkedin_utils.uploadImageToLinkedIn(
                    app,
                    owner_urn=owner_urn,
                    data=data,
                    access_token=auth.token.access_token))

    text = request.form["message"]
    context = {
        "owner": owner_urn,
        "text": {
            "text": text
        },
        "content": {
            "contentEntities": [
                # Iterate through the media contents here
                {
                    "entity": f"{asset_urn}"
                } for (upload_response, asset_urn) in upload_response_context
            ],
            # Add media category here for it to work!
            "shareMediaCategory":
            "IMAGE"
        },
    }

    response = app.make_request("POST",
                                "https://api.linkedin.com/v2/shares",
                                data=json.dumps(context))

    return str(200)
示例#15
0
from linkedin_v2 import linkedin as lin

# from hackzurich.settings import LINKEDIN_ID, LINKEDIN_SECRET
LINKEDIN_ID = '779u3cu8a069wz'
LINKEDIN_SECRET = 'bcDwGS7N3GxcuiYD'

authentication = lin.LinkedInAuthentication(LINKEDIN_ID, LINKEDIN_SECRET,
                                            'http://localhost:8080/code')

print(authentication.authorization_url)
application = lin.LinkedInApplication(authentication)
# print(authentication.get_access_token())
# Print the results with gender, age, and bounding box
#print("Faces in the remote image: ")
#if (len(detect_faces_results_remote.faces) == 0):
#    print("No faces detected.")
#else:
#    for face in detect_faces_results_remote.faces:
#        print("'{}' of age {} at location {}, {}, {}, {}".format(face.gender, face.age, \
#        face.face_rectangle.left, face.face_rectangle.top, \
#        face.face_rectangle.left + face.face_rectangle.width, \
#        face.face_rectangle.top + face.face_rectangle.height))
        
API_KEY = '86mf11anljqsfe'
API_SECRET = 'g0rxpjazY6gsH41v'
RETURN_URL = 'https://api-university.com'

authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Optionally one can send custom "state" value that will be returned from OAuth server
# It can be used to track your user state or something else (it's up to you)
# Be aware that this value is sent to OAuth server AS IS - make sure to encode or hash it
#authorization.state = 'your_encoded_message'
print (authentication.authorization_url)  # open this url on your browser
application = linkedin.LinkedInApplication(authentication)
#bikram's authentication code
authentication.authentication_code = 'AQRiRMpG1XfjaRF4bqC9oncAVknCanLCuov-5gZgfuiNRUUbqlbI3lgP8Se34gWRMRxxiurBD6_HQ-MWdJknW2K0Vv081jwllVpAmEGzVieh-QFFbNqTgwkWxJbzulBsgCboR-54lsJnDo5YZB0zZVn2gGsQeyT1Lh9V01_pqnvERFzCX0QvDVTCisjeVg'
#hitesh's authentication code
#authentication.authentication_code = 'AQQdLTIKgEtdQoQvUBd7n90e5zhLisrLitXfrFOR11dZKEk3RiUj2ctNHgRtWczM3RwMVQLfTMjY7Jk9ROiYA2usl-oTTT3or4c8qKiEinnx2_AYJwgp3mrB-5482N2sPGm5dcUB0GUHCtmdANaPDfk2KDwzH3gcJNBpSE4FlrBlrgwbWtk1E24E5QtoKQ'
#bikram's access token
application = linkedin.LinkedInApplication(token='AQWXUgHMAwl_htHJ_NareR8thl_Z-_1cAOMg65dS9dkpikMnVxgZjiipk8Uuv2w3f0O_5awiGzA_xiq64nSQBwcmPygphqtC4-rTpVJmmnyMKTTTW1micVfnVQ4A6uT0gGrNlbR4DLYDmEgQIbMOVbjjm9tsYjBEMFj3snVTIll6FuAs-s0IW-CITfhsm2-_1VYo0hiBTz2FyZphPcAR2H7kDqeHifvrrfZ-BSpwvZXHCRUMDjx-59v9wEleM7VkOQorBpwpFoUs3WLbEeatKQbQ8kjA80W2vX1nnKzo1uy6Hi6-COoI47v0IbOCCKHT2Iu-bl6BltI0M5N-64EPcjEuj4ndQg')
#print(application)
data = application.get_profile()
#print(data)