Exemplo n.º 1
0
def get_google_user_info(req: Request):
    client = WebApplicationClient(current_app.config['GOOGLE_CLIENT_ID'])
    code = req.args.get('code')
    callback_uri = current_app.config.get('GOOGLE_CLIENT_CALLBACK')
    # Find out what URL to hit to get tokens that allow you to ask for things on behalf of a user
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg['token_endpoint']
    userinfo_endpoint = google_provider_cfg['userinfo_endpoint']
    # Prepare and send a req to get tokens

    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=translate_url_https(req.url),
        redirect_url=callback_uri,
        code=code
    )
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(current_app.config.get('GOOGLE_CLIENT_ID'), current_app.config.get('GOOGLE_CLIENT_SECRET')),
    )
    client.parse_request_body_response(json.dumps(token_response.json()))
    # let's find and hit the URL from Google that gives you the user's profile information
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo = requests.get(uri, headers=headers, data=body).json()
    return userinfo
Exemplo n.º 2
0
    def get_userinfo(cls, client_id, client_secret, code,
                     authorization_response):
        client = WebApplicationClient(client_id)

        base_url = authorization_response.replace(
            '?' + urlparse(authorization_response).query, '')

        # get access token
        token_url, headers, body = client.prepare_token_request(
            cls.token_endpoint,
            authorization_response=authorization_response,
            redirect_url=base_url,
            code=code,
        )
        token_response = requests.post(
            token_url,
            headers=headers,
            data=body,
            auth=(client_id, client_secret),
        )
        client.parse_request_body_response(token_response.text)

        # get user information
        uri, headers, body = client.add_token(cls.userinfo_endpoint)
        userinfo_response = requests.get(uri, headers=headers, data=body)
        data = userinfo_response.json()

        return data
Exemplo n.º 3
0
    def test_parse_token_response(self):
        client = WebApplicationClient(self.client_id)

        # Parse code and state
        response = client.parse_request_body_response(self.token_json, scope=self.scope)
        self.assertEqual(response, self.token)
        self.assertEqual(client.access_token, response.get("access_token"))
        self.assertEqual(client.refresh_token, response.get("refresh_token"))
        self.assertEqual(client.token_type, response.get("token_type"))

        # Mismatching state
        self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid")
        os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
        token = client.parse_request_body_response(self.token_json, scope="invalid")
        self.assertTrue(token.scope_changed)

        scope_changes_recorded = []
        def record_scope_change(sender, message, old, new):
            scope_changes_recorded.append((message, old, new))

        signals.scope_changed.connect(record_scope_change)
        try:
            client.parse_request_body_response(self.token_json, scope="invalid")
            self.assertEqual(len(scope_changes_recorded), 1)
            message, old, new = scope_changes_recorded[0]
            self.assertEqual(message, 'Scope has changed from "invalid" to "/profile".')
            self.assertEqual(old, ['invalid'])
            self.assertEqual(new, ['/profile'])
        finally:
            signals.scope_changed.disconnect(record_scope_change)
        del os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE']
