Ejemplo n.º 1
0
 def callback(self):
     resp = google.get("/plus/v1/people/me").json()
     try:
         return resp['id'], resp['name']['givenName'], resp['emails'][0]['value']
     except KeyError:
         flash(resp)
         return None, None, None
Ejemplo n.º 2
0
def connect_google():
    page_referrer = request.referrer
    if not google.authorized:
        return redirect(url_for("google.login"))
    resp = google.get("/oauth2/v2/userinfo")
    assert resp.ok, resp.text
    current_profile = UserProfile(
        name="{val}".format(val=resp.json()['name']),
        oauth_provider='google',
        picture_url="{val}".format(val=resp.json()['picture']))
    session['current_profile'] = current_profile.to_json()
    return redirect(page_referrer)
Ejemplo n.º 3
0
def google_login():

    if not google.authorized:
        return redirect(url_for("google.login"))
    resp = google.get(
        "/oauth2/v2/userinfo",
        params={'token': app.blueprints['google'].token["access_token"]},
    )

    email = resp.json()["email"]
    session['username'] = str(email)
    return redirect(url_for('home_page'))
Ejemplo n.º 4
0
def google_login():
    if not google.authorized:
        return redirect(url_for('google.login'))
    resp = google.get("/oauth2/v2/userinfo")
    assert resp.ok, resp.text
    email = resp.json()["email"]
    name = resp.json()["name"]
    picture = resp.json()["picture"]
    return render_template('welcome.html',
                           email=email,
                           name=name,
                           picture=picture)
Ejemplo n.º 5
0
def log_in_google():
    if not google.authorized:
        return redirect(url_for("google.login"))
    try:
        json = google.get("/oauth2/v2/userinfo").json()
        get_or_insert_user(email=json['email'],
                           name=json['given_name'],
                           surname=json['family_name'],
                           picture=json['picture'])
    except TokenExpiredError:
        return redirect(url_for("google.login"))
    return redirect(url_for("home"))
Ejemplo n.º 6
0
 def index():
     if not google.authorized:
         user = None
     else:
         resp = google.get("/oauth2/v2/userinfo")
         assert resp.ok, resp.text
         user = User.from_google_userinfo(resp.json())
     return render_template(
         'index.html',
         user=user,
         texts=texts,
     )
Ejemplo n.º 7
0
def login_google():

    if not google.authorized:
        print(url_for('google.login'))
        return redirect(url_for('google.login'))
    try:
        resp = google.get('/oauth2/v2/userinfo')
        assert resp.ok, resp.text
    except(TokenExpiredError):
        return redirect(url_for('google.login'))

    return f'''You are {resp.json()['email']} on Google'''
Ejemplo n.º 8
0
def google_logged_in(google_bp, token):
    print ('am i here')
    if not token:
        print('login to google failed')
        return False
    print('------------------------ token exists --------------------')
    resp = google.get("/plus/v1/people/me")
    if not resp.ok:
        print('failed to get username from google')
        return False
    print('------------------------ resp ok---------------------')
    google_info = resp.json()
    user_email = google_info['emails'][0]['value']
    print(user_email)

    # query = OAuth.query.filter_by(
    #     provider=google_bp.name,
    #     provider_user_id=user_email
    # )

    lookup = OAuth.query.join(App_User, OAuth.user_id==App_User.id).filter(
        OAuth.provider==google_bp.name,
        App_User.username==user_email
    )
    
    try:
        oauth = lookup.one()
    except NoResultFound:
        print ('----------------------- query failed --------------------------')
        oauth = OAuth(
            provider=google_bp.name,
            token=token
        )

    if oauth.user:
        login_user(oauth.user)
        print('existing account, login successful')

    else:
        print('------------ trying to make new user???-------------')
        #create a new local user account for this user
        user = App_User(
            #need to check that this email is actually always going to be there
            username=user_email
        )
        oauth.user = user
        db.session.add_all([user, oauth])
        db.session.commit()
        login_user(user)
        print('created new account, login successful')

    #disables default flask_dance saving behavior?
    return False
