Exemplo n.º 1
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.º 2
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.º 3
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"))
Exemplo n.º 4
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
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.º 6
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.º 7
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.º 8
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.º 9
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.º 10
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.º 11
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.º 12
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.º 13
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.º 14
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.º 15
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.º 16
0
    def callback():
        get_code = request.args.get('code')
        client = WebApplicationClient(client_id=client_id)
        url, headers, body = client.prepare_token_request(
            'https://github.com/login/oauth/access_token', code=get_code)
        git_access_key = requests.post(url,
                                       headers=headers,
                                       data=body,
                                       auth=(client_id, client_secret))
        git_json = client.parse_request_body_response(git_access_key.text)
        git_user_request = client.add_token("https://api.github.com/user")
        git_user = requests.get(git_user_request[0],
                                headers=git_user_request[1]).json()
        git_login = User(git_user['login'])
        login_user(git_login)

        return redirect('/')
Exemplo n.º 17
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.º 18
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))
Exemplo n.º 19
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.º 20
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.º 21
0
    def login_callback():
        callback_code = request.args.get("code")
        github_client = WebApplicationClient(os.environ.get('GHOAUTHCLIENTID'))
        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('GHOAUTHCLIENTID'),
                  os.environ.get('GHOAUTHCLIENTSECRET')))
        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['login']))
        app.logger.info("Github User %s successfully logged in",
                        github_user['login'])
        return redirect('/')
Exemplo n.º 22
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.º 23
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.º 24
0
class UserController:
    def __init__(self, logger, user_dao):
        self._user_dao = user_dao
        self._client = WebApplicationClient(GOOGLE_CLIENT_ID)
        self._logger = logger

    def load_user(self, user_id):
        return User(self._user_dao.get(user_id))

    def login(self, google_provider_cfg, base_url):
        self._logger.get().debug("UserController: Attempting login")
        authorization_endpoint = google_provider_cfg["authorization_endpoint"]
        request_uri = self._client.prepare_request_uri(
            authorization_endpoint,
            redirect_uri=base_url + "/login/callback",
            scope=["openid", "email", "profile"],
        )
        return redirect(request_uri)

    def callback(self, google_provider_cfg, authorization_code_from_google,
                 url, base_url):
        self._logger.get().debug("UserController: login callback")
        token_endpoint = google_provider_cfg["token_endpoint"]
        token_url, headers, body = self._client.prepare_token_request(
            token_endpoint,
            authorization_response=url,
            redirect_url=base_url,
            code=authorization_code_from_google,
        )
        token_response = requests.post(
            token_url,
            headers=headers,
            data=body,
            auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
        )

        self._client.parse_request_body_response(
            json.dumps(token_response.json()))

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

        if not userinfo_response.json().get("email_verified"):
            return "User email could not be verified by Google.", 400

        user = {
            'id': userinfo_response.json()["sub"],
            'email': userinfo_response.json()["email"],
            'pic': userinfo_response.json()["picture"],
            'name': userinfo_response.json()["given_name"],
            'scope': User.get_default_scope()
        }
        if self._user_dao.get(user['id']) is None:
            self._logger.get().debug("UserController: setting new user " +
                                     user['email'])
            self._user_dao.set(user)

        user_to_login = User(user)
        self._logger.get_for(user_to_login).info(
            "UserController: Attempting log in for " + user['name'])
        login_user(user_to_login, remember=True)
        self._logger.get_for(user_to_login).info(
            "UserController: Login success ")

        return redirect(url.replace('login/callback', 'home'))

    def logout(self, url):
        self._logger.get().info("UserController: Logging out")
        logout_user()
        return redirect(url)