Exemplo n.º 4
0
def callback():
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]
    code = request.args.get("code")
    client = WebApplicationClient(GOOGLE_CLIENT_ID)

    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=force_https(request.url),
        redirect_url=force_https(request.base_url),
        code=code
    )

    token_response = requests.post(
        force_https(token_url),
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    client.parse_request_body_response(json.dumps(token_response.json()))

    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    logging.info('Logging user')
    login_user(User(userinfo_response.json()["email"]))

    return redirect(url_for('main'))
Exemplo n.º 5
0
    def callback():
        logger.debug("callback()")
        code = request.args.get("code")
        client = WebApplicationClient(oauth_credential["client_id"])

        token_endpoint = requests.get(
            GOOGLE_DISCOVERY_URL).json()["token_endpoint"]
        token_url, headers, body = 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=(oauth_credential["client_id"],
                  oauth_credential["client_secret"]))
        client.parse_request_body_response(json.dumps(token_response.json()))
        userinfo_endpoint = requests.get(
            GOOGLE_DISCOVERY_URL).json()["userinfo_endpoint"]
        uri, headers, body = client.add_token(userinfo_endpoint)
        uri = uri.replace("http:", "https:")

        userinfo_response = requests.get(uri, headers=headers,
                                         data=body).json()
        member = remote_db.get("member",
                               userinfo_response["email"].split('@')[0])

        login_user(member, remember=True)
        return redirect(url_for("index"))
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)
Exemplo n.º 7
0
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()
Exemplo n.º 8
0
def callback(client: WebApplicationClient):
    # Get authorization code Google sent back to you
    code = request.args.get("code")

    # Find out what URL to hit to get tokens that allow you to ask for
    # things on behalf of a user
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    # Prepare and send a request to get tokens! Yay tokens!
    token_url, headers, body = 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=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    # Parse the tokens!
    client.parse_request_body_response(json.dumps(token_response.json()))

    # Now that you have tokens (yay) let's find and hit the URL
    # from Google that gives you the user's profile information,
    # including their Google profile image and email
    user_info_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(user_info_endpoint)
    user_info_response = requests.get(uri, headers=headers, data=body)

    # You want to make sure their email is verified.
    # The user authenticated with Google, authorized your
    # app, and now you've verified their email through Google!
    if user_info_response.json().get("email_verified"):
        unique_id = user_info_response.json()["sub"]
        users_email = user_info_response.json()["email"]
        picture = user_info_response.json()["picture"]
        users_name = user_info_response.json()["name"]
    else:
        return "User email not available or not verified by Google.", 400

    # Create a user in your db with the information provided by Google
    user = user_dao.get_user_by_google_id(unique_id)
    if user is None:
        user = User(unique_id, users_name, users_email, picture, "")
        user_dao.save_user(user)
        # TODO send request about birthday
    else:
        if user.profile_pic != picture:
            user.profile_pic = picture
            user_dao.update_picture(user.id, picture)

    # Begin user session by logging the user in
    login_user(user)
Exemplo n.º 9
0
 def _get_access_token(self, client_id, client_secret, refresh_token):
     oauth = WebApplicationClient(client_id, refresh_token=refresh_token)
     url, headers, body = oauth.prepare_refresh_token_request(
         f"{self.api_base}/oauth2/token",
         client_id=client_id,
         client_secret=client_secret)
     req = urllib.request.Request(url, body.encode(), headers=headers)
     with urllib.request.urlopen(req) as res:
         oauth.parse_request_body_response(res.read())
     return oauth.access_token
Exemplo n.º 10
0
def callback():
    """
    
    This deals with the Google API token for user 
    authentification.
    """

    client = WebApplicationClient(current_app.config['GOOGLE_CLIENT_ID'])
    code = request.args.get("code")
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]
    print(request.base_url)
    print(code)
    print(request.url)
    if request.url[4] == 's':
        url = "https" + request.url[5:]
        print(url)
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=url,
        redirect_url=request.base_url,
        code=code)
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(current_app.config['GOOGLE_CLIENT_ID'],
              current_app.config['GOOGLE_CLIENT_SECRET']),
    )
    client.parse_request_body_response(json.dumps(token_response.json()))
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)
    if userinfo_response.json().get("email_verified"):
        unique_id = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
        users_name = userinfo_response.json()["given_name"]
        if User.query.filter_by(email=users_email).first():
            user = User.query.filter_by(email=users_email).first()
            if user is None or not user.check_password(unique_id):
                return redirect(url_for('shop.index'))
            login_user(user, remember=False)
            next_page = request.args.get('next')
            if not next_page or url_parse(next_page).netloc != '':
                next_page = url_for('shop.index')
            return redirect(next_page)
        else:
            user = User(username=users_name, email=users_email)
            user.set_password(unique_id)
            db.session.add(user)
            db.session.commit()
    else:
        return _("User email not available or not verified by Google."), 400
    return redirect(url_for("shop.index"))