Ejemplo n.º 9
0
def classifyData():
    if testmode:
        return render_template('dataClassify.html',
                               title='Data Classsification',
                               email='testing@devmode')
    if not google.authorized:
        return redirect(url_for("google.login"))
    resp = google.get("/oauth2/v2/userinfo")
    assert resp.ok, resp.text
    return render_template('dataClassify.html',
                           title='Data Classsification',
                           email=resp.json()["email"])
Ejemplo n.º 10
0
    def athenticate_user(cls):
        if google.authorized:
            resp = google.get("/oauth2/v2/userinfo")
            email = resp.json()["email"]
            if email in admin_users:
                return True

            user = UserModel.find_by_username(email)
            if user.dept_id == 9:
                return True

        return False
Ejemplo n.º 11
0
def test_context_local(make_app):
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = make_app(
        "foo1",
        "bar1",
        redirect_to="url1",
        storage=MemoryStorage({"access_token": "app1"}),
    )
    app2 = make_app(
        "foo2",
        "bar2",
        redirect_to="url2",
        storage=MemoryStorage({"access_token": "app2"}),
    )

    # outside of a request context, referencing functions on the `google` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        google.get("https://github.com")

    # inside of a request context, `google` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        google.get("https://google.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"

    with app2.test_request_context("/"):
        app2.preprocess_request()
        google.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
Ejemplo n.º 12
0
def test_context_local(make_app):
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = make_app(
        "foo1",
        "bar1",
        redirect_to="url1",
        backend=MemoryBackend({"access_token": "app1"}),
    )
    app2 = make_app(
        "foo2",
        "bar2",
        redirect_to="url2",
        backend=MemoryBackend({"access_token": "app2"}),
    )

    # outside of a request context, referencing functions on the `google` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        google.get("https://github.com")

    # inside of a request context, `google` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        google.get("https://google.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"

    with app2.test_request_context("/"):
        app2.preprocess_request()
        google.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
Ejemplo n.º 13
0
def single_companypost(company_id):
    form = MyCompany()
    form1 = MyInterview()
    resp = google.get("/oauth2/v1/userinfo")
    user = find_email(resp.json()['email'])
    if form.validate_on_submit() and user:
        ct.update_one({'_id': ObjectId(company_id)}, {
            '$push': {
                'reviews': {
                    '_id': str(ObjectId()),
                    'review': request.form.get('reviews'),
                    'rating': int(request.form.get('rating')),
                    'user': str(user['_id']),
                    'gender': user['gender'],
                    'location': user['location'],
                    'ethnicity': user['ethnicity']
                },
            },
        },
                      upsert=True)

        ct.update_one({'_id': ObjectId(company_id)},
                      {'$set': {
                          'last_modified': datetime.now()
                      }})

        client.delete_multi([str(user['_id']) + "_reviews", company_id])
    elif form1.validate_on_submit() and user:
        ct.update_one({'_id': ObjectId(company_id)}, {
            '$push': {
                request.form.get('position'): {
                    '_id': str(ObjectId()),
                    'employee': request.form.get('employee'),
                    'user': str(user['_id']),
                    'user_gender': user['gender'],
                    'user_ethnicity': user['ethnicity'],
                    'user_location': user['location'],
                    'win': request.form.get('win')
                }
            },
            '$set': {
                'last_modified': datetime.now()
            }
        },
                      upsert=True)
        client.delete_multi([company_id, company_id + "_pd_interviews"])
    else:
        return jsonify({
            'error':
            "Something went wrong.  Make sure you complete your profile!"
        })
    return redirect(request.url)
Ejemplo n.º 14
0
def google_logged_in(blueprint, token):
    resp = google.get("/oauth2/v2/userinfo")
    username = resp.json()['name']
    email = resp.json()['email']
    if resp.ok:
        user = User.query.filter_by(email=email).first()
        if user is None:
            user = User(username=username, email=email)
            db.session.add(user)
            db.session.commit()
            login_user(user)
            return redirect(url_for('type_selector'))
        login_user(user)
Ejemplo n.º 15
0
def retrieve_google_id():
    try:
        account_info = google.get('/oauth2/v1/userinfo')
    except (TokenExpiredError, InvalidClientIdError):
        session.clear()
        return redirect(url_for('google.login'))

    if account_info.ok:
        account_info_json = account_info.json()
        account_id = str(account_info_json['id'])
        return account_id
    else:
        return False
