forked from e-mission/op-admin-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_sidebar_collapsible.py
252 lines (221 loc) · 7.9 KB
/
app_sidebar_collapsible.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""
This app creates an animated sidebar using the dbc.Nav component and some local CSS. Each menu item has an icon, when
the sidebar is collapsed the labels disappear and only the icons remain. Visit www.fontawesome.com to find alternative
icons to suit your needs!
dcc.Location is used to track the current location, a callback uses the current location to render the appropriate page
content. The active prop of each NavLink is set automatically according to the current pathname. To use this feature you
must install dash-bootstrap-components >= 0.11.0.
For more details on building multi-page Dash applications, check out the Dash documentation: https://dash.plot.ly/urls
"""
import os
from datetime import date
import dash
import dash_bootstrap_components as dbc
from dash import Input, Output, dcc, html, Dash
import dash_auth
import logging
# Set the logging right at the top to make sure that debug
# logs are displayed in dev mode
# until https://github.com/plotly/dash/issues/532 is fixed
if os.getenv('DASH_DEBUG_MODE', 'True').lower() == 'true':
logging.basicConfig(level=logging.DEBUG)
from utils.db_utils import query_uuids, query_confirmed_trips
from utils.permissions import has_permission
import flask_talisman as flt
OPENPATH_LOGO = "https://www.nrel.gov/transportation/assets/images/openpath-logo.jpg"
auth_type = os.getenv('AUTH_TYPE')
if auth_type == 'cognito':
from utils.cognito_utils import authenticate_user, get_cognito_login_page
elif auth_type == 'basic':
from config import VALID_USERNAME_PASSWORD_PAIRS
app = Dash(
external_stylesheets=[dbc.themes.BOOTSTRAP, dbc.icons.FONT_AWESOME],
suppress_callback_exceptions=True,
use_pages=True,
)
server = app.server # expose server variable for Procfile
if auth_type == 'basic':
auth = dash_auth.BasicAuth(
app,
VALID_USERNAME_PASSWORD_PAIRS
)
sidebar = html.Div(
[
html.Div(
[
# width: 3rem ensures the logo is the exact width of the
# collapsed sidebar (accounting for padding)
html.Img(src=OPENPATH_LOGO, style={"width": "3rem"}),
html.H2("OpenPATH"),
],
className="sidebar-header",
),
html.Hr(),
dbc.Nav(
[
dbc.NavLink(
[
html.I(className="fas fa-home me-2"),
html.Span("Overview")
],
href=dash.get_relative_path("/"),
active="exact",
),
dbc.NavLink(
[
html.I(className="fas fa-sharp fa-solid fa-database me-2"),
html.Span("Data"),
],
href=dash.get_relative_path("/data"),
active="exact",
),
dbc.NavLink(
[
html.I(className="fas fa-solid fa-right-to-bracket me-2"),
html.Span("Tokens"),
],
href=dash.get_relative_path("/tokens"),
active="exact",
style={'display': 'block' if has_permission('token_generate') else 'none'},
),
dbc.NavLink(
[
html.I(className="fas fa-solid fa-globe me-2"),
html.Span("Map"),
],
href=dash.get_relative_path("/map"),
active="exact",
),
dbc.NavLink(
[
html.I(className="fas fa-solid fa-envelope-open-text me-2"),
html.Span("Push notification"),
],
href=dash.get_relative_path("/push_notification"),
active="exact",
style={'display': 'block' if has_permission('push_send') else 'none'},
),
dbc.NavLink(
[
html.I(className="fas fa-gear me-2"),
html.Span("Settings"),
],
href=dash.get_relative_path("/settings"),
active="exact",
)
],
vertical=True,
pills=True,
),
],
className="sidebar",
)
content = html.Div([
# Global Date Picker
html.Div(
dcc.DatePickerRange(
id='date-picker',
display_format='D/M/Y',
start_date_placeholder_text='D/M/Y',
end_date_placeholder_text='D/M/Y',
min_date_allowed=date(2010, 1, 1),
max_date_allowed=date.today(),
initial_visible_month=date.today(),
), style={'margin': '10px 10px 0 0', 'display': 'flex', 'justify-content': 'right'}
),
# Pages Content
dcc.Loading(
type='default',
fullscreen=True,
children=html.Div(dash.page_container, style={
"margin-left": "5rem",
"margin-right": "2rem",
"padding": "2rem 1rem",
})
),
])
home_page = [
sidebar,
content,
]
app.layout = html.Div(
[
dcc.Location(id='url', refresh=False),
dcc.Store(id='store-trips', data={}),
dcc.Store(id='store-uuids', data={}),
html.Div(id='page-content', children=home_page),
]
)
# Load data stores
@app.callback(
Output("store-uuids", "data"),
Input('date-picker', 'start_date'),
Input('date-picker', 'end_date'),
)
def update_store_uuids(start_date, end_date):
start_date_obj = date.fromisoformat(start_date) if start_date else None
end_date_obj = date.fromisoformat(end_date) if end_date else None
dff = query_uuids(start_date_obj, end_date_obj)
records = dff.to_dict("records")
store = {
"data": records,
"length": len(records),
}
return store
@app.callback(
Output("store-trips", "data"),
Input('date-picker', 'start_date'),
Input('date-picker', 'end_date'),
)
def update_store_trips(start_date, end_date):
start_date_obj = date.fromisoformat(start_date) if start_date else None
end_date_obj = date.fromisoformat(end_date) if end_date else None
df = query_confirmed_trips(start_date_obj, end_date_obj)
records = df.to_dict("records")
# logging.debug("returning records %s" % records[0:2])
store = {
"data": records,
"length": len(records),
}
return store
# Define the callback to display the page content based on the URL path
@app.callback(
Output('page-content', 'children'),
Input('url', 'search'),
)
def display_page(search):
if auth_type == 'cognito':
try:
is_authenticated = authenticate_user(search)
except Exception as e:
print(e)
return get_cognito_login_page('Unsuccessful authentication, try again.', 'red')
if is_authenticated:
return home_page
return get_cognito_login_page()
return home_page
extra_csp_url = [
"https://raw.githubusercontent.com",
"https://*.tile.openstreetmap.org",
"https://cdn.jsdelivr.net",
"https://use.fontawesome.com",
"https://www.nrel.gov",
"data:",
"blob:"
]
csp = {
'default-src': ["'self'", "'unsafe-inline'"] + extra_csp_url
}
flt.Talisman(server, content_security_policy=csp, strict_transport_security=False)
if __name__ == "__main__":
envPort = int(os.getenv('DASH_SERVER_PORT', '8050'))
envDebug = os.getenv('DASH_DEBUG_MODE', 'True').lower() == 'true'
app.logger.setLevel(logging.DEBUG)
logging.debug("before override, current server config = %s" % server.config)
server.config.update(
TESTING=envDebug,
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True
)
logging.debug("after override, current server config = %s" % server.config)
app.run_server(debug=envDebug, host='0.0.0.0', port=envPort)