def auth_authorized(): if request.args.get('state') != session.get('state'): url = Settings().get('host-url') + url_for('ui_routes.home') print('auth_authorized, A: %s' % url) return redirect(url) if 'error' in request.args: print('auth_authorized, B: auth_error.html') return render_template('auth_error.html', result=request.args) if request.args.get('code'): cache = _load_cache() code = request.args['code'] scopes = [Settings().get('ms-scope')] uri = Settings().get('host-url') + url_for( 'auth_routes.auth_authorized', _external=False) result = _build_msal_app(cache=cache)\ .acquire_token_by_authorization_code(code, scopes=scopes, redirect_uri=uri) if 'error' in result: print('auth_authorized, C: auth_error.html') return render_template('auth_error.html', result=result) session['user'] = result.get('id_token_claims') _save_cache(cache) url = Settings().get('host-url') + url_for('ui_routes.home') return redirect(url)
def load_userinfo(self): # # obtain /.../api/users, find # settings = Settings() url = settings.get('ad_api') + '/api/userinfo' formdata = {'key': settings.get('ad_api_key'), 'identity': self.name} try: data = requests.post(url, data=formdata) if data.status_code != 200: return record = data.json() if record['name'] == self.name: self.authenticated = True self.is_admin = record['admin'] self.is_user = record['user'] else: self.authenticated = False self.is_user = False self.is_admin = False except Exception as e: print('Error in check_groups: %s' % e.__str__()) return
def auth_route(): settings = Settings() guid = str(uuid.uuid4()) session['state'] = guid auth_url = _build_auth_url(scopes=settings.get('ms-scope'), state=session['state']) return redirect(auth_url)
def __init__(self, sess: session = None, req: request = None): if (sess is None) or (req is None): return skeys = [] for s in session.keys(): if s[0:1] != '_': skeys.append(s) for key in skeys: session.pop(key) settings = Settings() uri = 'mongodb://%s:%s' % (settings.get('session_host'), settings.get('session_port')) client = MongoClient(uri) db = client[settings.get('session_db')] collection = db['session'] del_query = {'_id': {'$eq': sess.get('_id')}} try: collection.find_one_and_delete(del_query) except Exception as e: print('Exception: %s' % str(e))
def _build_msal_app(cache=None, authority=None): settings = Settings() return msal.ConfidentialClientApplication( settings.get('ms-client_id'), authority=authority or settings.get('ms-authority'), client_credential=settings.get('ms-client_secret'), token_cache=cache, validate_authority=False)
def __init__(self, page_size=10, page=1): self.settings = Settings() self.parcels = [] self.parcels_flt = [] self.active = '1' self.page_size = page_size self.page = page self.parcel = None self.load_parcels()
def auth_logout(): SessionDestroy(sess=session, req=request) redirect_url = Settings().get('host-url') + url_for('ui_routes.home', _external=False) redirect_path = Settings().get( 'ms-authority' ) + "/oauth2/v2.0/logout" + "?post_logout_redirect_uri=" + redirect_url response = redirect(redirect_path) response.delete_cookie(Settings().get('session_cookie')) return response
def __init__(self): self.name = g.auth['name'] settings = Settings() uri = 'mongodb://%s:%s' % (settings.get('session_host'), settings.get('session_port')) self.client = MongoClient(uri) self.db = self.client[settings.get('session_db')] self.collection = self.db['log'] self.count = 0 self.filelist = [] self.log = []
def route_customer_view_status(): settings = Settings() # # Load Data # rs = CustomerViewStatus() context = { 'settings': settings.items, 'auth': g.auth, 'data': rs.data, 'database_info': settings.get('sqldb'), } return render_template('customer-view-status.html', context=context)
def route_customer_has_email(): settings = Settings() # # Load Data # rs = CustomerHasEmail() context = { 'settings': settings.items, 'auth': g.auth, 'data': rs.data, 'database_info': settings.get('sqldb'), } return render_template('customer-has-email.html', context=context)
def route_statement_no_email(): settings = Settings() # # Load Data # rs = CustNoEmail() context = { 'settings': settings.items, 'auth': g.auth, 'data': rs.data, 'database_info': settings.get('sqldb'), } return render_template('statement-no-email.html', context=context)
def route_received_a_statement(): settings = Settings() # # Load Data # rs = ReceivedStatement() context = { 'settings': settings.items, 'auth': g.auth, 'data': rs.data, 'database_info': settings.get('sqldb'), } return render_template('received-a-statement.html', context=context)
def __init__(self, ): self.settings = Settings() self.data = [] self.load_data() self.maildate = arrow.get( self.data[0]['maildate'] ) self.maildate_str = self.maildate.format(fmt='MM/DD/YYYY') return
def ui_site(sitename): if request.method == 'POST': session['days'] = request.form.get('numdays') s = Settings() site = sitename freq = '4PerDay' # Load default days. days = session.get('days', 15) if days is None: days = 15 # url = s.api_ip + ':' + s.api_port + '/api/v1/site/{}/{}/{}'.format( site, freq, days) # formdata = {} records = {} try: data = requests.post(url, data=formdata) if data.status_code != 200: return records = data.json() except Exception as e: pass context = { 'title': 'Site {}'.format(sitename), 'data': records, 'posturl': '/site/' + sitename, 'def_days': days } return render_template('site.html', context=context)
class Connection: def __init__(self, ): self.settings = Settings() return def value(self, ): server = self.settings.get('sqlserver') database = self.settings.get('sqldb') driver = 'DRIVER={ODBC Driver 17 for SQL Server}' driver = driver + ';SERVER=' + server + ';DATABASE=' + database + ';' if self.settings.get('sql-trusted').lower() == 'y': driver = driver + 'Trusted_Connection=yes;' else: driver = driver + 'UID=' + self.settings.get( 'sql-user') + ';PWD=' + self.settings.get('sql-password') return driver
def home(): if not g.auth['user']: login_page = Settings().get('host-url') + '/auth/login' return redirect(login_page) context = {'title': 'home', 'showsearch': True, 'auth': g.auth} session['page'] = '/' return render_template('home.html', context=context)
def route_deletefile(encoded, parcel): filename = base64.standard_b64decode(encoded).decode('ascii') folder, file = os.path.split(filename) os.remove(filename) UserActivity().save(parcel=parcel, activity='deletefile', msg='delete file: %s' % file) redirect_to = Settings().get('host-url') + '/selected/%s' % parcel return redirect(redirect_to)
def __init__(self, sess): self.session = sess if self.session.get('id', None) is None: sess['id'] = uuid.uuid4().hex self.sessionID = sess['id'] settings = Settings() self.sessLogFile = os.path.join(settings.session_file_dir, self.sessionID) self.create_log_folder() return
def _build_auth_url(authority=None, scopes=None, state=None): p1 = ([scopes] or []) p2 = state or str(uuid.uuid4()) p3 = Settings().get('host-url') + url_for('auth_routes.auth_authorized', _external=False) result = _build_msal_app( authority=authority).get_authorization_request_url(p1, state=p2, redirect_uri=p3) return result
def __init__(self, ): self.settings = Settings() self.process_date = None self.exists = self._check_exist_() if self.exists == False: self.create_swe_process() self.process_date = arrow.get(self.get_process_date()) if self.process_date < arrow.get('2000-01-01T00:00:00'): self.process_date_str = 'N.A.' else: self.process_date_str = self.process_date.format(fmt='MM/DD/YYYY') return
def route_setup(): if g.auth['admin']: settings = Settings() ua = UserActivity() activity_log = ua.list_all_activity() context = { 'log': activity_log, 'auth': g.auth } return render_template('log.html', context=context) else: return redirect('/')
def main_root(): settings = Settings() spd = StatementPrintDate() spd_maildate = spd.maildate_str swe = SWE_Process() process_date = swe.process_date_str btn_txt = 'Process Not Recommended' btn_type = 'btn-primary' if swe.process_date < spd.maildate: btn_txt = 'Process Recommended' btn_type = 'btn-danger' context = { 'settings': settings.items, 'auth': g.auth, 'statement_print_date': spd_maildate, 'swe_process': process_date, 'process_button_txt': btn_txt, 'process_button_type': btn_type, 'database_info': settings.get('sqldb'), } return render_template('main.html', context=context)
def ui_sites(): s = Settings() url = s.api_ip + ':' + s.api_port + '/api/v1/sitelist' formdata = {} records = {} try: data = requests.post(url, data=formdata) if data.status_code != 200: return records = data.json() except Exception as e: pass context = {'title': 'sites', 'data': records} return render_template('sites.html', context=context)
def __init__(self): settings = Settings() self.host = settings.get('mongo_host') self.port = settings.get('mongo_port') uri = "mongodb://%s:%s" % (self.host, self.port) self.client = MongoClient(uri) self.db = self.client[settings.get('mongo_db')] self.data = self.db[settings.get('mongo_data')] self.graph = self.db[settings.get('mongo_graph')] self.mrr = self.db[settings.get('mongo_mrr')] return
def route_selected_parcel(parcel_id): def float2datetime(epoc): import datetime result = '' dt = datetime.datetime.fromtimestamp(epoc) result = dt.strftime('%m/%d/%Y %H:%M:%S') return result def b2k(num): result = '0k' n = int(num) k = round(n / 1024, 2) result = str(k) + 'k' return result if not g.auth['user']: login_page = Settings().get('host-url') + '/auth/login' return redirect(login_page) file_list = FileList(parcel=parcel_id) for f in file_list.files: fpath = bytes(f['fullpath'], 'utf-8') f['encoded'] = '' f['encoded'] = base64.standard_b64encode(fpath).decode('utf-8') f['mtime'] = float2datetime(f['info'].st_mtime) f['filesize'] = b2k(f['info'].st_size) p = Parcels() p.load_one_parcel(parcel_id) details = p.parcel ua = UserActivity() activity = ua.list(parcel=p.parcel['parcel_id']) context = { 'title': 'parcel selected', 'showsearch': False, 'parcel': parcel_id, 'files': file_list.files, 'details': details, 'auth': g.auth, 'ua': activity } session['page'] = '/selected/%s' % parcel_id return render_template('selected_parcel.html', context=context)
def route_setup(): if request.method == 'GET': settings = Settings() context = {'settings': settings.items} return render_template('setup.html', context=context) else: # Extract each item from form, and save back to settings. settings = Settings() for item in settings.items: formitem = request.form[item['name']] item['value'] = formitem settings.save_config() return redirect('/setup')
def route_renamefile_post(): encoded = request.form['encoded'] parcel = request.form['parcel'] newfilename = request.form['newfilename'] # # Extract full path, and then split into path and name. fullpath = base64.standard_b64decode(encoded).decode('ascii') folder, file = os.path.split(fullpath) # # create new full path newfullpath = os.path.join(folder, newfilename) # # now rename the old file to new file. os.rename(fullpath, newfullpath) UserActivity().save(parcel=parcel, activity='renamefile', msg='%s to %s' % (file, newfilename)) redirect_to = Settings().get('host-url') + '/selected/%s' % parcel return redirect(redirect_to)
def app_before_request(): log_request(req=request) auth = {'authenticated': False, 'user': False, 'admin': False, 'name': ''} # try: auth['name'] = session['user']['name'] except Exception as e: auth['name'] = str(e) g.auth = auth # # Don't check if we are logged in for the following paths # try: path = request.full_path + ' ' shortpath = path[0:4] if shortpath in ['/api', '/fil', '/set', '/.we']: return finally: pass user = UserInfo(sess=session) if user.authenticated: auth['authenticated'] = True if user.is_user: auth['user'] = True if user.is_admin: auth['admin'] = True # Record user name if possible. g.auth = auth if path.__contains__('/auth/getAToken?code=' ) and auth['authenticated'] and (not auth['user']): target = Settings().get('host-url') + '/auth/logout' return redirect(target)
def route_statement_no_email_dl(): import io import csv from flask import make_response settings = Settings() # # Load Data # rs = CustNoEmail() csvdata = convert_to_csv(rs.data) si = io.StringIO() # cw = csv.writer(si) for row in csvdata: r = row[0] + ',' + row[1] cw.writerow(row) output = make_response(si.getvalue()) output.headers[ 'Content-Disposition'] = 'attachment; filename=statement-no-email.csv' output.headers['Content-type'] = 'text/csv' return output
def route_customer_view_status_dl(): import io import csv from flask import make_response settings = Settings() # # Load Data # rs = CustomerViewStatus() csvdata = convert_to_csv_extended(rs.data) si = io.StringIO() # cw = csv.writer(si) for row in csvdata: r = row[0] + ',' + row[1] cw.writerow(row) output = make_response(si.getvalue()) output.headers[ 'Content-Disposition'] = 'attachment; filename=customer-view-status.csv' output.headers['Content-type'] = 'text/csv' return output