Ejemplo n.º 16
0
def annotator():
    resp = google.get("/oauth2/v2/userinfo")
    target = os.path.join(UPLOAD_FOLDER, 'images/')
    if not os.path.isdir(target):
        os.mkdir(target)
    for upload in request.files.getlist("file"):
        filename = upload.filename
        print(filename)
        destination = "/".join([target, filename])
        upload.save(destination)
    image_names = os.listdir(target)
    print(image_names)
    return render_template("etiquetador.html", image_names=image_names, email=resp.json()["email"])
Ejemplo n.º 17
0
def index():
	if google.authorized:
		try:
			resp = google.get("/oauth2/v1/userinfo")
			session['username'] = resp.json()["email"]
			assert resp.ok, resp.text
			user = users.find_one({'username' : resp.json()["email"]})
			if not user:
				users.insert_one({'username' : resp.json()["email"], 'password' : ""})
			return redirect(url_for('home'))
		except (TokenExpiredError) as e:  # or maybe any OAuth2Error
			return redirect(url_for("index"))
	return render_template('index.html')
Ejemplo n.º 18
0
def logout():
    """
    This endpoint tries to revoke the token
    and then it clears the session
    """
    if google.authorized:
        try:
            google.get(
                'https://accounts.google.com/o/oauth2/revoke',
                params={
                    'token':
                        current_app.blueprints['google'].token['access_token']},
            )
        except TokenExpiredError:
            pass
        except InvalidClientIdError:
            # Our OAuth session apparently expired. We could renew the token
            # and logout again but that seems a bit silly, so for now fake
            # it.
            pass
    _empty_session()
    return redirect(url_for('index'))
Ejemplo n.º 19
0
def index():
    if not google.authorized:
        return redirect(url_for("google.login"))
    resp = google.get("/oauth2/v1/userinfo")

    # Get stats for past day
    stats = getRecentFitStats()

    # TO-DO: magic stuff with the store using the fit stats
    print(stats)

    #return "You are {email} on Google".format(email=resp.json()["email"])
    return shop(stats)
Ejemplo n.º 20
0
def forgetme(user):
    resp = google.get("/oauth2/v1/userinfo")
    if find_email(resp.json()['email'], ):
        ct.update({'reviews.user': user},
                  {'$pull': {
                      'reviews': {
                          'user': user
                      }
                  }})
        ct.update({'interviews.user': user},
                  {'$pull': {
                      'interviews': {
                          'user': user
                      }
                  }})
        ct.remove({'_id': ObjectId(user)})
        resp = google.get("/oauth2/v1/userinfo")
        client.delete_multi(
            [str(user['_id']) + "_reviews"],
            resp.json()['email'],
        )
    return redirect(url_for('home'))
Ejemplo n.º 21
0
def index():
    if not google.authorized:
        return redirect(url_for("google.login"))
    try:
        resp = google.get("/oauth2/v3/userinfo")
    except:
        return redirect(url_for("google.login"))
    email = resp.json()['email']
    name = resp.json()['name']
    update_users(email, name)

    flash('ready to work, ' + name + '?', 'success')
    return render_template('home.html', map=map, user=resp.json())
Ejemplo n.º 22
0
def google_login():
    if not google.authorized:
        return redirect(url_for("google.login"))
    try:
        resp = google.get("/oauth2/v2/userinfo")
        if resp.ok:
            account_info_json = resp.json()
            return bind_oauth_or_register(oauthblueprints[1]['id'], account_info_json['id'], 'google.login', 'google')
        flash(_(u"Google Oauth error, please retry later."), category="error")
        log.error("Google Oauth error, please retry later")
    except (InvalidGrantError, TokenExpiredError) as e:
        flash(_(u"Google Oauth error: {}").format(e), category="error")
        log.error(e)
    return redirect(url_for('web.login'))