Exemplo n.º 11
0
def google_callback():
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]
    oauth = WebApplicationClient(settings.GOOGLE_CLIENT_ID)
    if request.args.get("error"):
        flash('Error! ' + request.args.get("error"), 'alert-warning')
        return redirect(url_for('main'))

    state = request.args.get("state")
    if state != session.get("state"):
        flash('Error! state not match.', 'alert-warning')
        return redirect(url_for('main'))

    session.pop('state', None)
    url, headers, body = oauth.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        state='',
        body='',
        client_secret=settings.GOOGLE_CLIENT_SECRET)

    token_response = requests.post(
        url,
        headers=headers,
        data=body,
        auth=(settings.GOOGLE_CLIENT_ID, settings.GOOGLE_CLIENT_SECRET),
    )

    oauth.parse_request_body_response(json.dumps(token_response.json()))
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = oauth.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    if userinfo_response.status_code != 200:
        flash('Error! ' + userinfo_response.json(), 'alert-warning')
        return redirect(url_for('main'))

    unique_id = userinfo_response.json()["sub"]
    users_name = userinfo_response.json()["name"]
    picture = userinfo_response.json()["picture"]
    user = User(id_=unique_id, name=users_name, profile_pic=picture)
    if not User.get(unique_id):
        User.create(unique_id, users_name, picture)
        login_user(user)
        session["newregister"] = 1
        flash('You have been successfully created an account.',
              'alert-success')
        return redirect(url_for('pushtime'))

    login_user(user)
    return redirect(url_for('channellist'))
Exemplo n.º 12
0
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 {}
Exemplo n.º 13
0
 def callback():
     client = WebApplicationClient(app.config.get("CLIENT_ID"))
     token = client.prepare_token_request(
         "https://github.com/login/oauth/access_token",
         code=request.args.get("code"))
     access = requests.post(token[0],
                            headers=token[1],
                            data=token[2],
                            auth=(app.config.get("CLIENT_ID"),
                                  app.config.get("CLIENT_SECRET")))
     client.parse_request_body_response(access.text)
     params = client.add_token("https://api.github.com/user")
     github_user = requests.get(params[0], headers=params[1]).json()
     login_user(User(github_user['id']))
     return index()
Exemplo n.º 14
0
def auth_callback():
    global authorization_requests
    global tokens
    print(request.args)
    print(authorization_requests)

    state = request.args.get('state')
    authorization_request = authorization_requests.pop(state)

    oauth = WebApplicationClient(os.environ.get("AUTH0_CLIENT_ID"))
    url, headers, body = oauth.prepare_token_request(
        f'https://{os.environ.get("AUTH0_DOMAIN")}/oauth/token',
        authorization_response=request.url,
        state=authorization_request.get('state'),
        code_verifier=authorization_request.get('code_verifier'),
        redirect_url=os.environ.get("AUTH0_REDIRECT_URL"))

    print(url)
    print(headers)
    print(body)

    req = urllib.request.Request(url, body.encode(), headers=headers)
    with urllib.request.urlopen(req) as res:
        response = oauth.parse_request_body_response(res.read())
        token = jwt.decode(response.get('access_token'), verify=False)
        tokens[token.get('sub')] = token

    return 'OK'
Exemplo n.º 15
0
def callback():
    """Retrieving an access token.
    After you've redirected from our provider to your callback URL,
    you'll have access to the auth code in the redirect URL, which
    we'll be using to get an access token.
    """

    client = WebApplicationClient(client_id=CLIENT_ID)
    # Parse the response URI after the callback, with the same state we initially sent
    client.parse_request_uri_response(request.url,
                                      state=session["oauth_state"])
    # Now we've access to the auth code
    code = client.code

    # Prepare request body to get the access token
    body = client.prepare_request_body(
        code=code,
        redirect_uri=REDIRECT_URI,
        include_client_id=False,
        scope=scope,
    )

    # Basic HTTP auth by providing your client credentials
    auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)

    # Making a post request to the TOKEN_URL endpoint
    r = requests.post(TOKEN_URL, data=dict(urldecode(body)), auth=auth)

    # Parse the response to get the token and store it in session
    token = client.parse_request_body_response(r.text, scope=scope)
    session["access_token"] = token

    return redirect("/home")
