Exemplo n.º 1
0
def signup():
  ''' User Sign up page: Very basic email + password sign up form that will also login users. '''
  ## Data is used throughout for the jinja2 templates
  data={
    'active': "signup", # Sets the current page
    'loggedin': False # Don't show the logout link
  }

  ## Define the SignupForm
  form = SignupForm(request.form)
  ## Validate and then create userdata
  if request.method == "POST":
    if form.validate():
      ## Take form data
      email = form.email.data
      password = form.password.data
      company = form.company.data
      contact = form.contact.data
      userdata = {
        'username': email,
        'email': email,
        'password': password,
        'company': company,
        'contact': contact
      }

      ## Create user 
      user = User()
      result = user.createUser(userdata, g.rdb_conn)
      ## Check results for success or failure
      if result == "exists":
        data['error'] = True
        data['msg'] = 'User already exists'
      elif result is not False:
        stathat.ez_count(app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' User Signup', 1)
        print("/signup - New user created") 
        cdata = cookies.genCdata(result, app.config['SECRET_KEY'])
        data['loggedin'] = True
        data['msg'] = 'You are signed up'
        data['error'] = False
        ## Build response
        resp = make_response(redirect(url_for('dashboard_page')))
        timeout = int(time.time()) + int(app.config['COOKIE_TIMEOUT'])
        ## Set the cookie secure as best as possible
        resp.set_cookie('loggedin', cdata, expires=timeout, httponly=True)
        return resp
    else:
      stathat.ez_count(app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Failed User Signup', 1)
      print("/signup - Failed user creation") 
      data['msg'] = 'Form is not valid'
      data['error'] = True

  ## Return Signup Page
  return render_template('signup.html', data=data, form=form)
Exemplo n.º 2
0
def signup():
    """
    User Sign up page: Very basic email + password
    sign up form that will also login users.
    """
    # Data is used throughout for the jinja2 templates
    data = {"active": "signup", "loggedin": False}  # Sets the current page  # Don't show the logout link

    # Define the SignupForm
    form = SignupForm(request.form)
    # Validate and then create userdata
    if request.method == "POST":
        if form.validate():
            # Take form data
            email = form.email.data
            password = form.password.data
            company = form.company.data
            contact = form.contact.data
            userdata = {"username": email, "email": email, "password": password, "company": company, "contact": contact}

            # Create user
            user = User()
            user.config = app.config
            result = user.createUser(userdata, g.rdb_conn)
            # Check results for success or failure
            if result == "exists":
                flash("User already exists.", "danger")
            elif result is not False:
                try:
                    stathat.ez_count(app.config["STATHAT_EZ_KEY"], app.config["ENVNAME"] + " User Signup", 1)
                except:
                    pass
                print("/signup - New user created")
                cdata = cookies.genCdata(result, app.config["SECRET_KEY"])
                data["loggedin"] = True
                flash("You are signed up.", "success")

                # Generate confirmation token
                generate_confirmation_token(email, result, time.time())

                # Build response
                resp = make_response(redirect(url_for("member.dashboard_page")))
                timeout = int(time.time()) + int(app.config["COOKIE_TIMEOUT"])
                # Set the cookie secure as best as possible
                resp.set_cookie("loggedin", cdata, expires=timeout, httponly=True)
                return resp
        else:
            stathat.ez_count(app.config["STATHAT_EZ_KEY"], app.config["ENVNAME"] + " False User Signup", 1)
            print("/signup - False user creation")
            flash("Form is not valid.", "danger")

    # Return Signup Page
    return render_template("user/signup.html", data=data, form=form)
Exemplo n.º 3
0
def callStathat(redata, jdata):
    ''' Actually perform the stathat call '''
    if redata['data']['stat_type'] == "count":
        stathat.ez_count(redata['data']['ez_key'], redata['data']['stat_name'],
                         redata['data']['value'])
        line = "stathat: Sent stathat counter for monitor %s" % jdata['cid']
        syslog.syslog(syslog.LOG_INFO, line)
    elif redata['data']['stat_type'] == "value":
        stathat.ez_value(redata['data']['ez_key'], redata['data']['stat_name'],
                         redata['data']['value'])
        line = "stathat: Sent stathat value for monitor %s" % jdata['cid']
        syslog.syslog(syslog.LOG_INFO, line)
    else:
        line = "stathat: Unknown stat type defined in reaction %s" % redata[
            'id']
        syslog.syslog(syslog.LOG_ERR, line)
Exemplo n.º 4
0
def callStathat(redata, jdata, logger):
    ''' Actually perform the stathat call '''
    if redata['data']['stat_type'] == "count":
        stathat.ez_count(redata['data']['ez_key'], redata['data']['stat_name'],
                         redata['data']['value'])
        line = "stathat: Sent stathat counter for monitor %s" % jdata['cid']
        logger.info(line)
    elif redata['data']['stat_type'] == "value":
        stathat.ez_value(redata['data']['ez_key'], redata['data']['stat_name'],
                         redata['data']['value'])
        line = "stathat: Sent stathat value for monitor %s" % jdata['cid']
        logger.info(line)
    else:
        line = "stathat: Unknown stat type defined in reaction %s" % redata[
            'id']
        logger.error(line)
Exemplo n.º 5
0
def callStathat(redata, jdata):
    ''' Actually perform the stathat call '''
    if redata['data']['stat_type'] == "count":
        stathat.ez_count(
            redata['data']['ez_key'],
            redata['data']['stat_name'], redata['data']['value'])
        line = "stathat: Sent stathat counter for monitor %s" % jdata['cid']
        syslog.syslog(syslog.LOG_INFO, line)
    elif redata['data']['stat_type'] == "value":
        stathat.ez_value(
            redata['data']['ez_key'],
            redata['data']['stat_name'], redata['data']['value'])
        line = "stathat: Sent stathat value for monitor %s" % jdata['cid']
        syslog.syslog(syslog.LOG_INFO, line)
    else:
        line = "stathat: Unknown stat type defined in reaction %s" % redata[
            'id']
        syslog.syslog(syslog.LOG_ERR, line)
Exemplo n.º 6
0
def callStathat(redata, jdata, logger):
    ''' Actually perform the stathat call '''
    if redata['data']['stat_type'] == "count":
        stathat.ez_count(
            redata['data']['ez_key'],
            redata['data']['stat_name'], redata['data']['value'])
        line = "stathat: Sent stathat counter for monitor %s" % jdata['cid']
        logger.info(line)
    elif redata['data']['stat_type'] == "value":
        stathat.ez_value(
            redata['data']['ez_key'],
            redata['data']['stat_name'], redata['data']['value'])
        line = "stathat: Sent stathat value for monitor %s" % jdata['cid']
        logger.info(line)
    else:
        line = "stathat: Unknown stat type defined in reaction %s" % redata[
            'id']
        logger.error(line)
Exemplo n.º 7
0
    def get_redirect_url(self, *args, **kwargs):

        # stathat statistic for new passage
        stathat.ez_count('*****@*****.**', 'Passages Created', 1)

        d = date.today() + timedelta(days=2)

        p = Passage.objects.create(
            user=self.request.user,
            passage_data={
                "name": "New Passage",
                "departureDate": d.strftime("%Y-%m-%d"),
                "waypoints": [],
                "estimatedAvgSpeed": 5,
                "timeZone": "America/New_York",
                "mapType": "terrain",
                "zoom": 9,
            }
        )
        return p.get_absolute_url()
Exemplo n.º 8
0
def addreaction_page(rname):
    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/reactions/' + rname
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.config = app.config
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                            Reaction creation failed: exists".format(rname))
                        flash('{0} seems to already exist. Try using a \
                              different name.'.format(reaction.name), 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - Reaction \
                              edit failed: doesn't exist".format(rname))
                        flash('{0} cannot be edited as it does not \
                              exist.'.format(reaction.name), 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited: {0}.'.format(
                            reaction.name), 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited: {0}.'.format(
                            reaction.name), 'danger')
                    elif results == "toomany":
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: too many".format(rname))
                        flash('Could not create reaction: \
                              Too many reactions already created.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction creation successful".format(rname))
                        flash('Reaction "{0}" successfully added.'.format(
                            reaction.name), 'success')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction creation failed: form invalid".format(rname))
                    flash('Form is not valid.', 'success')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Exemplo n.º 9
0
def editreact_page(rname, rid):
    ''' This is a generic edit page for reactions '''
    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/edit-reactions/' + rname + '/' + rid
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js', ]
        data['edit'] = True
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            reaction = Reaction()
            reaction.config = app.config
            # If Edit get information
            reaction.get("rid", rid, g.rdb_conn)
            if reaction.uid == user.uid:
                data['reaction'] = {
                    'rid': reaction.rid,
                    'name': reaction.name,
                    'trigger': reaction.trigger,
                    'frequency': reaction.frequency,
                    'uid': reaction.uid,
                    'rtype': reaction.rtype,
                    'data': reaction.data
                }
            data['selects'] = []
            for item in form.__iter__():
                if item.type == "SelectField" or \
                        item.type == "SelectMultipleField":
                    item.default = data['reaction']['data'][item.name]
            tmpl = 'reactions/create.html'
            if request.method == 'POST':
                if form.validate():
                    reaction2 = Reaction()
                    reaction2.config = app.config
                    reaction2.rid = reaction.rid
                    reaction2.name = form.name.data
                    reaction2.trigger = form.trigger.data
                    reaction2.frequency = form.frequency.data
                    reaction2.lastrun = reaction.lastrun
                    reaction2.uid = user.uid
                    reaction2.rtype = reaction.rtype
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    reaction2.data = tmpdata

                    data['reaction'] = {
                        'rid': reaction2.rid,
                        'name': reaction2.name,
                        'trigger': reaction2.trigger,
                        'frequency': reaction2.frequency,
                        'uid': reaction2.uid,
                        'rtype': reaction2.rtype,
                        'data': reaction2.data
                    }
                    if reaction.uid == user.uid:
                        results = reaction2.editReaction(g.rdb_conn)
                    else:
                        results = False
                        print("/dashboard/reactions/{0} - \
                            Reaction edit failed: not owner".format(rname))
                        flash("It doesn't appear that you own this reaction.",
                              'danger')
                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction seems to already exist. \
                              Try using a different name.', 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction can not be edited \
                              as it does not exist.', 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited.', 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction edit success".format(rname))
                        flash('Reaction "{0}" successfully \
                              added.'.format(reaction2.name), 'danger')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction edit failed: form invalid".format(rname))
                    flash('Form is not valid.', 'danger')
        form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Exemplo n.º 10
0
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'))
Exemplo n.º 11
0
def addreaction_page(rname):
    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/reactions/' + rname
        tmpl = 'reactions/' + rname + '.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__("reactionforms." + rname, globals(), locals(),
                                ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        data[
                            'msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction creation failed: exists"
                        ) % rname
                        data['error'] = True
                    elif results == "edit noexists":
                        data[
                            'msg'] = "This reaction can not be edited as it does not exist: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: doesnt exist"
                        ) % rname
                        data['error'] = True
                    elif results == "edit true":
                        data[
                            'msg'] = "Reaction successfully edited: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit successful"
                        ) % rname
                        data['error'] = False
                    elif results == "edit false":
                        data[
                            'msg'] = "Reaction not successfully edited: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: unknown"
                        ) % rname
                        data['error'] = True
                    elif results == "toomany":
                        data[
                            'msg'] = "Could not create reaction: Too many reactions already created [%d]" % data[
                                'rlimit']
                        print(
                            "/dashboard/reactions/%s - Reaction creation failed: too many"
                        ) % rname
                        data['error'] = True
                    elif results is False:
                        data['msg'] = "Could not create reaction"
                        print(
                            "/dashboard/reactions/%s - Reaction creation failed: unknown"
                        ) % rname
                        data['error'] = True
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        data[
                            'msg'] = 'Reaction "%s" successfully added' % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction creation successful"
                        ) % rname
                        data['error'] = False
                else:
                    data['msg'] = "Form is not valid"
                    print(
                        "/dashboard/reactions/%s - Reaction creation failed: form invalid"
                    ) % rname
                    data['error'] = True

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Exemplo n.º 12
0
def editreact_page(rname, rid):
    ''' This is a generic edit page for reactions '''
    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-reactions/' + rname + '/' + rid
        tmpl = 'reactions/index.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        data['edit'] = True
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            reform = __import__("reactionforms." + rname, globals(), locals(),
                                ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            reaction = Reaction()
            # If Edit get information
            reaction.get("rid", rid, g.rdb_conn)
            if reaction.uid == user.uid:
                data['reaction'] = {
                    'rid': reaction.rid,
                    'name': reaction.name,
                    'trigger': reaction.trigger,
                    'frequency': reaction.frequency,
                    'uid': reaction.uid,
                    'rtype': reaction.rtype,
                    'data': reaction.data
                }
            data['selects'] = []
            for item in form.__iter__():
                if item.type == "SelectField" or \
                        item.type == "SelectMultipleField":
                    item.default = data['reaction']['data'][item.name]
            tmpl = 'reactions/' + rname + '.html'
            if request.method == 'POST':
                if form.validate():
                    reaction2 = Reaction()
                    reaction2.rid = reaction.rid
                    reaction2.name = form.name.data
                    reaction2.trigger = form.trigger.data
                    reaction2.frequency = form.frequency.data
                    reaction2.lastrun = reaction.lastrun
                    reaction2.uid = user.uid
                    reaction2.rtype = reaction.rtype
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    reaction2.data = tmpdata

                    data['reaction'] = {
                        'rid': reaction2.rid,
                        'name': reaction2.name,
                        'trigger': reaction2.trigger,
                        'frequency': reaction2.frequency,
                        'uid': reaction2.uid,
                        'rtype': reaction2.rtype,
                        'data': reaction2.data
                    }
                    if reaction.uid == user.uid:
                        results = reaction2.editReaction(g.rdb_conn)
                    else:
                        results = False
                        data[
                            'msg'] = "It doesn't appear that you own this reaction"
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: not owner"
                        ) % rname
                        data['error'] = True
                    if results == "exists":
                        data[
                            'msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: exists"
                        ) % rname
                        data['error'] = True
                    elif results == "edit noexists":
                        data[
                            'msg'] = "This reaction can not be edited as it does not exist: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: exists"
                        ) % rname
                        data['error'] = True
                    elif results == "edit true":
                        data[
                            'msg'] = "Reaction successfully edited: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit successful"
                        ) % rname
                        data['error'] = False
                    elif results == "edit false":
                        data[
                            'msg'] = "Reaction not successfully edited: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: unknown"
                        ) % rname
                        data['error'] = True
                    elif results is False:
                        data['msg'] = "Could not create reaction"
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: unknown"
                        ) % rname
                        data['error'] = True
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        data[
                            'msg'] = 'Reaction "%s" successfully added' % reaction2.name
                        print("/dashboard/reactions/%s - Reaction edit success"
                              ) % rname
                        data['error'] = False
                else:
                    data['msg'] = "Form is not valid"
                    print(
                        "/dashboard/reactions/%s - Reaction edit failed: form invalid"
                    ) % rname
                    data['error'] = True
        form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Exemplo n.º 13
