I'm trying to build a website that allows people to access different kinds of graphs in a dash app. I want the users to log in with a username and a password before they can access the dashboard. This is what I have thus far
from flask import Flask, flash, render_template, request, session
import os, dash
import dash_html_components as html
import dash_core_components as dcc
import flask
app = Flask(__name__)
dash_app = dash.Dash(__name__, server=app, url_base_pathname='/dash_app')
dash_app.config['suppress_callback_exceptions']=True
def index_page():
index = html.Div([
dcc.Link('Page 1', href='/page1'),
html.Br(),
dcc.Link('Page 2', href='/page2'),
html.Br(),
dcc.Link('Page 3', href='/page3'),
html.Br()
])
return index
dash_app.layout = html.Div(children=[
dcc.Location(id='url', refresh=False),
html.Div(id = 'page-content')
])
page_1 = html.Div([
html.H1('Welcome to page 1'),
index_page()
])
page_2 = html.Div([
html.H1('Welcome to page 2'),
index_page()
])
page_3 = html.Div([
html.H1('Welcome to page 3'),
index_page()
])
@dash_app.callback(
dash.dependencies.Output('page-content','children'),
[dash.dependencies.Input('url','pathname')]
)
def display_page(pathname):
if pathname == '/page1':
return page_1
if pathname == '/page2':
return page_2
if pathname == '/page3':
return page_3
else:
return index_page()
@app.route('/')
def home():
if not session.get('logged_in'):
return render_template('login.html')
else:
return flask.redirect('/dash_app')
@app.route('/login', methods=['POST'])
def do_admin_login():
if request.form['password'] == 'password' and request.form['username'] == 'admin':
session['logged_in'] = True
else:
flash('wrong password!')
return home()
if __name__ == "__main__":
app.secret_key = os.urandom(12)
app.run(debug=True, port=5000)
There are two problems that I want to solve:
With this setup, you don't have to login to access the dashboard. If, instead of entering the username and password, you go directly to http://localhost:5000/dash_app you get to see the dashboard immediately. I only want to give access to people that are logged in.
If I refresh my browser page, after clicking on one of the three page links, I get a message saying "Not Found":
I don't understand why this is happening and it feels to me like this has something to with the structure of the app.
Question: How do I solve these two issues? And, more generally; does this structure fit the goal I am trying to achieve? Is this the correct way to setup a dashboard inside a flask app? (I know that this login setup is not safe)
Edit: Regarding the refresh problem, I am sure that it has something to do with the dash app being run inside the flask app, because when I run the dash app by itself I can refresh http://localhost:5000/page1 and it renders successfully.