示例#1
0
def save_comment(username):
    password = str(request.form['password'])
    site = str(request.form['site'])
    comment = str(request.form['comment'])

    params = {
        'username': username,
        'password': password,
        'site': site,
    }

    user_password = UserPassword.fetch(db, username, password)
    new = user_password.getComment(site) is None

    if new:
        params['message'] = 'Your new site was saved.'
    else:
        params['message'] = 'Your comment was saved.'

    user_password.setSite(site, comment)

    params['comment'] = user_password.getComment(site)
    params['result'] = generatePassword(password, site)

    log_event('save-comment', {'username': username, 'new': new})

    return render_template('private/password.htm', **params)
示例#2
0
def add_password(username):
  password = str(request.form['password'])
  confirm_password = str(request.form['confirm_password'])
  existing_password = str(request.form['existing_password'])
  
  params = {
    'username': username,
    'password': password,
  }

  user = User.fetch(db, username)

  error = None

  if not user.getPassword(existing_password):
    error = "The existing password you entered was not found."

  if error is None and password != confirm_password:
    error = "The password you entered to confirm was not the same as entered originally."

  if error:
    return render_template('private/unknown.htm', error=error, **params)
    

  log_event('add-password', {
    'username': username,
    })

  user.addPasswordHash(createHash(password))

  params = {
      'username': username,
      'message': 'Your new password is now available.'
  }
  return render_template('private/index.htm', **params)
示例#3
0
def save_comment(username):
  password = str(request.form['password'])
  site = str(request.form['site'])
  comment = str(request.form['comment'])
  
  params = {
    'username': username,
    'password': password,
    'site': site,
  }

  user_password = UserPassword.fetch(db, username, password)
  new = user_password.getComment(site) is None

  if new:
    params['message'] = 'Your new site was saved.'
  else:
    params['message'] = 'Your comment was saved.'

  user_password.setSite(site, comment)

  params['comment'] = user_password.getComment(site)
  params['result'] = generatePassword(password, site)

  log_event('save-comment', {
    'username': username,
    'new': new
    })

  return render_template('private/password.htm', **params)
示例#4
0
def user_post(username):
    password = str(request.form['password'])
    site = str(request.form['site'])

    params = {
        'username': username,
        'password': password,
        'site': site,
    }

    user_password = UserPassword.fetch(db, username, password)

    if not user_password:
        log_event('password-unknown', {
            'username': username,
        })
        return render_template('private/unknown.htm', **params)

    comment = user_password.getComment(site)
    if comment is not None:
        params['comment'] = comment

    params['result'] = generatePassword(password, site)

    log_event('user-generate', {
        'username': username,
        'new': (comment is not None)
    })
    return render_template('private/password.htm', **params)
示例#5
0
def user_post(username):
  password = str(request.form['password'])
  site = str(request.form['site'])
  
  params = {
    'username': username,
    'password': password,
    'site': site,
  }

  user_password = UserPassword.fetch(db, username, password)

  if not user_password:
    log_event('password-unknown', {
      'username': username,
      })
    return render_template('private/unknown.htm', **params)
    
  comment = user_password.getComment(site)
  if comment is not None:
    params['comment'] = comment

  params['result'] = generatePassword(password, site)

  log_event('user-generate', {
    'username': username,
    'new': (comment is not None)
    })
  return render_template('private/password.htm', **params)
示例#6
0
def add_password(username):
    password = str(request.form['password'])
    confirm_password = str(request.form['confirm_password'])
    existing_password = str(request.form['existing_password'])

    params = {
        'username': username,
        'password': password,
    }

    user = User.fetch(db, username)

    error = None

    if not user.getPassword(existing_password):
        error = "The existing password you entered was not found."

    if error is None and password != confirm_password:
        error = "The password you entered to confirm was not the same as entered originally."

    if error:
        return render_template('private/unknown.htm', error=error, **params)

    log_event('add-password', {
        'username': username,
    })

    user.addPasswordHash(createHash(password))

    params = {
        'username': username,
        'message': 'Your new password is now available.'
    }
    return render_template('private/index.htm', **params)
示例#7
0
def public_post(name=None):

  password = str(request.form['password'])
  site = str(request.form['site'])
  
  result = generatePassword(password, site)
  params = {
    'password': password,
    'hash': createHash(password),
    'site': site,
    'result': result
  }

  log_event('public-generate')
  return render_template('public/password.htm', **params)
