-1
from flask import session
from functools import wraps
import flask
from flask import Flask, redirect, url_for, render_template, session
from flask_dance.contrib.google import make_google_blueprint, google
from flask_login import LoginManager, login_user , logout_user , current_user , login_required
from flask_session import Session
import time, dash, os, json, flask, configparser, shutil, base64, io
import pandas as pd
import numpy as np
from plotly.subplots import make_subplots
from dash_table import DataTable
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import dash_daq as daq
import plotly.graph_objs as go
from dash.exceptions import PreventUpdate
import dash_table.FormatTemplate as FormatTemplate 
from dash_table.Format import Format
from dash_extensions import Download 


def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = dict(session).get('profile', None)
        # You would add a check here and usethe user id or something to fetch
        # the other data for that user/check if they exist
        if user:
            return f(*args, **kwargs)
        return render_template('index.html')
    return decorated_function


# AS simeple as possbile flask google oAuth 2.0
from flask import Flask, redirect, url_for, session
from authlib.integrations.flask_client import OAuth
import os
from datetime import timedelta
#dotenv setup
from dotenv import load_dotenv
load_dotenv()


# App config
server = Flask(__name__)
server.secret_key = 'xxxx'
server.config['SESSION_COOKIE_NAME'] = 'google-login-session'
server.config['PERMANENT_SESSION_LIFETIME'] = timedelta(seconds=120)

# oAuth Setup
oauth = OAuth(server)
google = oauth.register(
    name='google',
    client_id='xxxx',
    client_secret='xxxx',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    access_token_params=None,
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    authorize_params=None,
    api_base_url='https://www.googleapis.com/oauth2/v1/',
    userinfo_endpoint='https://openidconnect.googleapis.com/v1/userinfo',  # This is only needed if using openId to fetch user info
    client_kwargs={'scope': 'openid email profile'},
)


@server.route('/')
@login_required
def index():
    email = dict(session)['profile']['email']
    return render_template('index.html')


@server.route('/login')
def login():
    google = oauth.create_client('google')  # create the google oauth client
    redirect_uri = url_for('authorize', _external=True)
    return google.authorize_redirect(redirect_uri)


@server.route('/authorize')
def authorize():
    google = oauth.create_client('google')  # create the google oauth client
    token = google.authorize_access_token()  # Access token from google (needed to get user info)
    resp = google.get('userinfo')  # userinfo contains stuff u specificed in the scrope
    user_info = resp.json()
    user = oauth.google.userinfo()  # uses openid endpoint to fetch user info
    # Here you use the profile/user data that you got and query your database find/register the user
    # and set ur own data in the session not the profile from google
    session['profile'] = user_info
    session.permanent = False  # make the session permanant so it keeps existing after broweser gets closed
    return redirect('/Planner/')


@server.route('/Planner/logout')
def logout():
    for key in list(session.keys()):
        session.pop(key)
    return redirect('/')

app = dash.Dash(__name__, server = server, 
                url_base_pathname='/Planner/')
app.scripts.config.serve_locally = False
app.title = 'Scenario Planner'
app.layout = html.Div([html.Div('Hey'), html.Br(), html.A('Logout', href = './logout')])


if __name__ == "__main__":
    server.run(debug=False)

This is my code. Basically there is a plotly dash application as well running in my code. Everything works except for restricting access to the dash application. If I use localhost:5000/Planner, irrespective of the authentication, my app is displayed.

If I follow the authentication flow, sign in, and then sign out and then click backspace, the dash application is still accessible. Is there a way I can modify this code to restrict such access.

1 Answer 1

0

Using a previous answer which somewhat solved this problem: Running a Dash app within a Flask app I have come up with this solution:

You can add this to your code:

@server.route('/plotly_dashboard') 
@login_required
def render_dashboard():
    return flask.redirect('/Planner')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.