def get_authorization_url(): """ LinkedIn oauth authenticate """ try: try: linkedin_client_id = Option.objects.get( parameter="linkedin_client_id").value linkedin_client_secret = Option.objects.get( parameter="linkedin_client_secret").value except: raise Exception("Failed to retrieve the LinkedIn App ID Key.") if settings.DEBUG or settings.TESTING: return linkedin.LinkedInAuthentication( linkedin_client_id, linkedin_client_secret, LinkedInAPI.callback_url_debug, LinkedInAPI.app_permissions).authorization_url else: return linkedin.LinkedInAuthentication( linkedin_client_id, linkedin_client_secret, LinkedInAPI.callback_url, LinkedInAPI.app_permissions).authorization_url except Exception as e: return 'LinkedInAPI.get_authorization_url() - Error: ' + str(e)
def setup_linkedin_application(self, linkedin_client_id, linkedin_client_secret): """ Sets up and returns a new LinkedInApplication that can be used to get data. Ensure that the LinkedIn app dashboard for the given client ID and client secret have the LINKEDIN_RETURN_URL at the top of this file in the 'Authorized Redurect URLs' """ authentication = linkedin.LinkedInAuthentication(linkedin_client_id, linkedin_client_secret, LINKEDIN_RETURN_URL, \ permissions=['r_basicprofile', \ 'r_emailaddress', \ 'rw_company_admin', \ 'w_share']) print( "Open this URL in your browser and give permissions if necessary: " + authentication.authorization_url) # open this url on your browser authentication.authorization_code = input( "After you are redirected, copy the entire URL from your address bar and enter it here: " ).replace(LINKEDIN_RETURN_URL + "?code=", "").split("&state=")[0] print("\n\n Your authorization code is: " + authentication.authorization_code) result = authentication.get_access_token() print("Your new Access Token:", result.access_token) print("Access Token Expires in (seconds):", result.expires_in) return linkedin.LinkedInApplication(authentication)
def linkedin_redirect(): authentication = linkedin.LinkedInAuthentication(APPLICATON_KEY, APPLICATON_SECRET, RETURN_URL, ['r_basicprofile']) print(dir(authentication)) return redirect(authentication.authorization_url, code=302)
def get_connection_values(response, **kwargs): if not response: return None access_token = response['access_token'] auth = linkedin.LinkedInAuthentication(None, None, None, None) auth.token = AccessToken(response['access_token'], response['expires_in']) api = linkedin.LinkedInApplication(auth) profile = api.get_profile(selectors=selectors) profile_url = profile['siteStandardProfileRequest']['url'] image_url = profile['pictureUrl'] return dict( provider_id=config['id'], provider_user_id=profile['id'], access_token=access_token, secret=None, display_name=profile['firstName'], full_name='%s %s' % (profile['firstName'], profile['lastName']), profile_url=profile_url, image_url=image_url, email=profile.get('emailAddress'), )
def linkedin_login(request): RETURN_URL = request.build_absolute_uri("linkedin_login") # url goes back to request # create authentication class: authentication = linkedin.LinkedInAuthentication( API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values()) print(authentication) # now its passed to the app: #application = linkedin.LinkedInApplication(authentication) code = request.GET.get('code') if code: authentication.authorization_code = code authentication.get_access_token() # save in DB doctor = Doctor.create_from_token(authentication) user = User.objects.get(id=doctor.user_id) user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return HttpResponseRedirect("/publish_case") # if I dont have code, ask for another one return HttpResponseRedirect(authentication.authorization_url)
def get_linkedin_authentication(): """ Get the access to the LinkedIn account and links it to the python3-linkedin library :return: the authentication object created by the python3-linkedin library """ print("Start: Authentication process") try: client_id = get_client_id() except FileNotFoundError: print( "linkedin.ini file not found. Please check that the linkedin.ini " "file is placed in the superform/plugins folder.") client_id = None try: client_secret = get_client_secret() except FileNotFoundError: print( "linkedin.ini file not found. Please check that the linkedin.ini " "file is placed in the superform/plugins folder.") client_secret = None return_url = request.url_root + str( url_for('channels.linkedin_return'))[1:] authentication = linkedin.LinkedInAuthentication( client_id, client_secret, return_url, linkedin.PERMISSIONS.enums.values()) return authentication
def redir(): authentication = linkedin.LinkedInAuthentication( API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values()) application = linkedin.LinkedInApplication(authentication) if request.args.get('code', '') != '': authentication.authorization_code = request.args.get('code', '') authentication.get_access_token() profile = application.get_profile(selectors=[ 'id', 'first-name', 'last-name', 'location', 'distance', 'num-connections', 'skills', 'educations', 'interests', 'courses', 'following', 'related-profile-views', 'job-bookmarks', 'certifications' ]) skills = get_skills(profile) courses = get_courses(profile) input_values = list(set(skills + courses)) # print input_values github_input_values = [ 'c', 'c++', 'java', 'data structures', 'algorithms' ] github_input_values = input_values[:10] stack_qn_recommendations = multilabelstack.query(input_values) github_recommendations = git_crawler.query(github_input_values) dump_json(stack_qn_recommendations, "linkedin/stackoverflow_qns.json") dump_json(github_recommendations, "linkedin/git_repos.json") return render_template('redir.html') else: print "No Auth Code\n" return render_template('redir.html')
def linkedin_get_url(return_url='http://www.leapkit.com'): authentication = linkedin.LinkedInAuthentication( __API_KEY, __API_SECRET, return_url, linkedin.PERMISSIONS.enums.values()) print authentication.authorization_url # open this url on your browser return authentication.authorization_url
def sign_in(request): # Get the authorization URL from Linkedin RETURN_URL = "http://localhost:8000/sign_in/" authentication = linkedin.LinkedInAuthentication( API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values()) application = linkedin.LinkedInApplication(authentication) return JsonResponse({'auth_url': authentication.authorization_url})
def linkedin_get_url(return_url=__RETURN_URL): authentication = linkedin.LinkedInAuthentication( __API_KEY, __API_SECRET, return_url, linkedin.PERMISSIONS.enums.values()) #print authentication.authorization_url # open this url on your browser return authentication.authorization_url
def linkedinRedirection(request): print "I was here!!!" authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, perms) code = request.GET.get('code') authentication.authorization_code = code at = authentication.get_access_token() print at application = linkedin.LinkedInApplication(token=at[0]) profile = application.get_profile(selectors=['id', 'first-name', 'siteStandardProfileRequest', 'last-name', 'location', 'distance', 'num-connections', 'skills', 'educations']) print profile # # Step 3. Lookup the user or create them if they don't exist. # #firstname = profile['firstName'] # #lastname = profile['lastName'] # identifier = profile['id'] print request.user page_user = get_object_or_404(User, username=request.user) print page_user #user = get_object_or_404(User, username=request.user) identifier = profile['siteStandardProfileRequest']['url'] print identifier LinkedInProfile.objects.get_or_create(identifier=identifier, user=page_user) page_user.profile.isLinkedinPresent = True page_user.profile.linkedin_url = identifier page_user.save() return render(request, 'core/add_linkedIn.html')
def linkedin_extract(redirect_uri, return_url): #assumes linkedin_url is correct if not empty if redirect_uri == "": print "Error: Invalid redirect_uri. redirect_uri is empty. Exiting" return 0 query = urlparse.urlparse(redirect_uri).query #Parse uri url_dict = urlparse.parse_qs(query) if 'code' not in url_dict: print "Error: Code not found in redirect uri. Exiting" return 0 authentication_code = url_dict['code'] #Get code authentication = linkedin.LinkedInAuthentication( __API_KEY, __API_SECRET, return_url, linkedin.PERMISSIONS.enums.values()) authentication.authorization_code = authentication_code #Set auth_code, lib does not do this smartly.. authentication.get_access_token() #Needed to access linkedin account info. application = linkedin.LinkedInApplication(authentication) #Now get access # Extract user information # Only extract skills: #fields = 'skills' # Full extraction: fields = ("id," + "first-name," + "last-name," + "headline," + "picture-url," + "industry," + "summary," + "specialties," + "positions:(" + "id," + "title," + "summary," + "start-date," + "end-date," + "is-current," + "company:(" + "id," + "name," + "type," + "size," + "industry," + "ticker)" + ")," + "educations:(" + "id," + "school-name," + "field-of-study," + "start-date," + "end-date," + "degree," + "activities," + "notes)," + "associations," + "interests," + "num-recommenders," + "date-of-birth," + "publications:(" + "id," + "title," + "publisher:(name)," + "authors:(id,name)," + "date," + "url," + "summary)," + "patents:(" + "id," + "title," + "summary," + "number," + "status:(id,name)," + "office:(name)," + "inventors:(id,name)," + "date," + "url)," + "languages:(" + "id," + "language:(name)," + "proficiency:(level,name))," + "skills:(" + "id," + "skill:(name))," + "certifications:(" + "id," + "name," + "authority:(name)," + "number," + "start-date," + "end-date)," + "courses:(" + "id," + "name," + "number)," + "recommendations-received:(" + "id," + "recommendation-type," + "recommendation-text," + "recommender)," + "honors-awards," + "three-current-positions," + "three-past-positions," + "volunteer") data = application.get_profile(None, None, fields) try: with open(FILE_NAME, 'w') as outfile: json.dump(data, outfile) except IOError: print 'Error: Cannot open or write to', FILE_NAME return 0 return 1
def get_api(connection, **kwargs): auth = linkedin.LinkedInAuthentication(kwargs.get('consumer_key'), kwargs.get('consumer_secret'), None, linkedin.PERMISSIONS.enums.values()) auth.token = AccessToken(getattr(connection, 'access_token'), getattr(connection, 'expires_in')) api = linkedin.LinkedInApplication(auth) return api
def _get_authentication(): authentication = linkedin.LinkedInAuthentication( CONSUMER_KEY, CONSUMER_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values(), ) return authentication
def linkedin_callback(request): if request.method == "GET": code = request.GET.get("code", None) code = True if code: authentication = linkedin.LinkedInAuthentication( API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values()) #authentication.authorization_code =code #token = authentication.get_access_token() token = "AQUVIvgggNBTubY5GCb06liOZigFlQhRCMGvJvCa7WvenfwewKm-3zVrf0BR0c16hr0kUPcQBmE9_vbarWfyNlUy4fAhrjxeqAnkoKGM30wqV5yX0ZFm0F11jjbAN5YGVGA5qc60w5biQs2fJedZ6GLdXulm4nQN4lTUVUJ6fKzYkq-TcI0" app = linkedin.LinkedInApplication(token=token) alumnies = Alumni.objects.all() if alumnies.count() > 0: for alumni in alumnies.iterator(): first_name = alumni.first_name last_name = alumni.last_name params = { "first-name": first_name, "last-name": last_name, "school-name": "University of Toronto" } profile = app.search_profile(selectors=[{ "people": [ "first-name", "email-address", "last-name", "positions", "educations" ] }], params=params) if profile['people']['_total'] == 0: continue if profile['people']['values'][0]['positions'][ '_total'] == 0: if 'emailAddress' in profile['people']['values'][0]: alumni.email = profile['people']['values'][0][ 'emailAddress'] alumni.save() continue positions = profile['people']['values'][0]['positions'][ 'values'] if len(positions) == 1: alumni.position = positions[0]['title'] alumni.company = positions[0]['company']['name'] else: for i in range(len(positions)): if positions[i]['isCurrent'] == True: alumni.position = positions[0]['title'] alumni.company = positions[0]['company'][ 'name'] if 'emailAddress' in profile['people']['values'][0]: alumni.email = profile['people']['values'][0][ 'emailAddress'] alumni.save() #alumni.company= profile['companies'] return redirect("/")
def __init__(self, get_response): """ Init the middleware with the response and the linkedin authentication object :param get_response: the middleware response """ self.get_response = get_response self.authentication = linkedin.LinkedInAuthentication( LINKEDIN_APPLICATION_KEY, LINKEDIN_APPLICATION_SECRET, LINKEDIN_APPLICATION_RETURN_CALLBACK, ['r_basicprofile'])
def success(name): API_KEY = '81mpzcy471ubsr' API_SECRET = 'p1sGHyX2hM6EKdpb' RETURN_URL = 'http://localhost:5000/success' authentication = linkedin.LinkedInAuthentication( API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values()) print authentication.authorization_url # open this url on your browser application = linkedin.LinkedInApplication(authentication) print application return 'welcome %s' % name
def authenticate_user(): global authentication API_KEY = '75dkp5mywna5gh' API_SECRET = '3KKU269ElBobsGzA' RETURN_URL = 'http://localhost:5000/index' authentication = linkedin.LinkedInAuthentication( API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values()) return redirect(authentication.authorization_url)
def get_provider_user_id(response, **kwargs): if response: auth = linkedin.LinkedInAuthentication(None, None, None, None) auth.token = AccessToken(response['access_token'], response['expires_in']) api = linkedin.LinkedInApplication(auth) profile = api.get_profile(selectors=selectors) return profile['id'] return None
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 auth(): authentication = linkedin.LinkedInAuthentication(APPLICATON_KEY, APPLICATON_SECRET, RETURN_URL, ['r_basicprofile']) auth_code = request.args.get('code', default=None, type=str) authentication.authorization_code = auth_code token = authentication.get_access_token().access_token li_application = linkedin.LinkedInApplication(token=token) print(li_application.get_profile()) return redirect('/user')
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 sign_in(request): # Authenticate using the API key and Secret RETURN_URL = "http://localhost:8000/sign_in/" authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values()) authentication.authorization_code = request.GET.get('code') application = linkedin.LinkedInApplication(authentication) # Get the API access token tok = authentication.get_access_token() application = linkedin.LinkedInApplication(token=tok) # Render the user's profile data as JSON return render(request, 'sign_in.html', {'profile': application.get_profile()})
def get_authorized_tokens(code): try: try: linkedin_client_id = Option.objects.get( parameter="linkedin_client_id").value linkedin_client_secret = Option.objects.get( parameter="linkedin_client_secret").value except: return { 'status': False, 'error': "Failed to retrieve the consumer keys." } if settings.DEBUG or settings.TESTING: api = linkedin.LinkedInAuthentication( linkedin_client_id, linkedin_client_secret, LinkedInAPI.callback_url_debug, LinkedInAPI.app_permissions) else: api = linkedin.LinkedInAuthentication( linkedin_client_id, linkedin_client_secret, LinkedInAPI.callback_url, LinkedInAPI.app_permissions) api.authorization_code = code response = api.get_access_token() return { 'status': True, 'access_token': response.access_token, 'expires_in': response.expires_in } except Exception as e: return { 'status': False, 'error': 'LinkedInAPI.get_authorized_tokens() - Error: ' + str(e) }
def LinkedIn(): API_KEY = #ADD API KEY API_SECRET = #ADD API SECRET RETURN_URL = 'http://localhost:8000' authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values()) print authentication.authorization_url print 'open this url in browser and copy he authorization code' application = linkedin.LinkedInApplication(authentication) auth_code = raw_input("Enter authorization code: ") authentication.authorization_code = auth_code authentication.get_access_token() application.get_profile(selectors=['id', 'first-name', 'last-name', 'location', 'distance', 'num-connections', 'skills', 'educations'])
def linkedin_response(request): API_KEY = "75i4121vcmndhp" API_SECRET = "Zi6dEWMS9GijIyuS" RETURN_URL = "http://9efbc57c.ngrok.io/complete/linkedin-oauth2/" code = request.GET.get('code') authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL) authentication.authorization_code = code token = authentication.get_access_token() application = linkedin.LinkedInApplication(token=token) print 'profile--------------', application.get_profile(selectors=[ 'id', 'first-name', 'last-name', 'location', 'headline', 'distance', 'num-connections', 'skills', 'educations', 'public-profile-url' ]) return render(request, 'login.html')
def linkedin_auth(request): code = request.GET.get('code', None) authentication = linkedin.LinkedInAuthentication( settings.LINKEDIN_API_KEY, settings.LINKEDIN_API_SECRET, '{0}linkedin/auth/'.format(settings.SITE_ROOT_URI), linkedin.PERMISSIONS.enums.values()) if not code: return redirect(authentication.authorization_url) if code: authentication.authorization_code = code token = authentication.get_access_token() return render(request, 'linkedin_auth.html', {'token': token[0]})
def linkedin_auth(request): code = request.GET.get('code', None) authentication = linkedin.LinkedInAuthentication( settings.LINKEDIN_API_KEY, settings.LINKEDIN_API_SECRET, '{0}linkedin/auth/'.format(settings.SITE_ROOT_URI), ['r_basicprofile', 'r_emailaddress'] ) if not code: return redirect(authentication.authorization_url) if code: authentication.authorization_code = code token = authentication.get_access_token() return render(request, 'linkedin_auth.html', {'token': token[0]})
def get_profile(): if 'token'in session: application = linkedin.LinkedInApplication(token=session['token']) profile_json = application.get_profile() f_name = profile_json['firstName'] if profile_json['firstName'] else None l_name = profile_json['lastName'] if profile_json['lastName'] else None headline = profile_json['headline'] if profile_json['headline'] else None url = profile_json['siteStandardProfileRequest']['url'] if profile_json['siteStandardProfileRequest']['url'] else None return render_template('profile.html',first_name=f_name, last_name=l_name, job_role=headline, profile_link=url) else: session['API_KEY']='77in7ezn6gf21x' session['API_SECRET']='rDnTVDUOmvI2ebmj' session['RETURN_URL']='http://localhost:8080/auth' authentication = linkedin.LinkedInAuthentication(session['API_KEY'], session['API_SECRET'], session['RETURN_URL']) auth_url = authentication.authorization_url authenticated = True return render_template('index.html',link=auth_url)
def refresh_token(self, api_key, api_secret, linkedin_email, linkedin_pass): print("Refreshing the token...") RETURN_URL = "https://localhost:8000" authentication = linkedin.LinkedInAuthentication( api_key, api_secret, RETURN_URL, ['w_share']) print("Navigating to authorization url") self.browser.get(authentication.authorization_url) sleep(2) #raw_input("Please allow access manually and press Enter to continue...") print("Logging in") self.perform_login(linkedin_email, linkedin_pass) print("Extracting code") url = self.browser.current_url start = 'code=' end = '&state=' code = url[url.find(start) + len(start):url.find(end)] #print code authentication.authorization_code = code print("Getting the token") return authentication.get_access_token()