示例#8
0
def before_request():
    # Redirect to SSL
    if config.ssl and request.headers.get('X-Forwarded-Proto', None) == 'http':
        url = config.base_url + request.path
        return redirect(url, 301)

    # Ensure we have a unique id
    if 'id' in request.cookies:
        distinct_id = request.cookies['id']
    else:
        distinct_id = uuid.uuid4().hex

    set_distinct_id(distinct_id)

    # Log a pageview
    log_event('pageview')
示例#9
0
def user_get_sites(username):
    password = str(request.form['password'])

    user = User.fetch(db, username)

    sites = user and user.getSites(password)

    log_event('get-sites', {
        'username': username,
        'found': (sites is not None)
    })

    if sites is None:
        return '{"result": false, "sites": []}'
    else:
        return json.dumps({"result": True, "sites": sites})
示例#10
0
def before_request():
  # Redirect to SSL
  if config.ssl and request.headers.get('X-Forwarded-Proto', None) == 'http':
    url = config.base_url + request.path
    return redirect(url, 301)

  # Ensure we have a unique id
  if 'id' in request.cookies:
    distinct_id = request.cookies['id']
  else:
    distinct_id = uuid.uuid4().hex

  set_distinct_id(distinct_id)

  # Log a pageview
  log_event('pageview')
示例#11
0
def user_get_sites(username):
  password = str(request.form['password'])

  user = User.fetch(db, username)

  sites = user and user.getSites(password)

  log_event('get-sites', {
    'username': username,
    'found': (sites is not None)
    })

  if sites is None:
    return '{"result": false, "sites": []}'
  else:
    return json.dumps({"result": True, "sites": sites})
示例#12
0
def signup():
  hash = str(request.form['hash'])
  site = str(request.form['site'])
  username = str(request.form['username'])
  
  error = None

  if User.fetch(db, username):
    error = "The username you selected is taken."
  elif not re.match(r'^[a-z]+$', username):
    error = 'Your username can only be made of lowercase letters'
  elif username in config.reserved:
    error = 'Sorry, the username you have selected is reserved'

  if error:
    params = {
      'hash': hash,
      'site': site,
      'new_username': username,
      'error': error
    }
    return render_template('public/password.htm', **params)
  else:
    db.hset('signups', username, json.dumps({
        'hash': hash,
        'site': site
      }))

    log_event('request-signup', {
      'username': username
      })

    return redirect((config.paypal_url + '?cmd=_xclick' + \
        '&item_name=Signup+for+password.ly:+{username}' + \
        '&item_number={username}&amount={price}&business={email}' + \
        '&custom={username}' + \
        '&currency_code=USD' + \
        '&notify_url={ipn}' + \
        '&cancel_return=http://password.ly/paypal/cancel' + \
        '&return=http://password.ly/{username}').format(
          username=username,
          email=config.paypal_email,
          price=config.price,
          ipn=config.ipn_url
        ))
示例#13
0
    def delete(self, table: str, primary_key: str):
        """
        Delete row with primary key.

        Args:
            table (str): Name of table to change.
            primary_key (str): Primary key of row to delete.

        Returns:
            ResultSet: Response of execution of deletion.
        """
        prepared = self.session.prepare(
            f"DELETE FROM {TABLE_NAMES['users']} WHERE {TABLE_FORMAT[table][0]}=?"
        )
        response = self.session.execute(prepared, [primary_key])
        log_event(f"Deleted {TABLE_FORMAT[table][0]}: {primary_key}",
                  module=MODULE)
        return response
示例#14
0
def ipn():
  request.parameter_storage_class = ImmutableOrderedMultiDict

  # Store any/all ipn requests for future
  db.rpush('ipn', json.dumps(request.form))
  log_event('ipn', request.form)

  # Fetch details from request
  username = str(request.form['item_number'])

  # Double check all the details are correct
  if request.form['receiver_email'] != config.paypal_email:
    return 'Payment was not sent to correct email address'
  elif request.form['payment_status'] != 'Completed':
    return 'Payment status was not completed'
  elif request.form['mc_currency'] != 'USD':
    return 'Payment was not in USD'
  elif request.form['mc_gross'] != ('%.2f' % config.price):
    return 'Payment was not for the correct amount'


  # Validate that the actual request is correct
  validate_url = config.paypal_url + '?cmd=_notify-validate'

  values = request.form
  for x, y in values.iteritems():
    validate_url += "&{x}={y}".format(x=x,y=y)

  print 'Validating IPN using {url}'.format(url=validate_url)

  result = requests.get(validate_url)

  if result.text == 'VERIFIED':
    print "PayPal transaction was verified successfully."

    # Everything okay, actually perform the signup
    log_event('signup-complete', {"username": username})
    User.signup(db, username)
  else:
    print 'Paypal IPN string did not validate'

  return result.text
