Exemple #1
0
def google_callback():
    #ref: https://realpython.com/flask-google-login/
    code = request.args.get("code")
    google_provider_cfg = requests.get(
        current_app.config['GOOGLE_DISCOVERY_URL']).json()
    token_endpoint = google_provider_cfg["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=(current_app.config['GOOGLE_CLIENT_ID'],
              current_app.config['GOOGLE_CLIENT_SECRET']),
    )

    # Parse the tokens!
    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).json()
    user = User.query.filter_by(email=userinfo_response['email']).first()
    if not user:
        user = User(userinfo_response['email'],
                    username=userinfo_response['sub'],
                    first_name=userinfo_response['given_name'],
                    last_name=userinfo_response['family_name'])
        db.session.add(user)
        db.session.commit()
    login_user(user)
    return redirect(url_for('users.home'))
def oauth_callback():
    '''
    oAuth2 Callback endpoint, expects google accepted query string
    '''
    '''Parse given authorization code'''
    code = request.args.get('code')
    config_payload = requests.get(
        os.environ.get('GOOGLE_DISCOVERY_URL')).json()
    token_endpoint = config_payload['token_endpoint']
    '''Prepare the token request'''
    '''Spits out token_url, headers and body'''
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url='https://fabricio7p.com.br/oauth',
        code=code)
    '''Send the actual request that gets access to user info'''
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(os.environ.get('GOOGLE_CLIENT_ID'),
              os.environ.get('GOOGLE_CLIENT_SECRET')),
    )
    '''Parse received token'''
    '''Retrieve user information from google response'''
    client.parse_request_body_response(json.dumps(token_response.json()))
    userinfo_endpoint = config_payload['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']
        picture = userinfo_response.json()['picture']
        users_name = userinfo_response.json()['given_name']
    else:
        return jsonify(
            {'response': 'User email not avaiable or not verified by Google'})
    '''Finally adding google user to own app database'''
    user_q = User(oauth_id=unique_id,
                  username=users_email,
                  email=users_email,
                  picture=picture,
                  fullname=users_name,
                  password=hash_password(os.environ.get('APP_SECRET_KEY')))
    if not User.query.filter_by(oauth_id=unique_id).first():
        try:
            db.session.add(user_q)
            db.session.commit()
        except IntegrityError:
            abort(500)
    access_code = user_gen_jwt(users_email, os.environ.get('APP_SECRET_KEY'))
    refresh_jwt = user_gen_jwt(users_email,
                               os.environ.get('APP_SECRET_KEY'),
                               refresh=True)
    '''Returns jwt to client'''
    return jsonify({
        'key': '{}'.format(access_code),
        'refresh_key': '{}'.format(refresh_jwt)
    })
Exemple #3
0
def login_google_callback():
    # Get auth code sent back by google.
    code = request.args.get("code")
    google_endpoints = get_google_endpoints()
    token_endpoint = google_endpoints['token_endpoint']
    # Construct and send token request.
    token_url, header, 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=header,
        data=body,
        auth=(app.config['GOOGLE_CLIENT_ID'],
              app.config['GOOGLE_CLIENT_SECRET']),
    )
    client.parse_request_body_response(json.dumps(token_response.json()))
    userinfo_endpoint = google_endpoints['userinfo_endpoint']
    uri, header, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=header, data=body)
    if userinfo_response.json().get("email_verified"):
        uid = userinfo_response.json()["sub"]
        user_email = userinfo_response.json()["email"]
        user_name = userinfo_response.json()["given_name"]
        user = User.query.filter_by(social_id=uid).first()
        if not user:
            add_user = User(social_id=uid,
                            username=user_name,
                            email=user_email)
            db.session.add(add_user)
            db.session.commit()
        login_user(user)
        return redirect(url_for('index'))
    else:
        return "The user cannot be verified by google !!"
Exemple #4
0
def get_google_user(request):
    google_provider_cfg = get_google_provider_cfg()
    code = request.args.get("code")
    token_endpoint = google_provider_cfg.get("token_endpoint")
    print(request.url)
    print(request.base_url)
    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!
    token = client.parse_request_body_response(
        json.dumps(token_response.json()))
    userinfo_endpoint = google_provider_cfg.get("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"]
        picture = userinfo_response.json()["picture"]
        users_name = userinfo_response.json()["given_name"]
        return {
            "email": users_email,
            "profile_pic": picture,
            "username": users_name,
            "id_": unique_id,
            "google_token": json.dumps(token)
        }
    else:
        return None
Exemple #5
0
def callback():
    # 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 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 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"):
        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

    # we can now insert the incoming data into the db
    user = User.query.filter_by(email=users_email).first()
    if user is None:
        user = User(unique_id=unique_id,
                    username=users_name,
                    email=users_email,
                    image_file=picture)

        db.session.add(user)
        db.session.commit()

        requests.post(
            "https://api.mailgun.net/v3/support.annapurna.tech/messages",
            auth=("api", "221bffe3a7b94d381f7e3ff66c3e7332-7fba8a4e-e87281bf"),
            data={
                "from":
                "Annapurna <*****@*****.**>",
                "to": [users_email],
                "subject":
                "Welcome to annapurna {}".format(user.username),
                # "text": "Please click the link {}".format(url),
                "template":
                "welcome",
                "h:X-Mailgun-Variables":
                json.dumps({"sitelink": "https://www.annapurna.tech"})
            })
        login_user(user)
        return redirect(url_for('home'))
    else:
        login_user(user)

        return redirect(url_for('home'))