From 5fa1c62d7ddc8ad84a5cc3247597956356d730c3 Mon Sep 17 00:00:00 2001 From: Aaron Lee Date: Wed, 6 Oct 2021 22:44:08 +0800 Subject: [PATCH] Add token refresh; Add functions.py --- app.py | 44 +++-------------------------- functions.py | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++ manage.py | 41 ++++----------------------- upload.py | 43 +---------------------------- 4 files changed, 88 insertions(+), 118 deletions(-) create mode 100644 functions.py diff --git a/app.py b/app.py index f3a2ab8..78b72dd 100644 --- a/app.py +++ b/app.py @@ -1,10 +1,4 @@ -from flask import * -import pyrebase -from datetime import datetime -import pytz -import os -from dotenv import load_dotenv -import requests +from functions import * from manage import manage from upload import upload load_dotenv() @@ -13,39 +7,6 @@ app.register_blueprint(manage) app.register_blueprint(upload) app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') -config = { - "apiKey": os.environ.get('apiKey'), - "authDomain": os.environ.get('authDomain'), - "databaseURL": os.environ.get('databaseURL'), - "storageBucket": os.environ.get('storageBucket'), - "serviceAccount": os.environ.get('serviceAccount'), - "messagingSenderId": os.environ.get('messagingSenderId'), - "appId": os.environ.get('appId'), - "measurementId": os.environ.get('measurementId'), -} -firebase = pyrebase.initialize_app(config) -db = firebase.database() -auth = firebase.auth() -tz = pytz.timezone('Asia/Taipei') - - -def check_login_status(): - return ('is_logged_in' not in session or - session['is_logged_in'] == False or - (datetime.now(tz) - session['loginTime']).total_seconds() > 3600) - - -def verify_recaptcha(response): - return True - data = { - 'secret': os.environ.get('RECAPTCHA_SECRET'), - 'response': response, - 'remoteip': request.remote_addr - } - r = requests.post( - 'https://www.google.com/recaptcha/api/siteverify', data=data) - print(r.json()) - return r.json()['success'] @ app.route('/', methods=['GET', 'POST']) @@ -106,6 +67,7 @@ def selSubUser(): session.clear() flash("Timeout. 遇時,請重新登入") return redirect('/') + refresh_token() if 'subuser_type' in session and session['subuser_type'] == 'admin': return redirect('/manage') if request.method == 'GET': @@ -143,6 +105,7 @@ def chgPassword(): data = {} if request.method == 'GET': if not check_login_status(): + refresh_token() return render_template('chgPassword.html') else: return abort(404) @@ -150,6 +113,7 @@ def chgPassword(): oldEmail = session['email'] delUser = False if not check_login_status(): + refresh_token() try: if (verify_recaptcha("")): oldUsr = auth.sign_in_with_email_and_password( diff --git a/functions.py b/functions.py new file mode 100644 index 0000000..c918d56 --- /dev/null +++ b/functions.py @@ -0,0 +1,78 @@ +from flask import * +from typing import OrderedDict +from flask import * +import pyrebase +from datetime import datetime +import pytz +import os +import base64 +import csv +import os +import pandas as pd +from random import randint +from dotenv import load_dotenv +load_dotenv() + +config = { + "apiKey": os.environ.get('apiKey'), + "authDomain": os.environ.get('authDomain'), + "databaseURL": os.environ.get('databaseURL'), + "storageBucket": os.environ.get('storageBucket'), + "serviceAccount": os.environ.get('serviceAccount'), + "messagingSenderId": os.environ.get('messagingSenderId'), + "appId": os.environ.get('appId'), + "measurementId": os.environ.get('measurementId'), +} +firebase = pyrebase.initialize_app(config) +db = firebase.database() +auth = firebase.auth() +storage = firebase.storage() +tz = pytz.timezone('Asia/Taipei') + + +def refresh_token(): + user = auth.refresh(session['refreshToken']) + session['is_logged_in'] = True + session['token'] = user['idToken'] + session['refreshToken'] = user['refreshToken'] + session['loginTime'] = datetime.now(tz) + + +def next_item(odic, key): + return list(odic)[list(odic.keys()).index(key) + 1] + + +def check_login_status(): + return ('is_logged_in' not in session or + session['is_logged_in'] == False or + (datetime.now(tz) - session['loginTime']).total_seconds() > 3600) + +# LOGIN + + +def verify_recaptcha(response): + return True + data = { + 'secret': os.environ.get('RECAPTCHA_SECRET'), + 'response': response, + 'remoteip': request.remote_addr + } + r = requests.post( + 'https://www.google.com/recaptcha/api/siteverify', data=data) + print(r.json()) + return r.json()['success'] + +# UPLOAD + + +def check_permission(): + return (db.child('Users').child(session['uid']).child('permission').get(session['token']).val() == 'admin' and + db.child("Users").child(session['uid']).child("showUpload").get(session['token']).val() == '1') + + +def addZeroesUntil(str, number): + if len(str) >= number: + return str + else: + str = str + '0' + return addZeroesUntil(str, number) diff --git a/manage.py b/manage.py index cef07b3..9f4ba75 100644 --- a/manage.py +++ b/manage.py @@ -1,41 +1,6 @@ -from flask import * -from typing import OrderedDict -from flask import * -import pyrebase -from datetime import datetime -import pytz -import os -import base64 -from dotenv import load_dotenv -load_dotenv() - +from functions import * manage = Blueprint('manage', __name__) -config = { - "apiKey": os.environ.get('apiKey'), - "authDomain": os.environ.get('authDomain'), - "databaseURL": os.environ.get('databaseURL'), - "storageBucket": os.environ.get('storageBucket'), - "serviceAccount": os.environ.get('serviceAccount'), - "messagingSenderId": os.environ.get('messagingSenderId'), - "appId": os.environ.get('appId'), - "measurementId": os.environ.get('measurementId'), -} -firebase = pyrebase.initialize_app(config) -db = firebase.database() -auth = firebase.auth() -storage = firebase.storage() -tz = pytz.timezone('Asia/Taipei') - - -def next_item(odic, key): - return list(odic)[list(odic.keys()).index(key) + 1] - - -def check_login_status(): - return ('is_logged_in' not in session or - session['is_logged_in'] == False or - (datetime.now(tz) - session['loginTime']).total_seconds() > 3600) def removeprefix(s, prefix): @@ -51,6 +16,7 @@ def manageProcess(fCommand, fData): db.child("Users").child( session['uid']).child("permission").get(session['token']).val() # end bug fix + refresh_token() pl = session['subuser_type'] if pl == 'admin': homerooms = db.child("Homerooms").get(session['token']).val() @@ -233,6 +199,7 @@ def manage_admin(): def group_teach_publish(): if (check_login_status()): return redirect('/logout') + refresh_token() cclass = { "name": db.child("Classes").child("GP_Class").child(session['category']).child( "Class").child(session['class']).child("name").get(session['token']).val(), @@ -289,6 +256,7 @@ def group_teach_publish(): def homeroom_abs_publish(): if (check_login_status()): return redirect('/logout') + refresh_token() date = request.form['date'] homeroom = request.form['homeroom'].split('^') period = request.form['period'] @@ -326,6 +294,7 @@ def homeroom_abs_publish(): def homeroom_confirm(): if (check_login_status()): return redirect('/logout') + refresh_token() date = request.form['date'] homeroom = request.form['homeroom'].split('^') signature = request.form['signatureData'] diff --git a/upload.py b/upload.py index b6369e7..9302742 100644 --- a/upload.py +++ b/upload.py @@ -1,48 +1,7 @@ -from flask import * -import pyrebase -from datetime import datetime -import pytz -import csv -import os -import pandas as pd -from dotenv import load_dotenv -from random import randint +from functions import * load_dotenv() upload = Blueprint('upload', __name__) -config = { - "apiKey": os.environ.get('apiKey'), - "authDomain": os.environ.get('authDomain'), - "databaseURL": os.environ.get('databaseURL'), - "storageBucket": os.environ.get('storageBucket'), - "serviceAccount": os.environ.get('serviceAccount'), - "messagingSenderId": os.environ.get('messagingSenderId'), - "appId": os.environ.get('appId'), - "measurementId": os.environ.get('measurementId'), -} -firebase = pyrebase.initialize_app(config) -db = firebase.database() -auth = firebase.auth() -tz = pytz.timezone('Asia/Taipei') - - -def check_login_status(): - return ('is_logged_in' not in session or - session['is_logged_in'] == False or - (datetime.now(tz) - session['loginTime']).total_seconds() > 3600) - - -def check_permission(): - return (db.child('Users').child(session['uid']).child('permission').get(session['token']).val() == 'admin' and - db.child("Users").child(session['uid']).child("showUpload").get(session['token']).val() == '1') - - -def addZeroesUntil(str, number): - if len(str) >= number: - return str - else: - str = str + '0' - return addZeroesUntil(str, number) @upload.route('/upload/users', methods=['GET', 'POST'])