def delcheck_page(cid): ''' Dashboard Delete Checks: This will delete health checks via the url parameters ''' verify = verifyLogin( app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) if user.status != "active": pass else: # Delete the Monitor monitor = Monitor(cid) monitor.get(cid, g.rdb_conn) result = monitor.deleteMonitor(user.uid, cid, g.rdb_conn) if result: print("/dashboard/delete-checks - Delete successful") flash('Health Check was successfully deleted.', 'success') else: print("/dashboard/delete-checks - Delete failed") flash('Health Check was not deleted', 'danger') return redirect(url_for('member.dashboard_page'))
def get(self, method, lookup, rdb): ''' Lookup the user by the uid ''' if method == 'uid': uid = lookup elif method == 'username': uid = self.getUID(lookup, rdb) results = r.table('users').get(uid).run(rdb) data = results if data: self.email = results['email'] self.uid = results['id'] self.username = results['username'] self.status = results['status'] self.company = results['company'] self.contact = results['contact'] self.acttype = results['acttype'] self.stripeid = results['stripeid'] self.stripe = results['stripe'] self.subplans = results['subplans'] self.payments = results['payments'] self.subscription = results['subscription'] self.creation_time = results['creation_time'] self.confirmed = results['confirmed'] ## Identify number of monitors and reactions monitor = Monitor() reaction = Reaction() self.monitorCount = monitor.count(self.uid, rdb) self.reactionCount = reaction.count(self.uid, rdb) return self else: return None
def get(self, method, lookup, rdb): """ Lookup the user by the uid """ if method == "uid": uid = lookup elif method == "username": uid = self.getUID(lookup, rdb) results = r.table("users").get(uid).run(rdb) data = results if data: self.email = results["email"] self.uid = results["id"] self.username = results["username"] self.status = results["status"] self.company = results["company"] self.contact = results["contact"] self.acttype = results["acttype"] self.stripeid = results["stripeid"] self.stripe = results["stripe"] self.subplans = results["subplans"] self.payments = results["payments"] self.subscription = results["subscription"] self.creation_time = results["creation_time"] self.confirmed = results["confirmed"] ## Identify number of monitors and reactions monitor = Monitor() reaction = Reaction() self.monitorCount = monitor.count(self.uid, rdb) self.reactionCount = reaction.count(self.uid, rdb) return self else: return None
def test_4members_2fix(self): from monitors import Monitor from scheduler import gen_monitor_combos m1 = Monitor('A', True) m2 = Monitor('B', True) m3 = Monitor('C', False) m4 = Monitor('D', False) members = [m1, m2, m3, m4] expected = [ _create_monitor_combo(m1, m2, m3), _create_monitor_combo(m1, m2, m4), _create_monitor_combo(m2, m1, m3), _create_monitor_combo(m2, m1, m4), _create_monitor_combo(m1, m3, m2), _create_monitor_combo(m1, m3, m4), _create_monitor_combo(m3, m1, m2), _create_monitor_combo(m3, m1, m4), _create_monitor_combo(m1, m4, m2), _create_monitor_combo(m1, m4, m3), _create_monitor_combo(m4, m1, m2), _create_monitor_combo(m4, m1, m3), _create_monitor_combo(m2, m3, m1), _create_monitor_combo(m2, m3, m4), _create_monitor_combo(m3, m2, m1), _create_monitor_combo(m3, m2, m4), _create_monitor_combo(m2, m4, m1), _create_monitor_combo(m2, m4, m3), _create_monitor_combo(m4, m2, m1), _create_monitor_combo(m4, m2, m3), ] actual = list(gen_monitor_combos(members)) self.assertCountEqual(expected, actual)
def delcheck_page(cid): ''' Dashboard Delete Checks: This will delete health checks via the url parameters ''' verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) if user.status != "active": pass else: # Delete the Monitor monitor = Monitor(cid) monitor.get(cid, g.rdb_conn) result = monitor.deleteMonitor(user.uid, cid, g.rdb_conn) if result: print("/dashboard/delete-checks - Delete successful") flash('Health Check was successfully deleted.', 'success') else: print("/dashboard/delete-checks - Delete failed") flash('Health Check was not deleted', 'danger') return redirect(url_for('member.dashboard_page'))
def checkapi_page(atype, cid, check_key, action): ''' Web based API for various health checks ''' monitor = Monitor(cid) monitor.config = app.config urldata = { 'cid': cid, 'atype': atype, 'check_key': check_key, 'action': action } app.logger.debug("Got new API request with these details: %s" % json.dumps(urldata)) try: webapi = __import__("monitorapis." + atype, globals(), locals(), ['webCheck'], -1) replydata = webapi.webCheck(request, monitor, urldata, g.rdb_conn) except Exception as e: app.logger.error("/api/%s - webCheck action failed - %s" % (atype, e.message)) replydata = { 'headers': { 'Content-type': 'application/json' }, 'data': "{ 'results' : 'fatal error' }" } print("/api/%s - API request") % atype return replydata['data']
def detailhistory_page(cid, hid): verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/detail-history/' + hid tmpl = 'monitors/detail-history.html' # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: monitor = Monitor() monitor.get(cid, g.rdb_conn) if monitor.uid == user.uid: data['monitor'] = { 'cid': monitor.cid, 'name': monitor.name, 'ctype': monitor.ctype, 'uid': monitor.uid, 'data': monitor.data } data['monitor-history'] = monitor.history( method="detail-history", hid=hid, rdb=g.rdb_conn) else: flash('This monitor does not belong to your user.', 'warning') page = render_template(tmpl, data=data) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def detailhistory_page(cid, hid): verify = verifyLogin( app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/detail-history/' + hid tmpl = 'monitors/detail-history.html' # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: monitor = Monitor() monitor.get(cid, g.rdb_conn) if monitor.uid == user.uid: data['monitor'] = { 'cid': monitor.cid, 'name': monitor.name, 'ctype': monitor.ctype, 'uid': monitor.uid, 'data': monitor.data } data['monitor-history'] = monitor.history( method="detail-history", hid=hid, rdb=g.rdb_conn) else: flash('This monitor does not belong to your user.', 'warning') page = render_template(tmpl, data=data) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def test_less_than_3members(self): from monitors import Monitor from scheduler import gen_monitor_combos members = { Monitor('A', True), Monitor('B', True), } expected = [] actual = list(gen_monitor_combos(members)) self.assertEqual(expected, actual)
def filter_monitoring_max(monitor: Monitor, day: datetime): filters = [] filter_roles = [] if monitor.is_role_max(ERole.AM1): filter_roles.append(ERole.AM1) if monitor.is_role_max(ERole.AM2): filter_roles.append(ERole.AM2) if monitor.is_role_max(ERole.PM): filter_roles.append(ERole.PM) if filter_roles: filters.append( _create_monitor_combo_filter(monitor.name, include=False, roles=filter_roles)) return filters
def viewhistory_page(cid, start, limit): verify = verifyLogin( app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/view-history/' + cid tmpl = 'monitors/view-history.html' # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: monitor = Monitor() monitor.get(cid, g.rdb_conn) if monitor.uid == user.uid: data['monitor'] = { 'cid': monitor.cid, 'name': monitor.name, 'ctype': monitor.ctype, 'uid': monitor.uid, 'data': monitor.data } chktime = time.time() - float(data['dataret']) data['monitor-history-count'] = monitor.history( method="count", time=chktime, rdb=g.rdb_conn) data['monitor-history'] = monitor.history( method="mon-history", time=chktime, start=int(start), limit=int(limit), rdb=g.rdb_conn) data['error'] = False data['monitor-history-paging'] = [] data['monitor-history-paging-start'] = int(start) cur = 0 while cur < data['monitor-history-count'] - 200: cur = cur + 200 data['monitor-history-paging'].append(cur) else: data['msg'] = "This monitor does not belong to your user" data['error'] = True page = render_template(tmpl, data=data) return page else: return redirect(url_for('user.login_page'))
def checkaction_page(cid, action): ''' Dashboard Delete Checks: This will delete health checks via the url parameters ''' verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) if user.status != "active": pass else: ## Delete the Monitor monitor = Monitor(cid) monitor.get(cid, g.rdb_conn) if user.uid == monitor.uid: if action == "failed": monitor.healthcheck = "web-failed" result = monitor.webCheck(g.rdb_conn) print("/dashboard/action-checks - Manual monitor failure") elif action == "healthy": monitor.healthcheck = "web-healthy" print("/dashboard/action-checks - Manual monitor healthy") result = monitor.webCheck(g.rdb_conn) if result: print("/dashboard/action-checks - Manual monitor queued") flash('Health check status change is queued', 'success') else: print("/dashboard/action-checks - Manual monitor action failed") flash('Something went wrong. Could not modify health check', 'danger') else: print("/dashboard/action-checks - Manual monitor action failed: do not own") flash('It does not appear you own this health check', 'danger') return redirect(url_for('dashboard_page'))
def delreaction_page(rid): ''' Dashboard Delete Domains: This will delete a domain based on url parameters ''' verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.config = app.config user.get('uid', verify, g.rdb_conn) if user.status != "active": pass else: appliedcount = 0 results = r.table('monitors').filter({ 'uid': user.uid }).run(g.rdb_conn) for x in results: monitor = Monitor() monitor.config = app.config monitor.get(x['id'], g.rdb_conn) mondata = monitor.data if rid in mondata['reactions']: appliedcount = appliedcount + 1 if appliedcount < 1: # Delete the Reaction reaction = Reaction(rid) reaction.config = app.config result = reaction.deleteReaction(user.uid, rid, g.rdb_conn) if result: flash('Reaction was successfully deleted.', 'success') else: flash('Reaction was not deleted.', 'danger') else: flash( 'You must first detach this reaction \ from all monitors before deleting.', 'danger') return redirect(url_for('member.dashboard_page'))
def checkaction_page(cid, action): ''' Dashboard Update Checks: This will update health checks via the url parameters ''' verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.config = app.config user.get('uid', verify, g.rdb_conn) if user.status != "active": pass else: # Update the Monitor monitor = Monitor(cid) monitor.config = app.config monitor.get(cid, g.rdb_conn) if user.uid == monitor.uid: if action == "false": monitor.healthcheck = "web-false" result = monitor.webCheck(g.rdb_conn) print("/dashboard/action-checks - Manual monitor failure") elif action == "true": monitor.healthcheck = "web-true" print("/dashboard/action-checks - Manual monitor true") result = monitor.webCheck(g.rdb_conn) if result: print("/dashboard/action-checks - Manual monitor queued") flash('Health check status change is queued.', 'success') else: print("/dashboard/action-checks - \ Manual monitor action failed") flash( 'Something went wrong. \ Could not modify health check.', 'danger') else: print("/dashboard/action-checks - \ Manual monitor action failed: do not own") flash('It does not appear you own this health check.', 'danger') return redirect(url_for('member.dashboard_page'))
def delreaction_page(rid): ''' Dashboard Delete Domains: This will delete a domain based on url parameters ''' verify = verifyLogin( app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.config = app.config user.get('uid', verify, g.rdb_conn) if user.status != "active": pass else: appliedcount = 0 results = r.table('monitors').filter( {'uid': user.uid}).run(g.rdb_conn) for x in results: monitor = Monitor() monitor.config = app.config monitor.get(x['id'], g.rdb_conn) mondata = monitor.data if rid in mondata['reactions']: appliedcount = appliedcount + 1 if appliedcount < 1: # Delete the Reaction reaction = Reaction(rid) reaction.config = app.config result = reaction.deleteReaction(user.uid, rid, g.rdb_conn) if result: flash('Reaction was successfully deleted.', 'success') else: flash('Reaction was not deleted.', 'danger') else: flash('You must first detach this reaction \ from all monitors before deleting.', 'danger') return redirect(url_for('member.dashboard_page'))
def checkapi_page(atype, cid, check_key, action): ''' Web based API for various health checks ''' monitor = Monitor(cid) monitor.config = app.config urldata = { 'cid': cid, 'atype': atype, 'check_key': check_key, 'action': action } app.logger.debug("Got new API request with these details: %s" % json.dumps(urldata)) try: webapi = __import__( "monitorapis." + atype, globals(), locals(), ['webCheck'], -1) replydata = webapi.webCheck(request, monitor, urldata, g.rdb_conn) except Exception as e: app.logger.error("/api/%s - webCheck action failed - %s" % (atype, e.message)) replydata = { 'headers': {'Content-type': 'application/json'}, 'data': "{ 'results' : 'fatal error' }" } print("/api/%s - API request") % atype return replydata['data']
def viewhistory_page(cid, start, limit): verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.config = app.config user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/view-history/' + cid tmpl = 'monitors/view-history.html' # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: monitor = Monitor() monitor.config = app.config monitor.get(cid, g.rdb_conn) if monitor.uid == user.uid: data['monitor'] = { 'cid': monitor.cid, 'name': monitor.name, 'ctype': monitor.ctype, 'uid': monitor.uid, 'data': monitor.data } chktime = time.time() - float(data['dataret']) data['monitor-history-count'] = monitor.history(method="count", time=chktime, rdb=g.rdb_conn) data['monitor-history'] = monitor.history(method="mon-history", time=chktime, start=int(start), limit=int(limit), rdb=g.rdb_conn) data['monitor-history-paging'] = [] data['monitor-history-paging-start'] = int(start) cur = 0 while cur < data['monitor-history-count'] - 200: cur = cur + 200 data['monitor-history-paging'].append(cur) else: flash('This monitor does not belong to your user.', 'warning') page = render_template(tmpl, data=data) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def checkapi_page(atype, cid, check_key, action): ''' Web based API for various health checks ''' monitor = Monitor(cid) urldata = { 'cid': cid, 'atype': atype, 'check_key': check_key, 'action': action } try: webapi = __import__( "monitorapis." + atype, globals(), locals(), ['webCheck'], -1) replydata = webapi.webCheck(request, monitor, urldata, g.rdb_conn) except: print("/api/%s - webCheck action") % atype replydata = { 'headers': {'Content-type': 'application/json'}, 'data': "{ 'results' : 'fatal error' }" } print("/api/%s - API request") % atype return replydata['data']
def addcheck_page(cname): verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/monitors/' + cname tmpl = 'monitors/' + cname + '.html' data['js_bottom'] = [ 'monitors/monitorlist.js', 'monitors/base.js', 'monitors/' + cname + '.js' ] # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: # Get list of reactions and validate that there are some data['reactions'] = user.getReactions(g.rdb_conn) # Proces the form cform = __import__("monitorforms." + cname, globals(), locals(), ['CheckForm'], -1) form = cform.CheckForm(request.form) if form.__contains__("timer"): form.timer.choices = data['choices'] reactchoices = [] for key in data['reactions'].keys(): reactchoices.append((data['reactions'][key]['id'], data['reactions'][key]['name'])) form.reactions.choices = reactchoices if request.method == 'POST': if form.validate(): monitor = Monitor() monitor.name = form.name.data monitor.ctype = cname monitor.uid = user.uid monitor.status = "queued" monitor.url = None tmpdata = {} for item in form.__iter__(): tmpdata[item.name] = item.data monitor.data = tmpdata # Check if the user already exceeds their limit if monitor.count(user.uid, g.rdb_conn) < data['limit']: # Create the monitor if all checks out results = monitor.createMonitor(g.rdb_conn) else: results = "toomany" if results == "exists": print("/dashboard/monitors/{0} - \ Monitor already exists".format(cname)) flash( '{0} seems to already exist. \ Try using a different name.'.format( monitor.name), 'danger') elif results is False: print("/dashboard/monitors/{0} - \ Monitor creation failed".format(cname)) flash('Could not create monitor.', 'danger') elif results == 'toomany': stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Too many health checks', 1) flash( 'You have too many monitors. \ Please upgrade your plan or clean \ up old ones.', 'danger') print("/dashboard/monitors/{0} - \ Monitor creation failed: toomany".format(cname)) else: stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Monitor Added', 1) print("/dashboard/monitors/%s - \ Monitor creation successful") % cname flash( 'Monitor "{0}" successfully added.'.format( monitor.name), 'success') newmonitor = Monitor() newmonitor.get(results, g.rdb_conn) if newmonitor.uid == user.uid: data['monitor'] = { 'cid': newmonitor.cid, 'name': newmonitor.name, 'uid': newmonitor.uid, 'ctype': newmonitor.ctype, 'url': newmonitor.url, 'data': newmonitor.data } else: print("/dashboard/monitors/{0} - \ Monitor creation failed: Form invalid".format(cname)) flash('Form is not valid.', 'danger') page = render_template(tmpl, data=data, form=form) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def editcheck_page(cname, cid): verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/edit-monitors/' + cname + "/" + cid tmpl = 'monitors/' + cname + '.html' data['edit'] = True data['js_bottom'] = ['monitors/base.js', 'monitors/' + cname + '.js'] # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: # Get list of reactions and validate that there are some data['reactions'] = user.getReactions(g.rdb_conn) # Proces the form cform = __import__("monitorforms." + cname, globals(), locals(), ['CheckForm'], -1) form = cform.CheckForm(request.form) oldmonitor = Monitor() oldmonitor.get(cid, g.rdb_conn) if oldmonitor.uid == user.uid: data['monitor'] = { 'cid': oldmonitor.cid, 'name': oldmonitor.name, 'uid': oldmonitor.uid, 'ctype': oldmonitor.ctype, 'url': oldmonitor.url, 'data': oldmonitor.data } # Check if the form contains the timer SelectField if form.__contains__("timer"): form.timer.choices = data['choices'] reactchoices = [] reactdefaults = [] for key in data['reactions'].keys(): reactchoices.append((data['reactions'][key]['id'], data['reactions'][key]['name'])) if data['reactions'][key]['id'] in \ data['monitor']['data']['reactions']: reactdefaults.append(data['reactions'][key]['id']) form.reactions.choices = reactchoices for item in form.__iter__(): if item.type == "SelectField" or\ item.type == "SelectMultipleField": item.default = data['monitor']['data'][item.name] if request.method == 'POST': if form.validate(): monitor = Monitor() monitor.cid = cid monitor.name = form.name.data monitor.ctype = cname monitor.uid = user.uid monitor.status = "queued" monitor.url = oldmonitor.url tmpdata = {} for item in form.__iter__(): tmpdata[item.name] = item.data if item.type == "SelectField" or\ item.type == "SelectMultipleField": item.default = item.data monitor.data = tmpdata data['monitor'] = { 'cid': monitor.cid, 'name': monitor.name, 'uid': monitor.uid, 'ctype': monitor.ctype, 'url': monitor.url, 'data': monitor.data } reactdefaults = data['monitor']['data']['reactions'] # Check if the user already exceeds their limit if oldmonitor.uid == user.uid: # Create the monitor if all checks out results = monitor.editMonitor(g.rdb_conn) else: results = "NotYours" print("/dashboard/edit-monitors/{0} - \ Monitor edit failed: not users".format(cname)) flash("This Monitor doesn't appear to be yours.", 'danger') if results == "exists": print("/dashboard/edit-monitors/{0} - \ Monitor edit failed: exists".format(cname)) flash( 'This monitor seems to already exist. \ Try using a different name.', 'danger') elif results is False: print("/dashboard/edit-monitors/{0} - Monitor \ edit failed: unknown reason".format(cname)) flash('Could not edit monitor.', 'danger') elif results == 'toomany': stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Too many health checks', 1) print("/dashboard/edit-monitors/{0} - \ Monitor edit failed: too many".format(cname)) flash( 'You have too many monitors. \ Please upgrade your plan or clean \ up old ones.', 'danger') else: stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Monitor Added', 1) print("/dashboard/edit-monitors/{0} - \ Monitor edit successful").format(cname) flash( 'Monitor "{0}" successfully edited'.format( monitor.name), 'success') else: print("/dashboard/edit-monitors/{0} - \ Monitor edit failed: Form invalid".format(cname)) flash('Form is not valid.', 'danger') # Process form to display defaults if form.__contains__("timer"): form.timer.default = data['monitor']['data']['timer'] form.reactions.default = reactdefaults form.process() page = render_template(tmpl, data=data, form=form) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def modsub_page(): '''Dashboard Modify Subscription: This will allow a user to modify their subscription and account plan ''' verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/mod-subscription' data['uid'] = user.uid tmpl = 'member/mod-subscription.html' data['js_bottom'].append('forms/subscribe.js') form = [] headers = { "content-type": "application/json", "Authorization": app.config['ASSEMBLY_PRIVATE_KEY'] } from generalforms import subscribe if data['acttype'] == "Lite": # Upgrade Users if request.method == "POST" and \ "stripeToken" in request.form and "plan" in request.form: stripeToken = request.form['stripeToken'] plan = request.form['plan'] if stripeToken: result = None monitor = Monitor() payload = { 'email': user.email, 'quantity': monitor.count(user.uid, g.rdb_conn), 'card': stripeToken, 'plan': plan } json_payload = json.dumps(payload) url = app.config['ASSEMBLY_PAYMENTS_URL'] + "/customers" print("Making request to %s") % url try: # Send Request to Assembly to create user and subscribe # them to desired plan result = requests.post(url=url, headers=headers, data=json_payload, verify=True) except: print("Critical Error making request to ASM Payments") flash( 'There was an error processing \ your card details.', 'danger') print("Got {0} status code from Assembly".format( result.status_code)) if result.status_code >= 200 and result.status_code <= 299: rdata = json.loads(result.text) user.stripeid = rdata['id'] user.stripe = stripeToken user.subplans = payload['quantity'] user.subscription = payload['plan'] user.acttype = "pro" print("Setting UID %s Subscription to: %s") % ( user.uid, user.acttype) subres = user.setSubscription(g.rdb_conn) stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' User Upgrades', 1) if subres: newdata = startData(user) data['limit'] = newdata['limit'] data['rlimit'] = newdata['rlimit'] data['acttype'] = newdata['acttype'] data['subplans'] = newdata['subplans'] data['cost'] = newdata['cost'] data['subscription'] = newdata['subscription'] flash('Subscription successfully created.', 'success') else: flash('Subscription not successfully created.', 'danger') # Increase subscription if data['acttype'] != "Lite": form = subscribe.AddPackForm(request.form) if request.method == "POST" and "stripeToken" not in request.form: if form.validate(): add_packs = int(form.add_packs.data) # Set subscription quantity to desired monitor count payload = {'quantity': add_packs} json_payload = json.dumps(payload) url = app.config[ 'ASSEMBLY_PAYMENTS_URL'] + "/customers/" + user.stripeid print("Making request to %s") % url try: # Get Subscription ID result = requests.get(url=url, headers=headers, verify=True) if result.status_code == 200: rdata = json.loads(result.text) subsid = rdata['subscriptions']['data'][0]['id'] url = url + "/subscriptions/" + subsid print("Making request to %s") % url # Set Quantity try: result = requests.put(url=url, headers=headers, data=json_payload, verify=True) except: print("Critical Error making \ request to ASM Payments") flash( 'An error occured while \ processing the form.', 'danger') else: flash( 'An error occured while \ processing the form.', 'danger') except: print("Critical Error making request to ASM Payments") flash( 'An error occured \ while processing the form.', 'danger') print("Got {0} status code from Assembly".format( result.status_code)) if result.status_code >= 200 and result.status_code <= 299: user.subplans = add_packs # Save user config print("Setting subscription count to \ {0} for user {1}".format(add_packs, user.uid)) subres = user.setSubscription(g.rdb_conn) if subres: newdata = startData(user) data['limit'] = newdata['limit'] data['rlimit'] = newdata['rlimit'] data['acttype'] = newdata['acttype'] data['subplans'] = newdata['subplans'] data['cost'] = newdata['cost'] flash('Subscription successfully modified.', 'success') else: flash('Unknown error modifing subscription.', 'danger') page = render_template(tmpl, data=data, form=form) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def modsub_page(): '''Dashboard Modify Subscription: This will allow a user to modify their subscription and account plan ''' verify = verifyLogin( app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/mod-subscription' data['uid'] = user.uid tmpl = 'member/mod-subscription.html' data['js_bottom'].append('forms/subscribe.js') form = [] # Stripe vs ASM stuff if user.payments == "ASM": headers = { "content-type": "application/json", "Authorization": app.config['ASSEMBLY_PRIVATE_KEY'] } paymenturl = app.config['ASSEMBLY_PAYMENTS_URL'] else: from base64 import b64encode api_key = b64encode(app.config['STRIPE_PRIVATE_KEY']).decode("ascii") headers = { "Authorization": "Basic " + api_key, } paymenturl = app.config['STRIPE_PAYMENTS_URL'] from generalforms import subscribe if data['upgraded'] is False: # Upgrade Users if request.method == "POST" and \ "stripeToken" in request.form and "plan" in request.form: stripeToken = request.form['stripeToken'] plan = request.form['plan'] if stripeToken: result = None monitor = Monitor() payload = { 'email': user.email, 'quantity': monitor.count(user.uid, g.rdb_conn), 'source': stripeToken, 'plan': plan } json_payload = json.dumps(payload) url = paymenturl + "/customers" print ("Making request to %s") % url try: # Send Request to Payment system to create user and subscribe # them to desired plan result = requests.post( url=url, headers=headers, params=payload, verify=True) except: print("Critical Error making request to Payments") flash('There was an error processing \ your card details.', 'danger') print("Got {0} status code from Payments".format( result.status_code)) if result.status_code >= 200 and result.status_code <= 299: rdata = json.loads(result.text) user.stripeid = rdata['id'] user.stripe = stripeToken user.subplans = payload['quantity'] user.subscription = payload['plan'] if "pro_plus" in plan: user.acttype = "proplus" else: user.acttype = "pro" print("Setting UID %s Subscription to: %s") % ( user.uid, user.acttype) subres = user.setSubscription(g.rdb_conn) stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' User Upgrades', 1) if subres: newdata = startData(user) data['limit'] = newdata['limit'] data['rlimit'] = newdata['rlimit'] data['acttype'] = newdata['acttype'] data['subplans'] = newdata['subplans'] data['cost'] = newdata['cost'] data['subscription'] = newdata['subscription'] flash('Subscription successfully created.', 'success') else: flash('Subscription not successfully created.', 'danger') else: flash('Subscription not created got status code: %d' % result.status_code, 'danger') # Increase subscription if data['upgraded']: form = subscribe.AddPackForm(request.form) if request.method == "POST" and "stripeToken" not in request.form: if form.validate(): add_packs = int(form.add_packs.data) # Set subscription quantity to desired monitor count payload = {'quantity': add_packs} json_payload = json.dumps(payload) url = paymenturl + "/customers/" + user.stripeid print("Making request to %s") % url try: # Get Subscription ID result = requests.get( url=url, headers=headers, verify=True) if result.status_code == 200: rdata = json.loads(result.text) subsid = rdata['subscriptions']['data'][0]['id'] url = url + "/subscriptions/" + subsid print("Making request to %s") % url # Set Quantity try: if user.payments == "ASM": result = requests.put( url=url, headers=headers, data=json_payload, verify=True) else: result = requests.post( url=url, headers=headers, params=payload, verify=True) except: print("Critical Error making \ request to ASM Payments") flash('An error occured while \ requesting update to %s.' % url, 'danger') else: flash('An error occured while \ pulling subscription details - %d.' % result.status_code, 'danger') except: print("Critical Error making request to ASM Payments") flash('An error occured \ while processing the form.', 'danger') print("Got {0} status code from Assembly".format( result.status_code)) if result.status_code >= 200 and result.status_code <= 299: user.subplans = add_packs # Save user config print("Setting subscription count to \ {0} for user {1}".format(add_packs, user.uid)) subres = user.setSubscription(g.rdb_conn) if subres: newdata = startData(user) data['limit'] = newdata['limit'] data['rlimit'] = newdata['rlimit'] data['acttype'] = newdata['acttype'] data['subplans'] = newdata['subplans'] data['cost'] = newdata['cost'] flash('Subscription successfully modified.', 'success') else: flash('Unknown error modifing subscription.', 'danger') page = render_template(tmpl, data=data, form=form) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def modsub_page(): '''Dashboard Modify Subscription: This will allow a user to modify their subscription and account plan ''' verify = verifyLogin( app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/mod-subscription' data['uid'] = user.uid tmpl = 'member/mod-subscription.html' data['js_bottom'].append('forms/subscribe.js') form = [] headers = { "content-type": "application/json", "Authorization": app.config['ASSEMBLY_PRIVATE_KEY'] } from generalforms import subscribe if data['acttype'] == "Lite": # Upgrade Users if request.method == "POST" and \ "stripeToken" in request.form and "plan" in request.form: stripeToken = request.form['stripeToken'] plan = request.form['plan'] if stripeToken: result = None monitor = Monitor() payload = { 'email': user.email, 'quantity': monitor.count(user.uid, g.rdb_conn), 'card': stripeToken, 'plan': plan } json_payload = json.dumps(payload) url = app.config['ASSEMBLY_PAYMENTS_URL'] + "/customers" print ("Making request to %s") % url try: # Send Request to Assembly to create user and subscribe # them to desired plan result = requests.post( url=url, headers=headers, data=json_payload, verify=True) except: print("Critical Error making request to ASM Payments") data['msg'] = "There was an error processing your card details" data['error'] = True print( "Got %d status code from Assembly") % result.status_code if result.status_code >= 200 and result.status_code <= 299: rdata = json.loads(result.text) user.stripeid = rdata['id'] user.stripe = stripeToken user.subplans = payload['quantity'] user.subscription = payload['plan'] user.acttype = "pro" print("Setting UID %s Subscription to: %s") % ( user.uid, user.acttype) subres = user.setSubscription(g.rdb_conn) stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' User Upgrades', 1) if subres: newdata = startData(user) data['limit'] = newdata['limit'] data['rlimit'] = newdata['rlimit'] data['acttype'] = newdata['acttype'] data['subplans'] = newdata['subplans'] data['cost'] = newdata['cost'] data['subscription'] = newdata['subscription'] data['msg'] = "Subscription successfully created" data['error'] = False else: data[ 'msg'] = "Subscription not successfully created" data['error'] = True # Increase subscription if data['acttype'] != "Lite": form = subscribe.AddPackForm(request.form) if request.method == "POST" and "stripeToken" not in request.form: if form.validate(): add_packs = int(form.add_packs.data) # Set subscription quantity to desired monitor count payload = {'quantity': add_packs} json_payload = json.dumps(payload) url = app.config[ 'ASSEMBLY_PAYMENTS_URL'] + "/customers/" + user.stripeid print("Making request to %s") % url try: # Get Subscription ID result = requests.get( url=url, headers=headers, verify=True) if result.status_code == 200: rdata = json.loads(result.text) subsid = rdata['subscriptions']['data'][0]['id'] url = url + "/subscriptions/" + subsid print("Making request to %s") % url # Set Quantity try: result = requests.put( url=url, headers=headers, data=json_payload, verify=True) except: data['msg'] = "An error occured while processing the form" data['error'] = True print("Critical Error making request to ASM Payments") else: data['msg'] = "An error occured while processing the form" data['error'] = True except: data['msg'] = "An error occured while processing the form" data['error'] = True print("Critical Error making request to ASM Payments") print( "Got %d status code from Assembly") % result.status_code if result.status_code >= 200 and result.status_code <= 299: user.subplans = add_packs # Save user config print("Setting subscription count to %d for user %s") % (add_packs, user.uid) subres = user.setSubscription(g.rdb_conn) if subres: newdata = startData(user) data['limit'] = newdata['limit'] data['rlimit'] = newdata['rlimit'] data['acttype'] = newdata['acttype'] data['subplans'] = newdata['subplans'] data['cost'] = newdata['cost'] data['msg'] = "Subscription successfully modified" data['error'] = False else: data['msg'] = "Unknown error modifing subscription" data['error'] = True page = render_template(tmpl, data=data, form=form) return page else: return redirect(url_for('user.login_page'))
def addcheck_page(cname): verify = verifyLogin( app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/monitors/' + cname tmpl = 'monitors/' + cname + '.html' data['js_bottom'] = ['monitors/monitorlist.js', 'monitors/base.js', 'monitors/' + cname + '.js'] # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: # Get list of reactions and validate that there are some data['reactions'] = user.getReactions(g.rdb_conn) # Proces the form cform = __import__( "monitorforms." + cname, globals(), locals(), ['CheckForm'], -1) form = cform.CheckForm(request.form) if form.__contains__("timer"): form.timer.choices = data['choices'] reactchoices = [] for key in data['reactions'].keys(): reactchoices.append( (data['reactions'][key]['id'], data['reactions'][key]['name'])) form.reactions.choices = reactchoices if request.method == 'POST': if form.validate(): monitor = Monitor() monitor.name = form.name.data monitor.ctype = cname monitor.uid = user.uid monitor.status = "queued" monitor.url = None tmpdata = {} for item in form.__iter__(): tmpdata[item.name] = item.data monitor.data = tmpdata # Check if the user already exceeds their limit if monitor.count(user.uid, g.rdb_conn) < data['limit']: # Create the monitor if all checks out results = monitor.createMonitor(g.rdb_conn) else: results = "toomany" if results == "exists": print("/dashboard/monitors/{0} - \ Monitor already exists".format(cname)) flash('{0} seems to already exist. \ Try using a different name.'.format( monitor.name), 'danger') elif results is False: print("/dashboard/monitors/{0} - \ Monitor creation failed".format(cname)) flash('Could not create monitor.', 'danger') elif results == 'toomany': stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Too many health checks', 1) flash('You have too many monitors. \ Please upgrade your plan or clean \ up old ones.', 'danger') print("/dashboard/monitors/{0} - \ Monitor creation failed: toomany".format(cname)) else: stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Monitor Added', 1) print("/dashboard/monitors/%s - \ Monitor creation successful") % cname flash('Monitor "{0}" successfully added.'.format( monitor.name), 'success') newmonitor = Monitor() newmonitor.get(results, g.rdb_conn) if newmonitor.uid == user.uid: data['monitor'] = { 'cid': newmonitor.cid, 'name': newmonitor.name, 'uid': newmonitor.uid, 'ctype': newmonitor.ctype, 'url': newmonitor.url, 'data': newmonitor.data } else: print("/dashboard/monitors/{0} - \ Monitor creation failed: Form invalid".format(cname)) flash('Form is not valid.', 'danger') page = render_template(tmpl, data=data, form=form) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def editcheck_page(cname, cid): verify = verifyLogin( app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/edit-monitors/' + cname + "/" + cid tmpl = 'monitors/' + cname + '.html' data['edit'] = True data['js_bottom'] = ['monitors/base.js', 'monitors/' + cname + '.js'] # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: # Get list of reactions and validate that there are some data['reactions'] = user.getReactions(g.rdb_conn) # Proces the form cform = __import__( "monitorforms." + cname, globals(), locals(), ['CheckForm'], -1) form = cform.CheckForm(request.form) oldmonitor = Monitor() oldmonitor.get(cid, g.rdb_conn) if oldmonitor.uid == user.uid: data['monitor'] = { 'cid': oldmonitor.cid, 'name': oldmonitor.name, 'uid': oldmonitor.uid, 'ctype': oldmonitor.ctype, 'url': oldmonitor.url, 'data': oldmonitor.data } # Check if the form contains the timer SelectField if form.__contains__("timer"): form.timer.choices = data['choices'] reactchoices = [] reactdefaults = [] for key in data['reactions'].keys(): reactchoices.append( (data['reactions'][key]['id'], data['reactions'][key]['name'])) if data['reactions'][key]['id'] in \ data['monitor']['data']['reactions']: reactdefaults.append(data['reactions'][key]['id']) form.reactions.choices = reactchoices for item in form.__iter__(): if item.type == "SelectField" or\ item.type == "SelectMultipleField": item.default = data['monitor']['data'][item.name] if request.method == 'POST': if form.validate(): monitor = Monitor() monitor.cid = cid monitor.name = form.name.data monitor.ctype = cname monitor.uid = user.uid monitor.status = "queued" monitor.url = oldmonitor.url tmpdata = {} for item in form.__iter__(): tmpdata[item.name] = item.data if item.type == "SelectField" or\ item.type == "SelectMultipleField": item.default = item.data monitor.data = tmpdata data['monitor'] = { 'cid': monitor.cid, 'name': monitor.name, 'uid': monitor.uid, 'ctype': monitor.ctype, 'url': monitor.url, 'data': monitor.data } reactdefaults = data['monitor']['data']['reactions'] # Check if the user already exceeds their limit if oldmonitor.uid == user.uid: # Create the monitor if all checks out results = monitor.editMonitor(g.rdb_conn) else: results = "NotYours" print("/dashboard/edit-monitors/{0} - \ Monitor edit failed: not users".format(cname)) flash("This Monitor doesn't appear to be yours.", 'danger') if results == "exists": print("/dashboard/edit-monitors/{0} - \ Monitor edit failed: exists".format(cname)) flash('This monitor seems to already exist. \ Try using a different name.', 'danger') elif results is False: print("/dashboard/edit-monitors/{0} - Monitor \ edit failed: unknown reason".format(cname)) flash('Could not edit monitor.', 'danger') elif results == 'toomany': stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Too many health checks', 1) print("/dashboard/edit-monitors/{0} - \ Monitor edit failed: too many".format(cname)) flash('You have too many monitors. \ Please upgrade your plan or clean \ up old ones.', 'danger') else: stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Monitor Added', 1 ) print("/dashboard/edit-monitors/{0} - \ Monitor edit successful").format(cname) flash('Monitor "{0}" successfully edited'.format( monitor.name), 'success') else: print("/dashboard/edit-monitors/{0} - \ Monitor edit failed: Form invalid".format(cname)) flash('Form is not valid.', 'danger') # Process form to display defaults if form.__contains__("timer"): form.timer.default = data['monitor']['data']['timer'] form.reactions.default = reactdefaults form.process() page = render_template(tmpl, data=data, form=form) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))