Example #1
0
    def wrap(*args, **kwargs):
        # Check if the "item" keyword is in the arguments
        if 'iten' in kwargs:
            # Collect the catalog from the database
            item_id = pg_session.query(Item).filter_by(
                name=kwargs['item']).one()

            if session['user_id'] == item_id.user_id:
                return d(*args, **kwargs)
            else:
                flash('You are not authorised to edit/delete this item',
                      'warning')
                return redirect(url_for('main.list_categories'))

        # Check if the "category" keyword is in the arguments
        if 'category' in kwargs:
            # Collect the catalog from the database
            cat_id = pg_session.query(Category).filter_by(
                name=kwargs['category']).one()

            if session['user_id'] == cat_id.user_id:
                return d(*args, **kwargs)
            else:
                flash('You are not authorised to edit/delete this category',
                      'warning')
                return redirect(url_for('main.list_categories'))
Example #2
0
def listCategoriesJSON():
    '''
    Return a JSON with all the categories

    .. :quickref: API; Get a JSON with all categories

    :return: Return a JSON list of categories.
    '''
    # Retrieve all the categories from the database
    categories = pg_session.query(Category).order_by(Category.name.asc())

    return jsonify(categories=[i.serialize for i in categories])
Example #3
0
def createUser(session):
    '''
    Take the user_id and check the Database, if the user does not exist

    :param flask.session: The flask session instance containing all data
    '''
    newUser = User(name=login_session['username'],
                   email=login_session['email'],
                   picture=login_session['picture'])
    pg_session.add(newUser)
    pg_session.commit()
    user = pg_session.query(User).filter_by(email=login_session['email']).one()
    return user.id
Example #4
0
def listItemsJSON(category):
    '''
    Return a JSON with all the items in the given category

    .. :quickref: API; Get a JSON with all the items under category provided

    :param str category: The selected category
    :return: Retrun a JSON list of items.
    '''
    # Retrieve the last 5 added items from the database
    items = pg_session.query(Item).filter(
        Item.category.has(name=category)).order_by(Item.name.asc())

    return jsonify({'Category': category,
                    'items': [i.serialize for i in items]})
Example #5
0
def oauth2callback():
    '''
    Specify the state so it can verify the server response.
    When successful, fetch the OAuth2 tokens and store the credentials

    .. :quickref: User; Fetch the Oauth2 tokens and store credentials
    '''
    # Check if user is logged_in, then redirect to main page.
    if session.get('logged_in', None):
        flash('You are already logged in', 'warning')
        return redirect(url_for('main.list_categories'))

    # In a development environment allow insecure transport
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    state = session['state']

    # Create the flow instance using the client secret file, scope and state
    flow = Flow.from_client_secrets_file(app.config['CLIENT_SECRET_FILE'],
                                         scopes=app.config['SCOPES'],
                                         state=state)
    # Add the redirect uri to the flow.oauth2session
    flow.redirect_uri = url_for('.oauth2callback', _external=True)

    # Create the authorization url to obtain the access token
    authorization_response = request.url
    # Complete the Authorization Flow and obtain an access token
    flow.fetch_token(authorization_response=authorization_response)

    # Create an credentials instance using session's tokens and client config
    credentials = flow.credentials

    # PLACE ALL TOKENS IN THE DATABASE
    session['credentials'] = credentials_to_dict(credentials)

    # Retrieve userinfo with the session['credentials']
    data = getUserInfo()
    # Add the userinfo into the session dict
    session.update(data)
    # Create a logged_in key with a boolean value True
    session['logged_in'] = True

    # Check if the user has previously logged in with the Google ID
    user = pg_session.query(User).filter_by(google_id=data['id']).first()
    # If user has not previously logged in, create a new user
    if not user:
        user = User(google_id=data['id'],
                    name=data['name'],
                    email=data['email'])
        pg_session.add(user)
        pg_session.commit()
        user = pg_session.query(User).filter_by(email=session['email']).one()

        # Add the new credentials to the Credential Database
        creds = Credential(cred_token=session['credentials']['token'],
                           cred_expiry=session['credentials']['expiry'],
                           cred_refresh=session['credentials']['refresh'],
                           user_id=user.id)
        pg_session.add(creds)
        pg_session.commit()

        # Flash message of correct login
        flash('User {} is authorized'.format(data['name']), 'success')
    else:
        # Flash message of correct login
        flash('Welcome back, {}'.format(data['name']), 'success')

    session['user_id'] = user.id

    # Redirect the user back to the main page.
    return redirect(url_for('main.list_categories'))