Exemplo n.º 1
0
def createUser(login_session):
    newUser = User(name=login_session['username'], email=login_session[
                   'email'], picture=login_session['picture'])
    session.add(newUser)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
Exemplo n.º 2
0
def checkTokenValid():
    if (not checkLoggedIn()):
        return False
    if (login_session['provider'] == 'local_server'):
        user_id = User.verify_auth_token(login_session['access_token'])
        if (user_id is None):
            return False
    return True
Exemplo n.º 3
0
def newUser():
    if (request.method == 'GET'):
        return render_template('newuser.html')
    if (request.method == 'POST'):
        newUsername = request.form['username']
        newPassword = request.form['password']
        newEmail = request.form['email']
        if ((newUsername is None) or (newUsername == '')
                or (newPassword is None) or (newPassword == '')):
            flash("New user must have a valid username/password")
            return redirect(url_for('newUser'))
        else:
            user = session.query(User).filter_by(username=newUsername).first()
            if (user is None):
                newUser = User(username=newUsername, email=newEmail)
                newUser.set_hash_password(newPassword)
                session.add(newUser)
                session.commit()
                flash("New user created")
                return redirect(url_for('login'))
            else:
                flash("Username already in use")
                return redirect(url_for('newUser'))
Exemplo n.º 4
0
# A DBSession() instance establishes all conversations with the database
# and represents a "staging zone" for all the objects loaded into the
# database session object. Any change made against the objects in the
# session won't be persisted into the database until you call
# session.commit(). If you're not happy about the changes, you can
# revert all of them back to the last commit by calling
# session.rollback()
session = DBSession()

sports = {
    "soccer", "basketball", "tennis", "polo", "track", "swimming", "racing",
    "football", "baseball", "golf", "skydiving", "poker", "video games",
    "chess", "archery", "roulette", "water polo"
}

user = User(name="admin", email="*****@*****.**", admin=True)
session.add(user)
session.commit()

for sport in sports:
    category = Category(name=sport)
    session.add(category)
    session.commit()
    for i in range(random.randint(1, 20)):
        name = sport + ' item ' + str(i + 1)
        price = random.randint(1, 100)
        item = Item(
            name=name,
            description=
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi cursus luctus dapibus. Aenean ut quam eu sapien malesuada porta ut non quam. Etiam cursus maximus eros eu pharetra. Fusce finibus turpis ipsum, quis vehicula libero molestie sed. Aenean cursus viverra nulla, vel venenatis dui vulputate in. Morbi et aliquet erat. Duis eget lacus quis lorem iaculis ornare ut quis dui. Vivamus euismod, sapien nec varius sodales, justo lacus mattis erat, non pellentesque arcu nulla ut neque. Aenean sagittis consectetur sem eu tristique. Donec consectetur turpis tincidunt risus euismod tincidunt. Sed lacus turpis, iaculis nec nulla eget, varius pretium magna. Aliquam vitae magna vitae elit eleifend suscipit eget eu arcu. Nunc dolor ex, bibendum id purus quis, tempus bibendum augue. Praesent consequat sapien risus, quis fermentum velit tincidunt imperdiet. Cras lacinia tempus libero, sed mollis ante tincidunt non.",
            price=price + .99,
Exemplo n.º 5
0
def gconnect():
    # Validate anti-forgery 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('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('''Failed to upgrade the
         authorization code.'''), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    urlBase = 'https://www.googleapis.com/'
    urlLocation = 'oauth2/v1/tokeninfo?access_token='
    access_token = credentials.access_token
    url = urlBase + urlLocation + 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)
        print("sToken's client ID does not match app's.")
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the current user isn't already logged in
    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

    # 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['provider'] = 'google'
    login_session['username'] = data['name']
    login_session['email'] = data['email']
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # See if user exists. IF not, create user
    user = session.query(User).filter_by(email=data["email"]).first()
    if (user is None):
        user = User(username=login_session['username'],
                    email=login_session['email'])
        session.add(user)
        session.commit()
    login_session['id'] = user.id
    flash("Logged in as " + data['name'])
    return "Login Successful"
Exemplo n.º 6
0
def googleConnect():
    # Ensure that the request is not a forgery and that the user sending
    # this connect request is the expected user.
    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
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # 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'

    # 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)
        print "Token's client ID does not match app's."
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_credentials = login_session.get('credentials')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = make_response(json.dumps('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['credentials'] = 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()
    # First User to login gets administrator status
    if session.query(User).first().name == 'admin':
        user = session.query(User).first()
        user.email = data['email']
        user.name = data['name']
        session.add(user)
        session.commit()
        login_session['email'] = user.email
        login_session['name'] = user.name
        login_session['admin'] = user.admin
    else:
        # See if user is a passed user if not create account
        findUser = session.query(User).filter(User.email == data['email'])
        if findUser.first():
            login_session['email'] = findUser.one().email
            login_session['name'] = findUser.one().name
            login_session['admin'] = findUser.one().admin
        else:
            newUser = User(email=data['email'], name=data['name'])
            session.add(newUser)
            session.commit()
            login_session['email'] = newUser.email
            login_session['name'] = newUser.name
            login_session['admin'] = False

    response = make_response(json.dumps('Successfully connected user.'), 200)
    response.headers['Content-Type'] = 'application/json'

    return response