Exemplo n.º 16
0
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
Exemplo n.º 17
0
    def login():
        # provder (github) sends the authorization code back
        code = request.args.get('code')
        client = WebApplicationClient(
            client_id=os.getenv("GIT_CLIENT_ID"),
            client_secret=os.getenv("GIT_CLIENT_SECRET"),
            code=code)
        # client then sends he authorization code back to the providers token URL to exchange for token
        url, headers, body = client.prepare_token_request(
            'https://github.com/login/oauth/access_token',
            client_secret=os.getenv("GIT_CLIENT_SECRET"),
            code=code)
        # parse the JSON response body post token validation, receives an access token or key
        token_response = requests.post(url,
                                       headers=headers,
                                       data=body,
                                       auth=(os.getenv("GIT_CLIENT_ID"),
                                             os.getenv("GIT_CLIENT_SECRET")))
        # parse the token from the response
        token = client.parse_request_body_response(token_response.text)
        # save the token
        session['oauth_token'] = token
        # get user id details by passing above git token
        github = OAuth2Session(os.getenv("GIT_CLIENT_ID"),
                               token=session['oauth_token'])
        # can see my details in response 200
        userinfo_response = jsonify(
            github.get('https://api.github.com/user').json())
        # prints out logged in user, TheLegendaryPan in this case!
        user_id = userinfo_response.json['login']

        user = User(user_id)
        login_user(user)

        return redirect(url_for('getAll'))
Exemplo n.º 18
0
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)
Exemplo n.º 19
0
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()
Exemplo n.º 20
0
def callback(app, request):
    # Get authorization code Google sent back to you
    code = request.args.get("code")
    client = WebApplicationClient(app.config["GOOGLE_CLIENT_ID"])

    # Find out what URL to hit to get tokens that allow you to ask for
    # things on behalf of a user
    google_provider_cfg = get_google_provider_cfg(app)
    token_endpoint = google_provider_cfg["token_endpoint"]

    # Prepare and send request to get tokens! Yay tokens!
    token_url, headers, body = 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=(app.config["GOOGLE_CLIENT_ID"],
              app.config["GOOGLE_CLIENT_SECRET"]),
    )

    # Parse the tokens!
    client.parse_request_body_response(json.dumps(token_response.json()))

    # Now that we have tokens (yay) let's find and hit URL
    # from Google that gives you user's profile information,
    # including their Google Profile Image and Email
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    # We want to make sure their email is verified.
    # The user authenticated with Google, authorized our
    # app, and now we've verified their email through Google!
    if userinfo_response.json().get("email_verified"):
        return {
            "unique_id": userinfo_response.json()["sub"],
            "users_name": userinfo_response.json()["given_name"],
            "users_email": userinfo_response.json()["email"],
            "picture": userinfo_response.json()["picture"],
        }
    else:
        return None
Exemplo n.º 21
0
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)
Exemplo n.º 22
0
class OAuthAuthorizationCodeGrantRequest:
    def __init__(self, redirect_uri: str, settings: OAuthSettings):
        from aiohttp import ClientSession
        from oauthlib.oauth2 import WebApplicationClient

        self.settings = settings
        self.future = get_event_loop().create_future()
        self.state = uuid.uuid4().hex
        self.client = WebApplicationClient(settings.client_id)
        self.redirect_uri = redirect_uri
        self.session = ClientSession()

    async def start(self) -> None:
        uri = self.client.prepare_request_uri(
            self.settings.token_uri, redirect_uri=self.redirect_uri, state=self.state)
        body = self.client.prepare_request_body()

        async with self.session.post(uri, data=body) as response:
            print(response.status)
            print(await response.text())

    async def handle_redirect(self, uri: str, code: str, state: str) -> OAuthSettings:
        self.client.parse_request_uri_response(uri, state)

        kwargs = {}
        if self.settings.client_secret:
            kwargs['client_secret'] = self.settings.client_secret

        uri = self.settings.token_uri
        body = self.client.prepare_request_body(
            code=code, redirect_uri=self.redirect_uri, **kwargs)

        # fetch token

        self.client.parse_request_body_response(response_body)

        new_settings = OAuthSettings(

        )

        self.future.set_result(new_settings)
        return new_settings

    async def close(self):
        await self.session.close()
