Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dash Basic Auth - get username in app

I am currently making a Dash app which would show different layout based on user privilege, so I would like to be able to identify the user which is signed up. I'm using Basic Auth and I changed some lines in dash_auth/basic_auth.py: Original:

username_password_utf8 = username_password.decode('utf-8')
username, password = username_password_utf8.split(':')

to:

username_password_utf8 = username_password.decode('utf-8')
username, password = username_password_utf8.split(':')
self._username = username

Unfortunately, I received the : AttributeError: 'BasicAuth' object has no attribute '_username' error when I tried to use the _username attribute from auth.

app.layout = html.Div(
    html.H3("Hello " + auth._username)
)

I understand that the Dash app is already processed before authorization check, but I have no idea where to implement a callback that changes the layout according to username. How can I get the username in the Dash application?

like image 845
Adam Avatar asked Aug 01 '18 17:08

Adam


1 Answers

Basically, you can use flask.request to access the authorization information.

Here's a minimal working example based on the dash authentication documentation.

import dash
import dash_auth
import dash_html_components as html
from dash.dependencies import Input, Output
from flask import request

# Keep this out of source code repository - save in a file or a database
VALID_USERNAME_PASSWORD_PAIRS = [
    ['hello', 'world']
]

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
auth = dash_auth.BasicAuth(
    app,
    VALID_USERNAME_PASSWORD_PAIRS
)

app.layout = html.Div([

    html.H2(id='show-output', children=''),
    html.Button('press to show username', id='button')

], className='container')

@app.callback(
    Output(component_id='show-output', component_property='children'),
    [Input(component_id='button', component_property='n_clicks')]
)
def update_output_div(n_clicks):
    username = request.authorization['username']
    if n_clicks:
        return username
    else:
        return ''

app.scripts.config.serve_locally = True


if __name__ == '__main__':
    app.run_server(debug=True)

I hope this helps!

like image 142
Chris Avatar answered Nov 09 '22 21:11

Chris