0
def signup():
    '''
    User Sign up page: Very basic email + password
    sign up form that will also login users.
    '''
    # Data is used throughout for the jinja2 templates
    data = {
        'active': "signup",  # Sets the current page
        'loggedin': False  # Don't show the logout link
    }

    # Define the SignupForm
    form = SignupForm(request.form)
    # Validate and then create userdata
    if request.method == "POST":
        if form.validate():
            # Take form data
            email = form.email.data
            password = form.password.data
            company = form.company.data
            contact = form.contact.data
            userdata = {
                'username': email,
                'email': email,
                'password': password,
                'company': company,
                'contact': contact
            }

            # Create user
            user = User()
            user.config = app.config
            result = user.createUser(userdata, g.rdb_conn)
            # Check results for success or failure
            if result == "exists":
                flash('User already exists.', 'danger')
            elif result is not False:
                try:
                    stathat.ez_count(
                        app.config['STATHAT_EZ_KEY'],
                        app.config['ENVNAME'] + ' User Signup', 1)
                except:
                    pass
                print("/signup - New user created")
                cdata = cookies.genCdata(result, app.config['SECRET_KEY'])
                data['loggedin'] = True
                flash('You are signed up.', 'success')

                # Generate confirmation token
                generate_confirmation_token(email, result, time.time())

                # Build response
                resp = make_response(redirect(url_for('member.dashboard_page')))
                timeout = int(time.time()) + int(app.config['COOKIE_TIMEOUT'])
                # Set the cookie secure as best as possible
                resp.set_cookie(
                    'loggedin', cdata, expires=timeout, httponly=True)
                return resp
        else:
            stathat.ez_count(
                app.config['STATHAT_EZ_KEY'],
                app.config['ENVNAME'] + ' False User Signup', 1)
            print("/signup - False user creation")
            flash('Form is not valid.', 'danger')

    # Return Signup Page
    return render_template('user/signup.html', data=data, form=form)