Ejemplo n.º 23
0
 def wrap(*args, **kwargs):
     if not google.authorized:
         return redirect(url_for("google.login"))
     try:
         json = google.get('/oauth2/v2/userinfo').json()
         user = get_or_insert_user(email=json['email'],
                                   name=json['given_name'],
                                   surname=json['family_name'],
                                   picture=json['picture'])
         return function(user, *args, **kwargs)
     except TokenExpiredError:
         return redirect(url_for("google.login"))
     except requests.RequestException:
         abort(500)
Ejemplo n.º 24
0
 def wrap(*args, **kwargs):
     if not google.authorized:
         function(*args, **kwargs)
     try:
         json = google.get('/oauth2/v2/userinfo').json()
         user = get_or_insert_user(email=json['email'],
                                   name=json['given_name'],
                                   surname=json['family_name'],
                                   picture=json['picture'])
         return function(user, *args, **kwargs)
     except TokenExpiredError:
         return function(*args, **kwargs)
     except KeyError:
         return function(*args, **kwargs)
Ejemplo n.º 25
0
def google_login():
    if not google.authorized:
        return redirect(url_for('google.login'))
    repo = None
    try:
        resp = google.get('/oauth2/v2/userinfo')
    except:
        return redirect(url_for('google.login'))
    assert resp.ok, resp.text

    username = resp.json()['email']
    if not users.find_one({"username": username}):
        users.insert_one({"username": username, "words": []})
    return make_json_response({"username": username}, 200)
    def get_email(self):
        if not google.authorized:
            # send to google login
            return False

        resp = google.get("/oauth2/v2/userinfo")
        assert resp.ok, resp.text

        email = session['email'] = resp.json().get('email')
        if email in self.authorized_emails:
            return email
        else:
            # unauthorized email
            return abort(403)
Ejemplo n.º 27
0
def deleteGolden():
    if not google.authorized and GOOGLE_LOGIN:
        return redirect(url_for("google.login"))
    if os.path.isfile(conllu(request.values.get("c")).findGolden()):
        caracteristicasCorpus(request.values.get("c"))
        os.remove(conllu(request.values.get("c")).findGolden())
    if os.path.isfile(conllu(request.values.get("c")).findOriginal()):
        os.remove(conllu(request.values.get("c")).findOriginal())
    return render_template(
        'upload.html',
        success="Corpus golden \"" + request.values.get("c") +
        "\" deletado com sucesso!",
        user=google.get('/oauth2/v2/userinfo').json(),
    )
Ejemplo n.º 28
0
def index():
	if google.authorized:
		# print(" google ", google)
		resp = google.get("/oauth2/v1/userinfo")
		session['username'] = resp.json()["email"]
		assert resp.ok, resp.text
		# user = users.find_one({'username' : resp.json()["email"]})
		# if not user:
		# 	users.insert_one({'username' : resp.json()["email"], 'password' : "", 'cart' : [], 'address': "", 'mobile': "", 'purchased':[], 'rating':{}})
		return redirect(url_for('viewHomepage'))
	if 'username' in session:
		return redirect(url_for('viewHomepage'))
	# if 'manufacturerName' in session:
	# 	return redirect(url_for('adminIndex'))
	return render_template('index.html')
Ejemplo n.º 29
0
    def is_authorized(self):
        if not google.authorized:
            # send to google login
            return False

        resp = google.get("/plus/v1/people/me")
        assert resp.ok, resp.text

        email = resp.json()["emails"][0]["value"]
        if email in self.authorized_emails:
            # send to index
            return True
        else:
            # unauthorized email
            return abort(403)
Ejemplo n.º 30
0
def admin():
    if not google.authorized:
        return redirect(url_for("google.login"))

    resp = google.get("/oauth2/v2/userinfo")
    assert resp.ok, resp.text
    email= resp.json()["email"]
    name = resp.json()["name"]

    if email in ['*****@*****.**', '*****@*****.**']:
        bposts = Blog_posts.query.order_by(Blog_posts.post_timestamp.desc()).all()

        return render_template('dashboard.html', bposts=bposts, name=name)
    else:
        abort(403)