Exemplo n.º 23
0
    def login_with_google_callback():
        if app.config.get('GOOGLE_CLIENT_ID') \
                and not request.is_secure \
                and request.headers.get('X-Forwarded-Proto', 'http') == 'https':
            os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

        client = WebApplicationClient(app.config.get('GOOGLE_CLIENT_ID'))
        google_provider_cfg = requests.get(app.config.get('GOOGLE_DISCOVERY_URL')).json()
        code = request.args.get("code")

        token_endpoint = google_provider_cfg["token_endpoint"]

        token_url, headers, body = client.prepare_token_request(
            token_endpoint,
            authorization_response=request.url,
            redirect_url=url_for('login_with_google_callback', _external=True),
            code=code,
        )
        token_response = requests.post(
            token_url,
            headers=headers,
            data=body,
            auth=(
                app.config.get('GOOGLE_CLIENT_ID'),
                app.config.get('GOOGLE_CLIENT_SECRET'),
                ),
            ).json()

        client.parse_request_body_response(json.dumps(token_response))

        userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
        uri, headers, body = client.add_token(userinfo_endpoint)
        userinfo_response = requests.get(uri, headers=headers, data=body).json()

        user = app.datamapper.user.getByGoogleId(userinfo_response["sub"])

        if user is None:
            response = redirect(url_for('login'))
            flash("Login failed", 'error')
            return response

        else:
            session['user_id'] = user.id
            flash("Welcome %s" % userinfo_response.get('name', user.name), 'success')
            return redirect(url_for('home'))
Exemplo n.º 24
0
    def link_google_callback(self):
        if self.config.get('GOOGLE_CLIENT_ID') \
                and not request.is_secure \
                and request.headers.get('X-Forwarded-Proto', 'http') == 'https':
            os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

        client = WebApplicationClient(self.config.get('GOOGLE_CLIENT_ID'))
        google_provider_cfg = requests.get(
            self.config.get('GOOGLE_DISCOVERY_URL')).json()
        code = request.args.get("code")

        token_endpoint = google_provider_cfg["token_endpoint"]

        token_url, headers, body = client.prepare_token_request(
            token_endpoint,
            authorization_response=request.url,
            redirect_url=url_for('user.link_google_callback', _external=True),
            code=code,
        )
        token_response = requests.post(
            token_url,
            headers=headers,
            data=body,
            auth=(
                self.config.get('GOOGLE_CLIENT_ID'),
                self.config.get('GOOGLE_CLIENT_SECRET'),
            ),
        ).json()

        client.parse_request_body_response(json.dumps(token_response))

        userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
        uri, headers, body = client.add_token(userinfo_endpoint)
        userinfo_response = requests.get(uri, headers=headers,
                                         data=body).json()

        user = self.datamapper.getById(request.user.id)
        user.google_id = userinfo_response["sub"]
        self.datamapper.update(user)

        return redirect(url_for('user.edit', obj_id=user.id))
    def test_parse_token_response(self):
        client = WebApplicationClient(self.client_id)

        # Parse code and state
        response = client.parse_request_body_response(self.token_json, scope=self.scope)
        self.assertEqual(response, self.token)
        self.assertEqual(client.access_token, response.get("access_token"))
        self.assertEqual(client.refresh_token, response.get("refresh_token"))
        self.assertEqual(client.token_type, response.get("token_type"))

        # Mismatching state
        self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid")
Exemplo n.º 26
0
    def login():

        request_code = request.args.get('code')
        client = WebApplicationClient(github_oauth_client_id)

        token_url, headers, body = client.prepare_token_request(
            github_oauth_token_url,
            authorization_response=request.url,
            code=request_code,
            client_secret=github_oauth_client_secret)

        token_resp = requests.post(token_url, headers=headers, data=body)
        client.parse_request_body_response(token_resp.text)

        get_user_uri, headers, body = client.add_token(
            'https://api.github.com/user')
        user_profile = requests.get(get_user_uri, headers=headers, data=body)
        user_profile_id = user_profile.json()["id"]
        user = User(user_profile_id)
        login_user(user)

        return redirect('/')
Exemplo n.º 27
0
    def login():
        github_code = request.args.get('code')
        client = WebApplicationClient(os.environ.get('AUTH_CLIENTID'))
        token = client.prepare_token_request(os.environ.get('AUTH_TOKEN_URL'),
                                             code=github_code)
        access = requests.post(token[0],
                               headers=token[1],
                               data=token[2],
                               auth=(os.environ.get('AUTH_CLIENTID'),
                                     os.environ.get('AUTH_SECRET')))
        client.parse_request_body_response(access.text)
        github_user_request_param = client.add_token(
            os.environ.get('AUTH_API_URL'))
        user_id = requests.get(
            github_user_request_param[0],
            headers=github_user_request_param[1]).json()['login']
        print(user_id)

        login_user(User(user_id))
        app.logger.info(f"User {current_user.id} logged in")

        return redirect('/')