Exemplo n.º 14
0
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'))
Exemplo n.º 15
0
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'))
Exemplo n.º 16
0
def getTime():
    now = datetime.now()
    return now.strftime("%H:%M:%S.%f")


# Do the work
# ------------------------------------------------------------------

# Give Broker time to wake up
time.sleep(5)

while True:
    jdata = zrecv.recv_json()
    # Log that we got a message
    stat = "[%s] Checks received by workers" % config['envname']
    stathat.ez_count(config['stathat_ez_key'], stat, 1)
    logger.debug("Got message for monitor %s from broker" % jdata['cid'])
    # Load health check module and run it
    monitor = __import__("checks." + jdata['ctype'], globals(), locals(),
                         ['check'], -1)
    result = monitor.check(jdata=jdata, logger=logger)
    if result is True:
        # Log it
        stat = "[%s] True Checks" % config['envname']
        stathat.ez_count(config['stathat_ez_key'], stat, 1)
        logger.info("Health check %s for monitor %s is True" %
                    (jdata['ctype'], jdata['cid']))
        jdata['check'] = {'status': 'true', 'method': 'automatic'}
        jdata['time_tracking']['worker'] = time.time()
        # Send success to sink
        ztext = json.dumps(jdata)
Exemplo n.º 17
0
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'))
Exemplo n.º 18
0
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'))
Exemplo n.º 19
0
def signup_signal_callback(sender, **kwargs):
    # stathat statistic for new registrations
    stathat.ez_count('*****@*****.**', 'Users Registered', 1)
