def login(request): client = WebApplicationClient(settings.SHEN_RING_CLIENT_ID) if not settings.SHEN_RING_NO_CSRF: csrftoken = request.session.get(csrf.CSRF_SESSION_KEY, "") if csrftoken == "": csrftoken = csrf.get_token(request) request.session[csrf.CSRF_SESSION_KEY] = csrftoken url = client.prepare_request_uri(settings.SHEN_RING_URL + "oauth/authorize/", state=csrftoken, approval_prompt='auto') else: url = client.prepare_request_uri(settings.SHEN_RING_URL + "oauth/authorize/", approval_prompt='auto') return HttpResponseRedirect(url)
def github_login(request): # Setup a Web Application Client from oauthlib client_id = settings.GITHUB_OAUTH_CLIENT_ID client = WebApplicationClient(client_id) # GitHub Authorize URL authorization_url = 'https://github.com/login/oauth/authorize' # Store state info in session request.session['state'] = secrets.token_urlsafe(16) """ Generate a complete authorization url with parameters https://github.com/login/oauth/authorize?response_type=code&client_id=<client_id>&redirect_uri=https://example.com/callback&scope=read%3Auser&state=<state>&allow_signup=false' """ url = client.prepare_request_uri( authorization_url, redirect_uri=settings.GITHUB_OAUTH_CALLBACK_URL, scope=['read:user'], state=request.session['state'], allow_signup='false') print('authorization_url', url) # Redirect to the complete authorization url return HttpResponseRedirect(url)
def test_oauth2(app, user, oauth2_client): client_id, client_secret = oauth2_client client = WebApplicationClient(client_id) host = "https://localhost" state = "randomly_text" with app.test_client() as provider: # login forcefully. with provider.session_transaction() as sess: sess["user_id"] = user sess["_fresh"] = True uri = client.prepare_request_uri(host + "/oauth2/authorize", redirect_uri=redirect_uri, state=state) uri = uri[len(host) :] # step 1: redirect to provider response = provider.get(uri, follow_redirects=True) assert response.status_code == 200 # step 2: redirect to client response = provider.post(uri, data={"scope": "user", "confirm": "yes"}) assert response.location.startswith(redirect_uri) data = client.parse_request_uri_response(response.location, state=state) assert "code" in data # step 3: get the token body = client.prepare_request_body(code=data["code"], redirect_uri=redirect_uri) response = provider.post("/oauth2/token", content_type="application/x-www-form-urlencoded", data=body) assert response.status_code == 200 data = client.parse_request_body_response(response.data) assert "access_token" in data assert data["token_type"] == "Bearer" assert data["scope"] == ["user"] # step 4: using token pass
async def auth(request): csrf_token = request.session['csrf_token'] client = WebApplicationClient(client_id) uri = request.url.replace('http://', 'https://') # TODO: code = client.parse_request_uri_response(uri, state=csrf_token)['code'] request_uri = client.prepare_request_uri(uri=token_uri, client_secret=client_secret, code=code, grant_type='authorization_code', redirect_uri=redirect_uri) async with aiohttp.ClientSession() as session: async with session.post(request_uri) as resp: assert resp.status == 200 access_token = (await resp.json())['access_token'] request.session['access_token'] = access_token async with aiohttp.ClientSession() as session: users_uri = 'https://api.twitch.tv/helix/users' headers = {'Authorization': f'Bearer {access_token}'} async with session.get(users_uri, headers=headers) as resp: assert resp.status == 200 user_login = (await resp.json())['data'][0]['email'] request.session['user_login'] = user_login headers = remember(request, user_login) return HTTPFound(location=request.route_url("home"), headers=headers)
class TestOauthlib(ApprovalTestCase): def setUp(self): super(TestOauthlib, self).setUp() self.libclient = WebApplicationClient(self.oauth_client.id) self.authorization_code.response_type = "code" self.authorization_code.save() def test_flow(self): self.client.login(username="******", password="******") request_uri = self.libclient.prepare_request_uri( "https://localhost" + reverse("oauth2_authorize"), redirect_uri=self.redirect_uri.url, scope=["test", ], state="test_state", ) response = self.client.get(request_uri[17:]) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "doac/authorize.html") approval_url = reverse("oauth2_approval") + "?code=" + self.authorization_code.token response = self.client.post(approval_url, { "code": self.authorization_code.token, "code_state": "test_state", "approve_access": None, }) response_uri = response.get("location", None) if not response_uri: response_uri = response.META["HTTP_LOCATION"] response_uri = response_uri.replace("http://", "https://") data = self.libclient.parse_request_uri_response(response_uri, state="test_state") authorization_token = data["code"] request_body = self.libclient.prepare_request_body( client_secret=self.oauth_client.secret, code=authorization_token, ) post_dict = {} for pair in request_body.split('&'): key, val = pair.split('=') post_dict[key] = val response = self.client.post(reverse("oauth2_token"), post_dict) data = self.libclient.parse_request_body_response(response.content)
class GoogleSignIn(OAuthSignIn): def __init__(self): super(GoogleSignIn, self).__init__('google') self.client = WebApplicationClient(self.consumer_id) @classmethod def get_google_provider_cfg(cls): return requests.get(app.config["GOOGLE_DISCOVERY_URL"]).json() def authorize(self): google_provider_cfg = self.get_google_provider_cfg() authorization_endpoint = google_provider_cfg["authorization_endpoint"] request_uri = self.client.prepare_request_uri( authorization_endpoint, redirect_uri=request.base_url + "/callback", scope=["openid", "email", "profile"], ) return jsonify({'uri': request_uri}) def callback(self): code = request.args.get("code") google_provider_cfg = self.get_google_provider_cfg() token_endpoint = google_provider_cfg["token_endpoint"] token_url, headers, body = self.client.prepare_token_request( token_endpoint, authorization_response=request.url, redirect_url=request.base_url, code=code ) token_response = requests.post( token_url, headers=headers, data=body, auth=( self.consumer_id, self.consumer_secret ), ) self.client.parse_request_body_response( json.dumps(token_response.json()) ) userinfo_endpoint = google_provider_cfg["userinfo_endpoint"] uri, headers, body = self.client.add_token(userinfo_endpoint) userinfo_response = requests.get(uri, headers=headers, data=body) if userinfo_response.json().get("email_verified"): user_email = userinfo_response.json()["email"] else: return jsonify( "User email not available or not verified by Google."), 400 return super().check_for_user_in_database(user_email)
class OAuth2: def __init__( self, *, client_id: str, client_secret: str, authorization_url: str, token_url: str, userinfo_url: str, scope: list ): self.client_id = client_id self.client_secret = client_secret self.authorization_url = authorization_url self.token_url = token_url self.userinfo_url = userinfo_url self.scope = scope # see https://oauthlib.readthedocs.io/en/latest/oauth2/clients/webapplicationclient.html # noqa self.oauth2_client = WebApplicationClient(client_id) def get_redirect_url(self, callback_url: str): # Prepare the authorization code request URI request_uri = self.oauth2_client.prepare_request_uri( self.authorization_url, redirect_uri=callback_url, scope=self.scope ) return request_uri def get_user_info(self, request_url: str, code: str) -> dict: # Get request url without query parameter base_url = urljoin(request_url, urlparse(request_url).path) # Prepare a token creation request. token_url, headers, body = self.oauth2_client.prepare_token_request( self.token_url, authorization_response=request_url, redirect_url=base_url, code=code ) token_response = requests.post( token_url, headers=headers, data=body, auth=(self.client_id, self.client_secret) ) # Parse the JSON response body. self.oauth2_client.parse_request_body_response( json.dumps(token_response.json()) ) # Add token to the request uri, body or authorization header. uri, headers, body = self.oauth2_client.add_token( self.userinfo_url ) userinfo_response = requests.get(uri, headers=headers, data=body) return userinfo_response.json()
def unauthorised(): state = ''.join(random.choices(string.ascii_lowercase, k=16)) auth_client = WebApplicationClient(OAUTH_ID) auth_uri = auth_client.prepare_request_uri( 'https://github.com/login/oauth/authorize', state=state ) return redirect(auth_uri)
def test_auth_grant_uri(self): client = WebApplicationClient(self.client_id) # Basic, no extra arguments uri = client.prepare_request_uri(self.uri) self.assertURLEqual(uri, self.uri_id) # With redirection uri uri = client.prepare_request_uri(self.uri, redirect_uri=self.redirect_uri) self.assertURLEqual(uri, self.uri_redirect) # With scope uri = client.prepare_request_uri(self.uri, scope=self.scope) self.assertURLEqual(uri, self.uri_scope) # With state uri = client.prepare_request_uri(self.uri, state=self.state) self.assertURLEqual(uri, self.uri_state) # with code_challenge and code_challenge_method uri = client.prepare_request_uri(self.uri, code_challenge=self.code_challenge, code_challenge_method=self.code_challenge_method) self.assertURLEqual(uri, self.uri_code_challenge) # with no code_challenge_method uri = client.prepare_request_uri(self.uri, code_challenge=self.code_challenge) self.assertURLEqual(uri, self.uri_code_challenge_method) # With extra parameters through kwargs uri = client.prepare_request_uri(self.uri, **self.kwargs) self.assertURLEqual(uri, self.uri_kwargs)
class Authentication: def __init__(self, req): self.authorization_endpoint = "https://accounts.google.com/o/oauth2/v2/auth" self.token_endpoint = "https://www.googleapis.com/oauth2/v4/token" self.url = req.url self.base_url = req.base_url self.full_path = req.full_path self.redirect_url = f'{req.url}/callback' self.args = req.args self.client_id = os.getenv('GOOGLE_CLIENT_ID') self.client_secret = os.getenv('GOOGLE_CLIENT_SECRET') self.client = WebApplicationClient(os.getenv('GOOGLE_CLIENT_ID')) self.scopes = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets" ] self.tokens_json = {} def google_login(self): state = hashlib.sha256(os.urandom(1024)).hexdigest() request_uri = self.client.prepare_request_uri( self.authorization_endpoint, redirect_uri=self.redirect_url, state=state, scope=self.scopes) return {'request_uri': request_uri, 'state': state} def google_login_callback(self): code = self.args.get('code') token_url, headers, body = self.client.prepare_token_request( self.token_endpoint, code=code, authorization_response=self.url, redirect_url=self.base_url) ## TODO handle error unauthorized! token_response = requests.post(token_url, headers=headers, data=body, auth=(self.client_id, self.client_secret)) self.tokens_json = token_response.json() user_data = jwt.decode(self.tokens_json['id_token'], verify=False) return { 'user_data': user_data, 'jwt': self.tokens_json['id_token'], 'access_token': self.tokens_json['access_token'] } def get_access_token(self): return self.tokens_json
def google_login(): client = WebApplicationClient(GOOGLE_CLIENT_ID) google_provider_cfg = get_google_provider_cfg() authorization_endpoint = google_provider_cfg["authorization_endpoint"] request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=force_https(request.base_url) + "/callback", scope=["openid", "email", "profile"], ) return redirect(request_uri)
async def login(request): config = request.app['config'] redirect_uri = f'{config.server_url}/login/complete' client = WebApplicationClient(config.auth.client_id) state = generate_token() dest = client.prepare_request_uri( f'{config.auth.url}/oauth/authorize', state=state, scope='openid', redirect_uri=redirect_uri) response = web.Response(status=302, headers={hdrs.LOCATION: dest}) response.set_cookie('oauth2-state', state, httponly=True) return response
async def login(request): # TODO: add check of user is logged in already csrf_token = secrets.token_hex(16) request.session['csrf_token'] = csrf_token client = WebApplicationClient(client_id) request_uri = client.prepare_request_uri( uri=authorize_uri, redirect_uri=redirect_uri, scope=['user:read:email', 'channel_subscriptions'], state=csrf_token, ) return HTTPFound(location=request_uri)
def authorize(self): scope = [ 'https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner' ] client = WebApplicationClient(self.registry['google_oauth_id']) self.req.response.redirect(client.prepare_request_uri( 'https://accounts.google.com/o/oauth2/auth', scope=scope, redirect_uri='%s/authorize-google' % self.site.absolute_url(), approval_prompt='force', access_type='offline', include_granted_scopes='true'))
def signin(): logger.debug("signin()") client = WebApplicationClient(oauth_credential["client_id"]) authorization_endpoint = requests.get( GOOGLE_DISCOVERY_URL).json()["authorization_endpoint"] request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=request.base_url + "/callback", scope=["openid", "email", "profile"], ) logger.debug(request_uri) return redirect(request_uri)
class GoogleAuth(object): AUTHORIZATION_ENDPOINT_URL = "https://accounts.google.com/o/oauth2/v2/auth" TOKEN_ENDPOINT_URL = "https://oauth2.googleapis.com/token" USERINFO_ENDPOINT_URL = "https://openidconnect.googleapis.com/v1/userinfo" def __init__(self, client_id, client_secret): self.CLIENT_ID = client_id self.CLIENT_SECRET = client_secret self.client = WebApplicationClient(self.CLIENT_ID) def get_requests_uri(self, redirect_uri, scope): request_uri = self.client.prepare_request_uri( self.AUTHORIZATION_ENDPOINT_URL, redirect_uri=redirect_uri, scope=scope, state=str(time.time())) return request_uri def get_user_info(self, code, redirect_url): token_url, headers, body = self.client.prepare_token_request( self.TOKEN_ENDPOINT_URL, client_secret=self.CLIENT_SECRET, client_id=self.CLIENT_ID, redirect_url=redirect_url, code=code) token_response = requests.post( token_url, headers=headers, data=body, auth=(self.CLIENT_ID, self.CLIENT_SECRET), ) self.client.parse_request_body_response( json.dumps(token_response.json())) uri, headers, body = self.client.add_token(self.USERINFO_ENDPOINT_URL) userinfo_response = requests.get(uri, headers=headers) if userinfo_response.json().get("email_verified"): _id = userinfo_response.json()["sub"] email = userinfo_response.json()["email"] name = userinfo_response.json()["given_name"] return {"id": _id, "email": email, "name": name} else: return {}
class GoogleAuthenication: def __init__(self): self.client = WebApplicationClient(app_config.GOOGLE_CLIENT_ID) if os.path.exists(app_config.GOOGLE_CACHE_FILE): with open(app_config.GOOGLE_CACHE_FILE, 'rb') as token: self.creds = pickle.load(token) self.google_provider_cfg = requests.get( app_config.GOOGLE_DISCOVERY_URL).json() def endpoint(self): authorization_endpoint = self.google_provider_cfg[ "authorization_endpoint"] request_uri = self.client.prepare_request_uri( authorization_endpoint, redirect_uri=url_for("google_authorized", _external=True), access_type='offline', scope=app_config.GOOGLE_SCOPE) return request_uri def create_token(self, request: Request): code = request.args.get("code") client_config = ClientConfigBuilder( client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=app_config.GOOGLE_CLIENT_ID, client_secret=app_config.GOOGLE_CLIENT_SECRET, auth_uri=self.google_provider_cfg["authorization_endpoint"], token_uri=self.google_provider_cfg["token_endpoint"]) flow = Flow.from_client_config(client_config=client_config.Build(), scopes=app_config.GOOGLE_SCOPE, redirect_uri=request.base_url) flow.fetch_token(code=code) self.creds = flow.credentials with open(app_config.GOOGLE_CACHE_FILE, 'wb') as token: pickle.dump(self.creds, token) return def get_creds(self): if self.creds and self.creds.expired and self.creds.refresh_token: self.creds.refresh(Request()) return self.creds
def generate_google_auth_request(): # Find out what URL to hit for Google login google_provider_cfg = get_google_provider_cfg() authorization_endpoint = google_provider_cfg['authorization_endpoint'] # Use library to construct the request for Google login and provide scopes client = WebApplicationClient(current_app.config['GOOGLE_CLIENT_ID']) callback_uri = current_app.config.get('GOOGLE_CLIENT_CALLBACK') request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=callback_uri, scope=['openid', 'email', 'profile'], ) return request_uri
def login(client: WebApplicationClient): # Find out what URL to hit for Google login google_provider_cfg = get_google_provider_cfg() authorization_endpoint = google_provider_cfg["authorization_endpoint"] # Use library to construct the request for Google login and provide # scopes that let you retrieve user's profile from Google request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=request.base_url + "/callback", scope=["openid", "email", "profile"], ) return request_uri
def test_auth_grant_uri(self): client = WebApplicationClient(self.client_id) # Basic, no extra arguments uri = client.prepare_request_uri(self.uri) self.assertURLEqual(uri, self.uri_id) # With redirection uri uri = client.prepare_request_uri(self.uri, redirect_uri=self.redirect_uri) self.assertURLEqual(uri, self.uri_redirect) # With scope uri = client.prepare_request_uri(self.uri, scope=self.scope) self.assertURLEqual(uri, self.uri_scope) # With state uri = client.prepare_request_uri(self.uri, state=self.state) self.assertURLEqual(uri, self.uri_state) # With extra parameters through kwargs uri = client.prepare_request_uri(self.uri, **self.kwargs) self.assertURLEqual(uri, self.uri_kwargs)
def login(): """This initiates the google log in process.""" url = request.base_url if url[4] != "s": url = "https" + url[4:] client = WebApplicationClient(current_app.config['GOOGLE_CLIENT_ID']) google_provider_cfg = get_google_provider_cfg() authorization_endpoint = google_provider_cfg["authorization_endpoint"] request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=url + "/callback", scope=["openid", "email", "profile"], prompt='consent') return redirect(request_uri)
def authorization(): """User Authorization. Redirect the user/resource owner to our OAuth provider While supplying key OAuth parameters. """ # Here we're using `WebApplicationClient` to utilize authorization code grant client = WebApplicationClient(client_id=CLIENT_ID) request_uri = client.prepare_request_uri(AUTH_URL, redirect_uri=REDIRECT_URI, scope=scope, state=state) # State is used to prevent CSRF, we'll keep it to reuse it later. session["oauth_state"] = state return redirect(request_uri)
def login_with_google(): client = WebApplicationClient(app.config.get('GOOGLE_CLIENT_ID')) google_provider_cfg = requests.get(app.config.get('GOOGLE_DISCOVERY_URL')).json() authorization_endpoint = google_provider_cfg["authorization_endpoint"] # Use library to construct the request for Google login and provide # scopes that let you retrieve user's profile from Google request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=url_for('login_with_google_callback', _external=True), scope=["profile"], ) return redirect(request_uri)
def get_grant_request_url(cls, client_id, redirect_uri, scope=None, state=None): oauth_client = WebApplicationClient(client_id) request_uri = oauth_client.prepare_request_uri( cls.authorization_endpoint, redirect_uri=redirect_uri, scope=scope, state=json.dumps(state) if state else None, ) return request_uri
def login(): #form = LoginForm() # if form.validate_on_submit(): google_provider_cfg = get_google_provider_cfg() authorization_endpoint = google_provider_cfg["authorization_endpoint"] client = WebApplicationClient(GOOGLE_CLIENT_ID) request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=request.base_url + "/callback", scope=["openid", "email", "profile"], ) return redirect(request_uri)
def authorize(self): scope = [ 'https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner' ] client = WebApplicationClient(self.registry['google_oauth_id']) self.req.response.redirect( client.prepare_request_uri( 'https://accounts.google.com/o/oauth2/auth', scope=scope, redirect_uri='%s/authorize-google' % self.site.absolute_url(), approval_prompt='force', access_type='offline', include_granted_scopes='true'))
def login(): """Google Login view.""" client = WebApplicationClient(current_app.config["GOOGLE_CLIENT_ID"]) # Find out what URL to hit for Google login google_provider_cfg = get_google_provider_cfg() authorization_endpoint = google_provider_cfg["authorization_endpoint"] # Use library to construct the request for Google login and provide # scopes that let you retrieve user's profile from Google request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=request.base_url + "/callback", scope=["openid", "email", "profile"], ) return redirect(request_uri)
def login(): global client DISCO_URL = current_app.config['GOOGLE_DISCOVERY_URL'] CLIENT = current_app.config['GOOGLE_CLIENT_ID'] client = WebApplicationClient(CLIENT) google_provider_cfg = requests.get(DISCO_URL).json() authorization_endpoint = google_provider_cfg["authorization_endpoint"] request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=request.base_url + "/callback", scope=["openid", "email", "profile"], ) return redirect(request_uri)
def api_auth_redirect(self): s = self._settings authorization_endpoint = s.get(['authorization_endpoint']) client_id = s.get(['client_id']) callback_base_url = s.get(['callback_base_url']) client = WebApplicationClient(client_id) request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=callback_base_url + "/plugin/oauth2_pgc/callback", scope=["email", "read:org"], ) return flask.redirect(request_uri)
def stripe_authorize(request, forening_id): # In order to keep the current forening_id in the callback URL, we'll have # to save it in the session request.session['admin.foreninger.stripe-connect.active-forening'] = forening_id forening = Forening.objects.get(id=forening_id) # Only admin are allowed to connect a Stripe account if not request.user.is_admin_in_forening(forening): raise PermissionDenied # Prepare Stripe OAuth 2.0 request URI using our oauth client library client = WebApplicationClient(settings.STRIPE_TOKEN['client_id']) params = { 'scope': 'read_write', 'stripe_landing': 'register', 'redirect_uri': 'https://%s%s' % ( request.site.domain, reverse('admin:foreninger.stripe_callback')), 'stripe_user[url]': forening.get_active_url(), 'stripe_user[phone_number]': forening.phone, 'stripe_user[business_name]': forening.name, 'stripe_user[business_type]': 'non_profit', 'stripe_user[physical_product]': 'false', 'stripe_user[product_category]': 'tourism_and_travel', 'stripe_user[product_description]': 'Trekking, lodging, outdoor activities', 'stripe_user[currency]': 'nok', 'stripe_user[country]': 'NO', 'stripe_user[street_address]': forening.post_address, 'stripe_user[zip]': forening.zipcode.zipcode if forening.zipcode is not None else '', 'stripe_user[city]': forening.zipcode.area if forening.zipcode is not None else '', 'stripe_user[email]': request.user.get_sherpa_email(), 'stripe_user[first_name]': request.user.get_first_name(), 'stripe_user[last_name]': request.user.get_last_name(), 'stripe_user[dob_day]': request.user.get_birth_date().day, 'stripe_user[dob_month]': request.user.get_birth_date().month, 'stripe_user[dob_year]': request.user.get_birth_date().year, } stripe_request_uri = client.prepare_request_uri( settings.STRIPE['endpoints']['authorize'], **params) return redirect(stripe_request_uri)
class FacebookAuth(object): AUTHORIZATION_ENDPOINT_URL = "https://www.facebook.com/v4.0/dialog/oauth" TOKEN_ENDPOINT_URL = "https://graph.facebook.com/v4.0/oauth/access_token" USERINFO_ENDPOINT_URL = "https://graph.facebook.com/me" def __init__(self, client_id, client_secret): self.CLIENT_ID = client_id self.CLIENT_SECRET = client_secret self.client = WebApplicationClient(self.CLIENT_ID) def get_requests_uri(self, redirect_uri, scope): request_uri = self.client.prepare_request_uri( self.AUTHORIZATION_ENDPOINT_URL, redirect_uri=redirect_uri, scope=scope, state=str(time.time())) return request_uri def get_user_info(self, code, redirect_url): token_url, headers, body = self.client.prepare_token_request( self.TOKEN_ENDPOINT_URL, client_secret=self.CLIENT_SECRET, client_id=self.CLIENT_ID, redirect_url=redirect_url, code=code) token_response = requests.post( token_url, headers=headers, data=body, auth=(self.CLIENT_ID, self.CLIENT_SECRET), ) self.client.parse_request_body_response( json.dumps(token_response.json())) uri, headers, body = self.client.add_token(self.USERINFO_ENDPOINT_URL) params = {"fields": "email,name"} userinfo_response = requests.get(uri, headers=headers, params=params) return userinfo_response.json()
class FacebookSignIn(OAuthSignIn): def __init__(self): super(FacebookSignIn, self).__init__('facebook') self.client = WebApplicationClient(self.consumer_id) self.authorize_url = app.config["FACEBOOK_AUTHORIZE_URL"] self.access_token_url = app.config["FACEBOOK_ACCESS_TOKEN_URL"] self.user_info_url = app.config["FACEBOOK_USER_INFO_URL"] def authorize(self): request_uri = self.client.prepare_request_uri( self.authorize_url, redirect_uri=request.base_url + "/callback", scope=["email"], ) return jsonify({'uri': request_uri}) def callback(self): code = request.args.get("code") token_url, headers, body = self.client.prepare_token_request( self.access_token_url, authorization_response=request.url, redirect_url=request.base_url, code=code ) token_response = requests.post( token_url, headers=headers, data=body, auth=( self.consumer_id, self.consumer_secret ), ) self.client.parse_request_body_response( json.dumps(token_response.json()) ) uri, headers, body = self.client.add_token(self.user_info_url) userinfo_response = requests.get(uri, headers=headers, data=body) user_email = userinfo_response.json()["email"] return super().check_for_user_in_database(user_email)
def get_request_uri(app, request): # OAuth2 client setup client = WebApplicationClient(app.config["GOOGLE_CLIENT_ID"]) # Find out what URL to hit for Google login google_provider_cfg = get_google_provider_cfg(app) authorization_endpoint = google_provider_cfg["authorization_endpoint"] # Use library to construct the request for login and provide # scopes that let you retrieve user's profile from Google request_uri = client.prepare_request_uri( authorization_endpoint, redirect_uri=request.host_url.rstrip("/") + url_for("auth.google_callback"), scope=["openid", "email", "profile"], ) return request_uri
async def get_session(client_id: str, client_secret: str) -> AuthToken: """ Use the Authorization Code Grant flow to get a token. This opens a browser tab. """ refresh_token_file = os.path.join(config.config_dir(), '.refresh.token') base_url = 'https://bitbucket.org/site/oauth2' # If we have a refresh token, use that existing_token = None if os.path.isfile(refresh_token_file): with open(refresh_token_file) as f: existing_token = json.load(f) now = arrow.utcnow() if existing_token and arrow.get(existing_token['expires_at']) - now > timedelta(minutes=5): log.info('Found existing token') return existing_token # Otherwise, send the user to the browser flow redirect_uri = 'https://localhost:8888' client = WebApplicationClient(client_id) auth_url = client.prepare_request_uri(f'{base_url}/authorize', redirect_uri=redirect_uri) print(f'Please go to the following link, then copy the redirected URL back here.\n\n\t{auth_url}\n') code = client.parse_request_uri_response(input('URL: '))['code'] token_reqest_params = parse_qs(client.prepare_request_body(code=code, redirect_uri=redirect_uri)) async with aiohttp.ClientSession() as session: resp = await session.post( f'{base_url}/access_token', headers={'Authorization': aiohttp.BasicAuth(client_id, client_secret).encode()}, data=token_reqest_params ) if resp.status != 200: log.error(await resp.text()) raise Exception('Could not authenticate with the Bitbucket API') token: AuthToken = await resp.json() token['expires_at'] = now.shift(seconds=token['expires_in']).format(arrow.FORMAT_RFC3339) with open(refresh_token_file, 'w') as f: json.dump(token, f) return token
def login_view(request): client = WebApplicationClient(VK_APP_ID) vk_uri = client.prepare_request_uri('https://oauth.vk.com/authorize', scope=['notify'], redirect_uri='http://localhost/vk_register', v='5.17') context = {'vk_uri': vk_uri} ''' На FaceBook времени не хватило вообщем client = WebApplicationClient(FACEBOOK_APP_ID) fb_uri = client.prepare_request_uri('https://www.facebook.com/dialog/oauth', redirect_uri='http://localhost/fb_register') ''' context = {'vk_uri': vk_uri, 'fb_uri': '#'} return render(request, 'tvevt/login.html', context)
def index(request): client = WebApplicationClient(settings.GITHUB_CLIENT_ID) if not request.GET.has_key('code'): # todo - also setup hook for repo # todo - check http referrer = 'https://github.com/' uri = client.prepare_request_uri(AUTHORIZATION_URL, redirect_uri=request.build_absolute_uri(reverse('index')), scope=['repo']) context = {'uri': uri} else: code = request.GET['code'] body = client.prepare_request_body(code=code, client_secret=settings.GITHUB_CLIENT_SECRET) headers = {'Accept': 'application/json'} response = requests.post(REQUEST_TOKEN_URL, body, headers=headers) response = response.json() owner = Github(response['access_token']).get_user() # todo - check if user already exists => show repo settings token = GithubToken(owner=owner.login, access_token=response['access_token'], scope=response['scope']) token.save() context = {'owner': owner.name} return render(request, 'benchmarks/index.html', context)
def vk_register(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('user_detail')) code = request.GET.get('code', '') if code == '': raise ValueError(u"Bad response") #return render(request, 'tvevt/fail.html', context) client = WebApplicationClient(VK_APP_ID) uri = client.prepare_request_uri('https://oauth.vk.com/access_token', client_secret=VK_APP_SECRET, code=code, redirect_uri='http://localhost/vk_register') h = HTTPSConnection("vk.com") h.request('GET', uri) r = h.getresponse() body = r.read() r = json.loads(body) user_id = r["user_id"] access_token = r["access_token"] uri = client.prepare_request_uri('https://api.vk.com/method/users.get', user_id=user_id, access_token=access_token, fields='sex,bdate') h.request('GET', uri) r = h.getresponse() body = r.read() r = json.loads(body) user = r["response"][0] if user["uid"] <=0: raise ValueError(u"Bad uid value") list = User.objects.filter(vk_user_id=user["uid"]) if len(list) == 1: u = list[0] login(request, u) return HttpResponseRedirect(reverse('user_detail')) else: "Если пользователя нет, то регистрируем его" username = "******" % user["uid"] l = user["bdate"].split('.') year = int(l[2]) month = int(l[1]) day = int(l[0]) user["bdate"] = date(year, month, day) if user["sex"] == 2: user["sex"] = "male" elif user["sex"] == 1: user["sex"] = "female" else: user["sex"] == '' u = User(username=username, vk_user_id=user["uid"], first_name=user["first_name"], last_name=user["last_name"], gender=user["sex"], birth_date=user["bdate"]) u.save() login(request, u) return render(request, 'tvevt/success.html')