Ejemplo n.º 31
0
def google_login():
    if not google.authorized:
        return redirect(url_for('google.login'))
    account_info = google.get('/oauth2/v2/userinfo')
    #    print(account_info)
    if account_info.ok:
        account_info_json = account_info.json()
        #        print(account_info_json)
        user = {}
        #add exception handling for key error
        user['email'] = account_info_json['email']
        user['firstName'] = account_info_json['given_name']
        user['lastName'] = account_info_json['family_name']
        return third_party_user_handler(user['email'], user['firstName'],
                                        user['lastName'], 'google')
def login():
    if not google.authorized:
        return redirect(url_for('google.login'))
    account = google.get('oauth2/v1/userinfo')
    account = account.json()
    email = account['email']
    name = account['name']
    avatar = account['picture']
    user = User.query.filter_by(email=email).first()
    if not user:
        user = User(email=email, name=name, avatar=avatar)
        db.session.add(user)
        db.session.commit()
    login_user(user)
    return redirect(url_for('user.dashboard'))
Ejemplo n.º 33
0
    def is_authorized(self):
        if not google.authorized:
            # send to google login
            return False

        resp = google.get("/oauth2/v2/userinfo")
        assert resp.ok, resp.text

        email = resp.json()["email"]
        if email in self.authorized_emails:
            # send to index
            return True
        else:
            # unauthorized email
            return abort(403)
Ejemplo n.º 34
0
def pass_creds_to_nylas():
    """
    This view loads the credentials from Google and passes them to Nylas,
    to set up native authentication.
    """
    # If you haven't already connected with Google, this won't work.
    if not google.authorized:
        return "Error: not yet connected with Google!", 400

    if "refresh_token" not in google.token:
        # We're missing the refresh token from Google, and the only way to get
        # a new one is to force reauthentication. That's annoying.
        return (
            (
                "Error: missing Google refresh token. "
                "Uncomment the `reprompt_consent` line in the code to fix this."
            ),
            500,
        )

    # Look up the user's name and email address from Google.
    google_resp = google.get("/oauth2/v2/userinfo?fields=name,email")
    assert google_resp.ok, "Received failure response from Google userinfo API"
    google_userinfo = google_resp.json()

    # Start the connection process by looking up all the information that
    # Nylas needs in order to connect, and sending it to the authorize API.
    nylas_authorize_data = {
        "client_id": app.config["NYLAS_OAUTH_CLIENT_ID"],
        "name": google_userinfo["name"],
        "email_address": google_userinfo["email"],
        "provider": "gmail",
        "settings": {
            "google_client_id": app.config["GOOGLE_OAUTH_CLIENT_ID"],
            "google_client_secret": app.config["GOOGLE_OAUTH_CLIENT_SECRET"],
            "google_refresh_token": google.token["refresh_token"],
        },
    }
    nylas_authorize_resp = requests.post(
        "https://api.nylas.com/connect/authorize", json=nylas_authorize_data
    )
    assert nylas_authorize_resp.ok, "Received failure response from Nylas authorize API"
    nylas_code = nylas_authorize_resp.json()["code"]

    # Now that we've got the `code` from the authorize response,
    # pass it to the token response to complete the connection.
    nylas_token_data = {
        "client_id": app.config["NYLAS_OAUTH_CLIENT_ID"],
        "client_secret": app.config["NYLAS_OAUTH_CLIENT_SECRET"],
        "code": nylas_code,
    }
    nylas_token_resp = requests.post(
        "https://api.nylas.com/connect/token", json=nylas_token_data
    )
    assert nylas_token_resp.ok, "Received failure response from Nylas token API"
    nylas_access_token = nylas_token_resp.json()["access_token"]

    # Great, we've connected Google to Nylas! In the process, Nylas gave us
    # an OAuth access token, which we'll need in order to make API requests
    # to Nylas in the future. We'll save that access token in the Flask session,
    # so we can pick it up later and use it when we need it.
    session["nylas_access_token"] = nylas_access_token

    # We're all done here. Redirect the user back to the home page,
    # which will pick up the access token we just saved.
    return redirect(url_for("index"))
Ejemplo n.º 35
0
def index():
    if not google.authorized:
        return redirect(url_for("google.login"))
    resp = google.get("/plus/v1/people/me")
    assert resp.ok, resp.text
    return "You are {email} on Google".format(email=resp.json()["emails"][0]["value"])