Exemplo n.º 28
0
 def callback():
     client = WebApplicationClient(os.getenv("CLIENT_ID"))
     client.state = request.args.get('state')
     code = request.args.get('code')
     tokenurl, headers, body = client.prepare_token_request(
         'https://github.com/login/oauth/access_token',
         state=client.state,
         code=code)
     secret = os.getenv('OAUTH_SECRET')
     clientid = os.getenv("CLIENT_ID")
     tokenresponse = requests.post(tokenurl,
                                   data=body,
                                   auth=(clientid, secret))
     client.parse_request_body_response(tokenresponse.text)
     userinfo_endpoint = "https://api.github.com/user"
     uri, headers, body = client.add_token(userinfo_endpoint)
     userinfo_response = requests.get(uri, headers=headers, data=body)
     userinfo_json = userinfo_response.json()
     id = userinfo_json['id']
     flask_login.login_user(load_user(id))
     app.logger.info("user logged in Succesfully",
                     extra={"user_id": flask_login.current_user.get_id()})
     return redirect("/")
Exemplo n.º 29
0
def get_access_token(code, state):
    auth_client = WebApplicationClient(OAUTH_ID)
    token_request = auth_client.prepare_token_request(
        'https://github.com/login/oauth/access_token',
        client_id=OAUTH_ID,
        client_secret=OAUTH_SECRET,
        code=code,
        state=state
    )
    print(token_request)
    token_request[1]['Accept'] = 'application/json'
    access_token_response = requests.post(token_request[0], data=token_request[2], headers=token_request[1]).content
    token_params = auth_client.parse_request_body_response(access_token_response)
    return token_params['access_token']
Exemplo n.º 30
0
def callback():
    # Get authorization code Google sent back to you
    code = request.args.get("code")
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]
    token_url = "https://accounts.google.com/o/oauth2/token"
    refresh_url = token_url
    client = WebApplicationClient(GOOGLE_CLIENT_ID)
    token_url, headers, body = 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=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )
    client.parse_request_body_response(json.dumps(token_response.json()))
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)
    if userinfo_response.json().get("email_verified"):
        unique_id = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
        users_name = userinfo_response.json()["given_name"]
    else:
        return "User email not available or not verified by Google.", 400

    employee = Employee.query.filter_by(email=users_email).first()
    login_user(employee)
    if employee.email == '*****@*****.**':
        employee.is_admin = 1
        return redirect(url_for("home.admin_dashboard"))
    else:
        return redirect(url_for("home.dashboard"))
Exemplo n.º 31
0
    def login_callback():
        callback_code = request.args.get("code")
        github_client =  WebApplicationClient(os.environ.get('clientId'))
        github_token = github_client.prepare_token_request("https://github.com/login/oauth/access_token", code=callback_code) 
        github_access = requests.post(github_token[0], headers=github_token[1], data=github_token[2], auth=(os.environ.get('clientId'), os.environ.get('client_secret')))
        github_json = github_client.parse_request_body_response(github_access.text)
        github_user_request_param = github_client.add_token("https://api.github.com/user")
        github_user = requests.get(github_user_request_param[0], headers=github_user_request_param[1]).json()

        login_user(User(github_user))

        mongo.add_user_mongo(current_user)
        app.logger.info("User '%s' logged in successfully", current_user.name)

        return redirect('/') 
Exemplo n.º 32
0
    def test_parse_token_response(self):
        client = WebApplicationClient(self.client_id)

        # Parse code and state
        response = client.parse_request_body_response(self.token_json,
                                                      scope=self.scope)
        self.assertEqual(response, self.token)
        self.assertEqual(client.access_token, response.get("access_token"))
        self.assertEqual(client.refresh_token, response.get("refresh_token"))
        self.assertEqual(client.token_type, response.get("token_type"))

        # Mismatching state
        self.assertRaises(Warning,
                          client.parse_request_body_response,
                          self.token_json,
                          scope="invalid")