Exemplo n.º 25
0
class GoogleMusicSession(httpx.Client):
    authorization_base_url = AUTHORIZATION_BASE_URL
    redirect_uri = REDIRECT_URI
    token_url = TOKEN_URL

    def __init__(self,
                 client_id,
                 client_secret,
                 scope,
                 *,
                 token=None,
                 **kwargs):
        # httpx sets a default timeout on the Client class.
        # requests did not.
        # Disable timeout by default as too low a value
        # can cause issues with upload calls.
        timeout = kwargs.pop('timeout', None)
        super().__init__(timeout=timeout, **kwargs)

        self.params = {}
        self.headers.update({'User-Agent': f'{__title__}/{__version__}'})

        self.client_id = client_id
        self.client_secret = client_secret
        self.scope = scope

        self.token = token or {}
        self.oauth_client = WebApplicationClient(self.client_id,
                                                 token=self.token)

    @property
    def access_token(self):
        return self.token.get('access_token')

    @property
    def authorized(self):
        return bool(self.access_token)

    def authorization_url(self):
        state = generate_token()

        return (self.oauth_client.prepare_request_uri(
            self.authorization_base_url,
            redirect_uri=self.redirect_uri,
            scope=self.scope,
            state=state,
            access_type='offline',
            prompt='select_account'))

    def fetch_token(self, code):
        body = self.oauth_client.prepare_request_body(
            code=code,
            body='',
            redirect_uri=self.redirect_uri,
            include_client_id=None)

        response = self.request(
            'POST',
            self.token_url,
            headers={
                'Accept': 'application/json',
                'Content-Type':
                'application/x-www-form-urlencoded;charset=UTF-8',
            },
            data=dict(urldecode(body)),
            auth=httpx.BasicAuth(self.client_id, self.client_secret))

        self.token = self.oauth_client.parse_request_body_response(
            response.text, scope=self.scope)

        return self.token

    def refresh_token(self):
        refresh_token = self.token.get('refresh_token')

        body = self.oauth_client.prepare_refresh_body(
            body='',
            refresh_token=refresh_token,
            scope=self.scope,
            client_id=self.client_id,
            client_secret=self.client_secret)

        response = self.request(
            'POST',
            self.token_url,
            headers={
                'Accept': 'application/json',
                'Content-Type':
                'application/x-www-form-urlencoded;charset=UTF-8',
            },
            data=dict(urldecode(body)),
            auth=httpx.BasicAuth(self.client_id, self.client_secret),
            withhold_token=True)

        self.token = self.oauth_client.parse_request_body_response(
            response.text, scope=self.scope)
        if 'refresh_token' not in self.token:
            self.token['refresh_token'] = refresh_token

        return self.token

    def request(self,
                method,
                url,
                data=None,
                headers=None,
                withhold_token=False,
                **kwargs):
        if self.token and not withhold_token:
            try:
                url, headers, data = self.oauth_client.add_token(
                    url, http_method=method, body=data, headers=headers)
            except TokenExpiredError:
                self.refresh_token()
                url, headers, data = self.oauth_client.add_token(
                    url, http_method=method, body=data, headers=headers)

        return super().request(method,
                               url,
                               headers=headers,
                               data=data,
                               **kwargs)