Exemplo n.º 20
0
def addreaction_page(rname):
    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/reactions/' + rname
        tmpl = 'reactions/' + rname + '.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        data['msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction creation failed: exists") % rname
                        data['error'] = True
                    elif results == "edit noexists":
                        data['msg'] = "This reaction can not be edited as it does not exist: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction edit failed: doesnt exist") % rname
                        data['error'] = True
                    elif results == "edit true":
                        data['msg'] = "Reaction successfully edited: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction edit successful") % rname
                        data['error'] = False
                    elif results == "edit false":
                        data['msg'] = "Reaction not successfully edited: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction edit failed: unknown") % rname
                        data['error'] = True
                    elif results == "toomany":
                        data['msg'] = "Could not create reaction: Too many reactions already created [%d]" % data['rlimit']
                        print("/dashboard/reactions/%s - Reaction creation failed: too many") % rname
                        data['error'] = True
                    elif results is False:
                        data['msg'] = "Could not create reaction"
                        print("/dashboard/reactions/%s - Reaction creation failed: unknown") % rname
                        data['error'] = True
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        data['msg'] = 'Reaction "%s" successfully added' % reaction.name
                        print("/dashboard/reactions/%s - Reaction creation successful") % rname
                        data['error'] = False
                else:
                    data['msg'] = "Form is not valid"
                    print("/dashboard/reactions/%s - Reaction creation failed: form invalid") % rname
                    data['error'] = True

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Exemplo n.º 21
0
def getTime():
    now = datetime.now()
    return now.strftime("%H:%M:%S.%f")


