user2268507
user2268507

Reputation:

Flask to only allow access to page internally

I'm building a RESTful API using Flask and currently have two pages (a login page and a index page).

The index page should only be accessible after a user has logged in.

Currently I have:

@app.route('/venue/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        venue_owner_email = request.form['username']
        venue_owner_password = request.form['password']

        with contextlib.closing(DBSession()) as session:
            try:
                venue = session.query(Venue).filter_by(venue_owner_email=venue_owner_email).first()
                if not venue or not pwd_context.verify(venue_owner_password, venue.venue_owner_password):
                    error = 'Invalid Credentials. Please try again.'
                else:
                    return redirect(url_for('index'))                                                                                   
            except exc.SQLAlchemyError, error:
                session.rollback()
                raise_database_error(error)

    return render_template('login.html', error=error)


@app.route('/', methods = ['GET'])
def index():
    return render_template('index.html')

Currently index.html is accessible through / but I only want it to be accessed via /venue/login and not directly from the browser.

If I use the decorator @auth.login_required, when the redirect occurs, the user has to re-enter their credentials. Is there a way to send the HTTP Authorisation Header when redirecting?

I also thought rather than use redirect, I might just use render_template but I don't know if this is the right way to do it.

Any help on how to properly go about this would be appreciated.

Upvotes: 4

Views: 3743

Answers (1)

Yash Mehrotra
Yash Mehrotra

Reputation: 3120

You can add a decorator to index.html that checks the referring url. If the referring url is /venue/login you should serve the page else return an error.

if request.referrer == <venue login url>:
    # continue
 else:
    # return error message

Upvotes: 3

Related Questions