Exemplo n.º 26
0
def callback():

    # Get authorization code Google sent back to you
    code = request.args.get("code")
    provider = session['oidc_provider']

    app = App(request.host)
    credentials = app.get_credentials(provider)
    client = WebApplicationClient(credentials['CLIENT_ID'])
    provider_cfg = get_provider_cfg(credentials['DISCOVERY_URL'])

    token_endpoint = 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=(
            credentials['CLIENT_ID'], 
            credentials['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
    userinfo_endpoint = provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    userdata = userinfo_response.json()

    # 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 userinfo_response.json().get("email_verified"):
        unique_id = f'{provider}:{userinfo_response.json()["sub"]}'
        users_email = userinfo_response.json()["email"]
        picture = userinfo_response.json()["picture"]
        users_name = userinfo_response.json()["given_name"]
    else:
        return f"User email not available or not verified by {provider}.", 400

    # Create a user in your db with the information provided
    # by Google


    userinfo = {
        'id': unique_id,
        'name': users_name,
        'email': users_email,
        'profile_pic': picture
    }


    try:
        user = User.get(app, unique_id)
    except UserNotFound:
        print("no such user, create")

        user = User(
                id_ = unique_id, 
                app = app, 
                userinfo = userinfo
        )
        user.create()
    
    # Begin user session by logging the user in
    # print("login user", user)
    login_user(user)
    session['userinfo'] = userinfo
    session.permanent = True

    app_opts = app.get_config('etc/options.json')
    # print("return to:", app_opts['return_url'])
    return redirect(app_opts['return_url'])
Exemplo n.º 27
0
class GoogleClient(object):
    AUTHORIZATION_URL = 'https://accounts.google.com/o/oauth2/v2/auth'
    ACCESS_TOKEN_URL = 'https://oauth2.googleapis.com/token'
    REVOKE_TOKEN_URL = 'https://oauth2.googleapis.com/revoke'
    USER_INFO_URL = 'https://openidconnect.googleapis.com/v1/userinfo'
    ADD_DOCUMENT_URL = 'https://docs.googleapis.com/v1/documents'
    GET_DOCUMENT_URL = 'https://docs.googleapis.com/v1/documents/%(file_id)s'
    EXPORT_DOCUMENT_URL = 'https://docs.google.com/feeds/download/documents/export/Export?id=%(file_id)s&exportFormat=html'

    DEFAULT_SCOPE = [
        'openid', 'email', 'profile',
        'https://www.googleapis.com/auth/documents.readonly',
        'https://www.googleapis.com/auth/userinfo.email',
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.googleapis.com/auth/documents',
        'https://www.googleapis.com/auth/drive.file'
    ]

    GOOGLE_DISCOVERY_URL = (
        'https://accounts.google.com/.well-known/openid-configuration'
    )

    GOOGLE_CLIENT_ID = settings.GOOGLE_CLIENT_ID
    GOOGLE_CLIENT_SECRET = settings.GOOGLE_CLIENT_SECRET

    def __init__(self):
        self.client = WebApplicationClient(self.GOOGLE_CLIENT_ID)

    def get_authorization_uri(self, redirect_uri):
        # Use library to construct the request for login and provide
        # scopes that let you retrieve user's profile from Google
        return self.client.prepare_request_uri(
            self.AUTHORIZATION_URL,
            redirect_uri=redirect_uri,
            scope=self.DEFAULT_SCOPE,
        )

    def complete_authorization(self, code, redirect_url):
        # Prepare token using oauth lib
        token_url, headers, body = self.client.prepare_token_request(
            self.ACCESS_TOKEN_URL,
            redirect_url=redirect_url,
            code=code,
            client_secret=self.GOOGLE_CLIENT_SECRET
        )

        # Check if tokens are valid by sending then to token endpoint
        token_response = requests.post(
            token_url,
            headers=headers,
            data=body,
            auth=(self.GOOGLE_CLIENT_ID, self.GOOGLE_CLIENT_SECRET),
        )

        # Parse the tokens!
        self.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
        uri, headers, body = self.client.add_token(self.USER_INFO_URL)
        user_info_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!
        return user_info_response.json(), token_response.json()
Exemplo n.º 28
0
class FlaskState(object):

    def __init__(self, app):
        self.app = app
        self.client_id = "950581708747-7t86ojep28ors7ei034rm58nidgne2d6.apps.googleusercontent.com"
        self.client_secret = "8o1MSmNN9R4iYYWATIgD8_Dk"
        self.google_url = "https://accounts.google.com/.well-known/openid-configuration"

        self.database_manager = DatabaseManager()
        self.db_conn = self.database_manager.get_db()

        self.login_manager = LoginManager()
        self.login_manager.init_app(self.app)
        self.login_manager._user_callback = lambda user_id: User(self.db_fresh()).get(user_id)

        self.client = WebApplicationClient(self.client_id)

        self.current_user = current_user
        self.login_user = login_user
        self.logout_user = logout_user

    def db_fresh(self):
        return self.database_manager.get_db()

    def google_login(self):
        google_provider = requests.get(self.google_url).json()
        authorization_endpoint = google_provider["authorization_endpoint"]
        request_uri = self.client.prepare_request_uri(
            authorization_endpoint,
            redirect_uri= request.base_url + "/callback",
            scope=["openid", "email", "profile"]
        )
        return redirect(request_uri)

    def login_callback(self):
        code = request.args.get("code")
        google_provider = requests.get(self.google_url).json()
        token_endpoint = google_provider["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.client_id, self.client_secret)
        )

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

        userinfo_endpoint = google_provider["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"):
            unique_id = userinfo_response.json()["sub"]
            users_email = userinfo_response.json()["email"]
            picture = userinfo_response.json()["picture"]
            users_name = userinfo_response.json()["given_name"]
        else:
            return "User email not available or not verified by Google.", 400

        user = User(DatabaseManager().get_db())
        # Doesn't exist? Add it to the database.
        if not user.get(unique_id):
            user.create(unique_id, users_name, users_email, picture)
        # Begin user session by logging the user in
        self.login_user(user)
        self.current_user = user
        return redirect(os.path.split(os.path.split(request.base_url)[0])[0])
Exemplo n.º 29
0
async def handle_oauth():

    register_msg = '<p class="text-monospace">!ow register</p>'
    try:
        logger.debug(f"handle_oauth with request args {request.args}")
        try:
            state = request.args["state"]
        except KeyError:
            return await render_message(
                _("I got an incomplete answer from the server. This sometimes happens (for unknown reasons) when registering from a "
                  "mobile phone. Try again with a PC or laptop. Sorry for the inconvenience"
                  ),
                is_error=True,
            )
        type, uid = serializer.loads(state, max_age=600)
    except SignatureExpired:
        return await render_message(
            _("The link has expired. Please request a new link with {register}."
              ).format(register=register_msg),
            is_error=True,
        )
    except BadSignature:
        return await render_message(
            _("The data I got back is invalid. Please request a new URL with {register}."
              ).format(register=register_msg),
            is_error=True,
        )

    if type == "pc":
        token_url = "https://eu.battle.net/oauth/token"
        endpoint = "https://eu.battle.net/oauth/userinfo"
        client_id = OAUTH_BLIZZARD_CLIENT_ID
        client_secret = OAUTH_BLIZZARD_CLIENT_SECRET
        scope = []
    elif type == "xbox":
        token_url = "https://discord.com/api/oauth2/token"
        endpoint = "https://discord.com/api/v6/users/@me/connections"
        scope = ["connections"]
        client_id = OAUTH_DISCORD_CLIENT_ID
        client_secret = OAUTH_DISCORD_CLIENT_SECRET
    else:
        return await render_message(
            _("I got invalid data. Please try registering again."),
            is_error=True)

    client = WebApplicationClient(client_id)
    logger.debug(f"got OAuth auth URL {request.url}")

    # we are behind a proxy, and hypercorn doesn't support
    # proxy headers yet, so just fake https to avoid an exception
    request_url = request.url.replace("http:", "https:")

    if "error=access_denied" in request_url:
        return await render_message(
            _("You didn't give me permission to access your BattleTag; registration cancelled."
              ),
            is_error=True,
        )

    try:
        url, headers, body = client.prepare_token_request(
            token_url,
            authorization_response=request_url,
            scope=scope,
            redirect_url=f"{OAUTH_REDIRECT_HOST}{OAUTH_REDIRECT_PATH}",
            client_secret=client_secret,
        )

        logger.debug(f"got data {(url, headers, body)}")

        resp = await asks.post(url, headers=headers, data=body)

        logger.debug("got response %s", resp.text)

        client.parse_request_body_response(resp.text, scope=scope)

        logger.debug("token is %s", client.token)

        url, headers, body = client.add_token(endpoint)

        logger.debug("requesting data")

        data = (await asks.get(url, headers=headers)).json()

        logger.debug("data received: %s", data)
    except Exception:
        logger.error(
            f"Something went wrong while getting OAuth data for {uid} {request_url}",
            exc_info=True,
        )
        return await render_message(
            _("I'm sorry. Something went wrong on my side. Try to reissue {register}."
              ).format(register=register_msg),
            is_error=True,
        )
    logger.debug("sending to channel %s", send_ch)
    await send_ch.send((uid, type, data))
    logger.debug("sent to channel %s", send_ch)

    return await render_message(_("Thank you! I have sent you a DM."))
Exemplo n.º 30
0
    def api_auth_callback(self):
        s = self._settings
        d = settings_defaults()

        code = flask.request.args.get("code")

        token_endpoint = s.get(['token_endpoint'])
        client_id = s.get(['client_id'])
        client_secret = s.get(['client_secret'])
        userinfo_endpoint = s.get(['userinfo_endpoint'])
        orguser_endpoint = s.get(['orguser_endpoint'])
        organization = s.get(['organization'])
        username_key = s.get(['username_key'])

        self._logger.info('token_endpoint: ' + str(token_endpoint))

        client = WebApplicationClient(client_id)

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

        headers['Accept'] = 'application/json'

        token_response = requests.post(
            token_url,
            headers=headers,
            data=body,
            auth=(client_id, client_secret),
        )

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

        uri, headers, body = client.add_token(userinfo_endpoint)
        headers['Accept'] = 'application/json'
        userinfo_response = requests.get(uri, headers=headers, data=body)

        userinfo = userinfo_response.json()
        username = userinfo[username_key]

        uri, headers, body = client.add_token(orguser_endpoint.format(organization, username))
        headers['Accept'] = 'application/json'
        orguser_response = requests.get(uri, headers=headers, data=body)

        if orguser_response.status_code == 204:
            # User is part of the specified organization, find user or create it if it doesn't exist
            user = self._user_manager.login_user(OAuth2PGCUser(username))
            flask.session["usersession.id"] = user.session
            flask.g.user = user

            self._logger.info("authenticated: " + str(user.is_authenticated))
            self._logger.info("user: "******"Actively logging in user {} from {}".format(user.get_id(), remote_addr))

            r = flask.redirect('/')
            r.delete_cookie("active_logout")

            eventManager().fire(Events.USER_LOGGED_IN, payload=dict(username=user.get_id()))

            return r

        return flask.redirect('/?error=unauthorized')