예제 #1
0
def callback():
    """
    google callback route
    """
    # redirect to home page if user is logged in
    if current_user is not None and current_user.is_authenticated:
        return redirect(url_for('index'))
    # check for errors
    if 'error' in request.args:
        # user denied access to their account
        if request.args.get('error') == 'access_denied':
            return 'Access denied by user'
        # some unknown error occured
        return 'Some error has occured. Please try again'
    # missing state information in the callback
    # something went wrong, login again
    if 'code' not in request.args and 'state' not in request.args:
        return redirect(url_for('login'))
    # successful authentication confirmed at this point
    google = get_google_auth(state=session['oauth_state'])
    try:
        # fetch token from google servers
        token = google.fetch_token(Auth.TOKEN_URI,
                                   client_secret=Auth.CLIENT_SECRET,
                                   authorization_response=request.url)
    except HTTPError as e:
        return 'HTTPError occurred: ' + str(e)
    # get handler for server token
    google = get_google_auth(token=token)
    # get user info now that we have token for user
    resp = google.get(Auth.USER_INFO)
    if resp.status_code == 200:
        # user data fetched
        user_data = resp.json()
        email = user_data['email']
        user = User.query.filter_by(email=email).first()
        if user is None:
            # create new user if user with the email didn't exist
            user = User()
            user.email = email
        user.name = user_data['name']
        user.token = json.dumps(token)
        # save user to database
        db.session.add(user)
        db.session.commit()
        # login user now using flask_login
        login_user(user)
        return redirect(url_for('index'))
    return 'Error when fetching user information from Google'
예제 #2
0
def login_google():
    if current_user is not None and current_user.is_authenticated:
        return redirect(url_for('site.home'))

    if 'error' in request.args:
        if request.args.get('error') == 'access_denied':
            return 'You denied access.'
        return 'Error encountered.'

    if 'code' not in request.args and 'state' not in request.args:
        return redirect(url_for('login'))
    else:
        google = get_google_auth(state=session['oauth_state'])
        try:
            token = google.fetch_token(
                app.config['TOKEN_URI'],
                client_secret=app.config['CLIENT_SECRET'],
                authorization_response=request.url)
        except HTTPError:
            return 'HTTPError occurred.'

        google = get_google_auth(token=token)
        resp = google.get(app.config['USER_INFO'])

        if resp.status_code == 200:

            user_data = resp.json()
            email = user_data['email']
            user = User.query.filter_by(email=email).first()

            if user is None:
                user = User()
                user.email = email

            user.name = user_data['name']

            user.tokens = json.dumps(token)
            user.avatar = user_data['picture']
            user.provider = "google"

            db_session.add(user)
            db_session.commit()

            login_user(user)
            return redirect(url_for('site.home'))

        return 'Could not fetch your information.'
from catalog import db
from catalog.models import User, Category, Item
from datetime import datetime
# Create All Tables
print "Creating tables ..."
db.create_all()

# Create First User
print "Creating User ..."
user = User()
user.username = "******"
user.email = "*****@*****.**"
user.gplus_id = '112241070706889739015'
user.created = datetime.utcnow()
user.modified = datetime.utcnow()
db.session.add(user)
db.session.commit()
print "User - Sophie Reddimalla created ID=" + str(user.id)

print "Creating Sample Category Football ..."
category = Category()
category.title = "Football"
category.user_id = user.id
category.created = datetime.utcnow()
category.modified = datetime.utcnow()
db.session.add(category)
db.session.commit()
print "Category - Football created ID=" + str(category.id)

print "Creating Sample Items in Football ..."
item = Item()
예제 #4
0
def gconnect():
    """
    Gathers data from Google Sign In API and places it inside a session variable.
    """
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets(
            '/var/www/catalog/catalog/client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        flash('Failed to upgrade the authorization code.')
        return (url_for('welcome'))


# Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += '" style = "width: 300px; height:300px;border-radius: 150px;"> '
    flash("you are now logged in as %s" % login_session['username'])

    # Store this User in Database if not existing
    user = User.query.filter_by(gplus_id=str(gplus_id)).first()
    if user is None:
        user = User()
        user.username = login_session['username']
        user.email = login_session['email']
        user.gplus_id = str(login_session['gplus_id'])
        user.created = datetime.utcnow()
        user.modified = datetime.utcnow()
        db.session.add(user)
        db.session.commit()

    return output