# Do the work
# ------------------------------------------------------------------

# Give Broker time to wake up
time.sleep(5)

while True:
    jdata = zrecv.recv_json()
    # Log that we got a message
    stat = "[%s] Checks received by workers" % config['envname']
    stathat.ez_count(config['stathat_ez_key'], stat, 1)
    logger.debug("Got message for monitor %s from broker" % jdata['cid'])
    # Load health check module and run it
    monitor = __import__(
        "checks." + jdata['ctype'], globals(), locals(), ['check'], -1)
    result = monitor.check(jdata=jdata, logger=logger)
    if result is True:
        # Log it
        stat = "[%s] True Checks" % config['envname']
        stathat.ez_count(config['stathat_ez_key'], stat, 1)
        logger.info("Health check %s for monitor %s is True" % (
            jdata['ctype'], jdata['cid']))
        jdata['check'] = {'status': 'true',
                          'method': 'automatic'}
        jdata['time_tracking']['worker'] = time.time()
        # Send success to sink
Exemplo n.º 22
0
def editreact_page(rname, rid):
  ''' This is a generic edit page for reactions '''
  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-reactions/' + rname + '/' + rid
    tmpl = 'reactions/index.html'
    data['js_bottom'] = [ 'reactions/base.js', 'reactions/' + rname + '.js' ]
    data['edit'] = True
    ## Check Users Status
    if user.status != "active":
      data['url'] = '/dashboard/mod-subscription'
      tmpl = 'mod-subscription.html'
    else:
      reform = __import__("reactionforms." + rname, globals(), locals(), ['ReactForm'], -1)
      form = reform.ReactForm(request.form)
      reaction = Reaction()
      ## If Edit get information
      reaction.get("rid", rid, g.rdb_conn)
      if reaction.uid == user.uid:
        data['reaction'] = {
          'rid': reaction.rid,
          'name': reaction.name,
          'trigger': reaction.trigger,
          'frequency': reaction.frequency,
          'uid': reaction.uid,
          'rtype': reaction.rtype,
          'data': reaction.data
        }
      data['selects'] = []
      for item in form.__iter__():
        if item.type == "SelectField" or item.type == "SelectMultipleField":
          item.default = data['reaction']['data'][item.name]
      tmpl = 'reactions/' + rname + '.html'
      if request.method == 'POST':
        if form.validate():
          reaction2 = Reaction()
          reaction2.rid = reaction.rid
          reaction2.name = form.name.data
          reaction2.trigger = form.trigger.data
          reaction2.frequency = form.frequency.data
          reaction2.uid = user.uid
          reaction2.rtype = reaction.rtype
          tmpdata = {}
          for item in form.__iter__():
            tmpdata[item.name] = item.data
            if item.type == "SelectField" or item.type == "SelectMultipleField":
              item.default = item.data
          reaction2.data = tmpdata

          data['reaction'] = {
            'rid': reaction2.rid,
            'name': reaction2.name,
            'trigger': reaction2.trigger,
            'frequency': reaction2.frequency,
            'uid': reaction2.uid,
            'rtype': reaction2.rtype,
            'data': reaction2.data
          }
          if reaction.uid == user.uid:
            results = reaction2.editReaction(g.rdb_conn)
          else:
            results = False
            data['msg'] = "I Doesn't appear that you own this reaction"
            print("/dashboard/reactions/%s - Reaction edit failed: not owner") % rname
            data['error'] = True
          if results == "exists":
            data['msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit failed: exists") % rname
            data['error'] = True
          elif results == "edit noexists":
            data['msg'] = "This reaction can not be edited as it does not exist: %s" % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit failed: exists") % rname
            data['error'] = True
          elif results == "edit true":
            data['msg'] = "Reaction successfully edited: %s" % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit successful") % rname
            data['error'] = False
          elif results == "edit false":
            data['msg'] = "Reaction not successfully edited: %s" % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit failed: unknown") % rname
            data['error'] = True 
          elif results == False:
            data['msg'] = "Could not create reaction"
            print("/dashboard/reactions/%s - Reaction edit failed: unknown") % rname
            data['error'] = True
          else:
            stathat.ez_count(app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Reaction Added', 1)
            data['msg'] = 'Reaction "%s" successfully added' % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit success") % rname
            data['error'] = False
        else:
          data['msg'] = "Form is not valid"
          print("/dashboard/reactions/%s - Reaction edit failed: form invalid") % rname
          data['error'] = True
    form.process()
    page = render_template(tmpl, data=data, form=form)
    return page
  else:
    return redirect(url_for('login_page')) 
Exemplo n.º 23
0
def addreaction_page(rname):
    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/reactions/' + rname
        tmpl = 'reactions/' + rname + '.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                            Reaction creation failed: exists".format(rname))
                        flash('{0} seems to already exist. Try using a \
                              different name.'.format(reaction.name), 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - Reaction \
                              edit failed: doesn't exist".format(rname))
                        flash('{0} cannot be edited as it does not \
                              exist.'.format(reaction.name), 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited: {0}.'.format(
                            reaction.name), 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited: {0}.'.format(
                            reaction.name), 'danger')
                    elif results == "toomany":
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: too many".format(rname))
                        flash('Could not create reaction: \
                              Too many reactions already created.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction creation successful".format(rname))
                        flash('Reaction "{0}" successfully added.'.format(
                            reaction.name), 'success')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction creation failed: form invalid".format(rname))
                    flash('Form is not valid.', 'success')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Exemplo n.º 24
0
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'))
Exemplo n.º 25
0
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'))