示例#15
0
    def insert(self, table: str, primary_key: str, data):
        """
        Insert data into table.

        Args:
            table (str): name of table to insert to.
            primary_key (str): Primary Key of data.
            data (dict): Data to insert.

        Returns:
            ResultSet: Response of execution of insertion.
        """
        response = self.session.execute(
            f"INSERT INTO {TABLE_NAMES[table]} ({', '.join(data)}) VALUES ({'%s, ' * 2 + '%s'})",
            list(data.values()))
        updated_data_string = ', '.join(f'{name}: {value}'
                                        for name, value in data.items())
        log_event(f"Inserted {table[:-1]} ({updated_data_string})",
                  module=MODULE)
        return response
示例#16
0
    def __init__(self):
        secure_bundle_path = f'{os.path.dirname(os.path.realpath(__file__))}/secure-connect-life-bot-db.zip'
        cloud_config = {'secure_connect_bundle': secure_bundle_path}
        auth_provider = PlainTextAuthProvider(config.DATASTAX_CLIENT_ID,
                                              config.DATASTAX_CLIENT_SECRET)
        cluster = Cluster(cloud=cloud_config, auth_provider=auth_provider)
        self.session = cluster.connect(KEYSPACE)
        db_version = self.session.execute(
            'select release_version from system.local').one()
        if db_version:
            log_event(f'accessing database version: {db_version[0]}',
                      module=MODULE)
        else:
            log_event('Could not find Version', module=MODULE)

        # create tables if not there
        self.session.execute(f"""
            CREATE TABLE IF NOT EXISTS {KEYSPACE}.{TABLE_NAMES['users']} (
                    username text PRIMARY KEY,
                    firstname text,
                    lastname text
                );
            """)
        self.session.execute(f"""
            CREATE TABLE IF NOT EXISTS {KEYSPACE}.{TABLE_NAMES['budgets']} (
                    itemid text PRIMARY KEY,
                    total float,
                    purchases text
                );
            """)
        log_event('Loaded users and budgets tables', module=MODULE)
示例#17
0
def user_sync(username):
  password = str(request.form['password'])

  user = User.fetch(db, username)
  user_password = user.getPassword(password)

  if not user_password:
    log_event('sync-fail', {'username': username})

    return '{"result": false, "sites": {}}'

  # Sync theirs into ours (where we don't have anything)
  theirs = json.loads(request.form['sites'])
  ours = user_password.getAllComments()

  for site, comment in theirs.items():
    if not site in ours:
      user_password.setSite(site, comment)
      ours[site] = comment

  log_event('sync', {'username': username})
  return json.dumps({"result": True, "sites": ours})
示例#18
0
def user_sync(username):
    password = str(request.form['password'])

    user = User.fetch(db, username)
    user_password = user.getPassword(password)

    if not user_password:
        log_event('sync-fail', {'username': username})

        return '{"result": false, "sites": {}}'

    # Sync theirs into ours (where we don't have anything)
    theirs = json.loads(request.form['sites'])
    ours = user_password.getAllComments()

    for site, comment in theirs.items():
        if not site in ours:
            user_password.setSite(site, comment)
            ours[site] = comment

    log_event('sync', {'username': username})
    return json.dumps({"result": True, "sites": ours})
示例#19
0
def test_event():
  log_event('test', {'a': 1, 'c': 3, 'e': 'eee'})
  return 'Event logged.'
示例#20
0
 def test_log_event(self, mock_print):
     util.log_event('hello', module='connected_database')
     mock_print.assert_called_with('[connected_database | 00:00:00] hello')
     util.log_event('hello')
     mock_print.assert_called_with('[00:00:00] hello')
示例#21
0
def test_event():
    log_event('test', {'a': 1, 'c': 3, 'e': 'eee'})
    return 'Event logged.'