Ejemplo n.º 1
0
    def run(self, name, backend):

        # Validate the parameters
        form = AddAccountForm(name=name, backend=backend)
        if not form.validate():
            self.err(**form.errors)
            return

        # Ask the user for the backend configuration options
        backend = Backend.get_backend(backend)
        config = {'backend': form.data['backend']}
        for field in backend.config_form():
            self.out((field.label.text, 'blue'))
            value = input('> ').strip()
            if value:
                config[field.name] = value

        # Validate the users configuration
        result = backend.validate_config(**config)
        if not result[0]:
            self.err('Invalid backend config:', **result[1])
            return

        # Create the new account
        account = Account(name=form.data['name'], backend=config)
        account.insert()

        self.out(('Account added: {0}'.format(account.api_key), 'bold_green'))
Ejemplo n.º 2
0
def test_rename_account(capsys, app, test_accounts):
    getme = Account.one(Q.name == 'getme').api_key

    # Generate a new API key for an account
    RenameAccount().run('getme', 'new_getme')

    # Check the account has been renamed
    new_getme = Account.one(Q.name == 'new_getme').api_key
    assert new_getme == getme

    # Check the output is as expected
    assert 'Account renamed: new_getme' == capsys.readouterr()[0].strip()
Ejemplo n.º 3
0
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    account = Account.login(username, password)
    if account:
        account.user_key = Account.random_api_key()
        account.save()
        return jsonify({
            'session_id': account.user_key,
            'username': account.username
        })
    return jsonify({'session_id': None, 'username': ""})
Ejemplo n.º 4
0
    def run(self):

        # Confirm the drop
        if not self.confirm('Enter the following string to confirm drop', \
                    'hangar51'):
            return

        # Delete all accounts, assets and files
        accounts = Account.many()
        for account in accounts:
            account.purge()

        # Drop the collections
        Asset.get_collection().drop()
        Account.get_collection().drop()
Ejemplo n.º 5
0
def test_generate_new_api_key(capsys, app, test_accounts):
    # Find an existing account change the API key for
    old_api_key = Account.one(Q.name == 'getme').api_key

    # Generate a new API key for an account
    GenerateNewAPIKey().run('getme')

    # Check a new API key has been generated
    new_api_key = Account.one(Q.name == 'getme').api_key
    assert new_api_key
    assert new_api_key != old_api_key

    # Check the output is as expected
    assert 'New key generated: {0}'.format(new_api_key) \
            == capsys.readouterr()[0].strip()
Ejemplo n.º 6
0
    def run(self, q=''):

        # If `q` is specified we filter the list of accounts to only accounts
        # with names that contain the value of `q`.
        filter = {}
        if q:
            filter = Q.name == re.compile(re.escape(q), re.I)

        # Get the list of accounts
        accounts = Account.many(filter, sort=[('name', ASC)])

        # Print a list of accounts
        output = []

        if q:
            output.append(
                ("Accounts matching '{0}' ({1}):".format(q, len(accounts)),
                 'underline_bold_blue'))
        else:
            output.append(('Accounts ({0}):'.format(len(accounts)),
                           'underline_bold_blue'))

        for account in accounts:
            output.append(('- {name} (using {backend})'.format(
                name=account.name,
                backend=account.backend.get('backend', 'unknown')), 'blue'))

        self.out(*output)
Ejemplo n.º 7
0
    def run(self, name):

        # Validate the parameters
        form = ViewAccountForm(name=name)
        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to view
        account = Account.one(Q.name == form.data['name'])

        # Output details of the account
        output = [("About '{0}':".format(account.name), 'underline_bold_blue')]

        pairs = [('created', account.created), ('modified', account.modified),
                 ('assets', Asset.count(Q.account == account)),
                 ('api_key', account.api_key),
                 ('backend', account.backend.get('backend', 'unknown'))]

        for key in sorted(account.backend.keys()):
            if key == 'backend':
                continue
            pairs.append(('> ' + key, account.backend[key]))

        # Find the longest key so we pad/align values
        width = sorted([len(p[0]) for p in pairs])[-1] + 2

        for pair in pairs:
            pair_str = '- {key:-<{width}} {value}'.format(key=pair[0].ljust(
                width, '-'),
                                                          value=pair[1],
                                                          width=width)
            output.append((pair_str, 'blue'))

        self.out(*output)
Ejemplo n.º 8
0
def addnew():
    current_username = get_jwt_identity()
    if isadmin(current_username):
        if request.method == 'POST':
            data = request.json
            acc = Account(data['account_number'], data['firstname'],
                          data['lastname'], data['gender'], data['age'],
                          data['email'], data['city'], data['address'],
                          data['state'], data['employer'], data['balance'])
            accTbl = db.accounts
            result = accTbl.insert(acc.tojson())
            if result.inserted_id:
                return jsonify({'msg': 'insert successed'}), 201
            else:
                return jsonify({'msg': 'insert failed'}), 400
    else:
        return jsonify({"msg": 'Access permission denied'}), 400
Ejemplo n.º 9
0
def update(id):
    current_username = get_jwt_identity()
    if isadmin(current_username):
        if request.method == 'PUT':
            data = request.json
            acc = Account(data['account_number'], data['firstname'],
                          data['lastname'], data['gender'], data['age'],
                          data['email'], data['city'], data['address'],
                          data['state'], data['employer'], data['balance'])
            accTbl = db.accounts
            result = accTbl.update_one({"account_number": int(id)},
                                       {"$set": acc.tojson()})
            if result.matched_count == 1:
                return jsonify({'msg': 'update successed'}), 201
            else:
                return jsonify({'msg': 'update failed'}), 400
    else:
        return jsonify({"msg": 'Access permission denied'}), 400
Ejemplo n.º 10
0
def test_delete_account(capsys, app, test_accounts):
    # Delete an account
    DeleteAccount().run('getme')

    # Check the output is as expected
    assert 'Account deleted' == capsys.readouterr()[0].strip()

    # Check there is no longer an account for 'getme'
    getme = Account.one(Q.name == 'getme')
    assert getme is None
Ejemplo n.º 11
0
    def add_variation(self, f, im, name, ops):
        """Add a variation to the asset"""
        from models.accounts import Account

        # Make sure we have access to the associated account frame
        if not isinstance(self.account, Account):
            self.account = Account.one(Q._id == self.account)

        # Transform the original image to generate the variation
        vim = None
        if im.format.lower() == 'gif' and im.is_animated:
            # By-pass transforms for animated gifs
            fmt = {'ext': 'gif', 'fmt': 'gif'}

        else:
            # Transform the image based on the variation
            vim = im.copy()
            vim, fmt = Variation.transform_image(vim, ops)

            # Prepare the variation file for storage
            f = io.BytesIO()
            vim.save(f, **fmt)
            f.seek(0)

        # Add the variation to the asset
        variation = Variation(name=name,
                              ext=fmt['ext'],
                              meta={
                                  'length': get_file_length(f),
                                  'image': {
                                      'mode': (vim or im).mode,
                                      'size': (vim or im).size
                                  }
                              })

        # Set a version
        variation.version = generate_uid(3)
        while self.get_variation(name, variation.version):
            variation.version = generate_uid(3)

        # Store the variation
        variation.store_key = Variation.get_store_key(self, variation)
        backend = self.account.get_backend_instance()
        backend.store(f, variation.store_key)

        # We use the $push operator to store the variation to prevent race
        # conditions if multiple processes attempt to update the assets
        # variations at the same time.
        self.get_collection().update(
            {'_id': self._id}, {'$push': {
                'variations': variation._document
            }})

        return variation
Ejemplo n.º 12
0
def test_add_account(capsys, app):
    # Add a new account
    responses = ['tests/data/assets']
    with mock.patch.object(builtins, 'input', mock_input(responses)):
        AddAccount().run('test', 'local')

    # Check the output is as expected
    account = Account.one()
    assert 'Account added: {0}'.format(account.api_key) == \
        capsys.readouterr()[0].strip().split('\n')[-1]

    # Check the account was created correctly
    assert account.name == 'test'
    assert account.backend == json.load(open('tests/data/local.cfg'))
    assert account.api_key
Ejemplo n.º 13
0
    def wrapper(*args, **kwargs):

        api_key = request.values.get('api_key')
        if not api_key:
            return fail('`api_key` not specified.')

        # Find the account
        account = Account.one(Q.api_key == api_key.strip())
        if not account:
            return fail('Not a valid `api_key`.')

        # Set the account against the global context
        g.account = account

        return func(*args, **kwargs)
Ejemplo n.º 14
0
    def run(self, name):

        # Validate the parameters
        form = ConfigAccountBackendForm(name=name)
        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to be configured
        account = Account.one(Q.name == form.data['name'])

        # Let the user know to use dash to clear existing values
        self.out(('* Enter dash (-) to clear the existing value',
                  'underline_bold_blue'))

        # Ask the user for the backend configuration options
        backend = Backend.get_backend(account.backend['backend'])
        config = {'backend': account.backend['backend']}
        for field in backend.config_form():

            # Request the value
            self.out((field.label.text, 'blue'))
            value = input('({0}) > '.format(account.backend.get(
                field.name, '')))
            value = value.strip()

            # Check if the value should be set to the original, cleared or used
            # as provided.
            if value:
                if value == '-':
                    continue
                else:
                    config[field.name] = value
            else:
                if account.backend.get(field.name):
                    config[field.name] = account.backend.get(field.name)

        # Validate the users configuration
        result = backend.validate_config(**config)
        if not result[0]:
            self.err('Invalid backend config:', **result[1])
            return

        # Update the accounts backend
        account.backend = config
        account.update('modified', 'backend')

        self.out(('Account configured', 'bold_green'))
Ejemplo n.º 15
0
    def run(self, name, new_name):

        # Validate the parameters
        form = RenameAccountForm(name=name, new_name=new_name)

        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to rename
        account = Account.one(Q.name == form.data['name'])

        # Set the accounts new name
        account.name = form.data['new_name']
        account.update('modified', 'name')

        self.out(('Account renamed: ' + account.name, 'bold_green'))
Ejemplo n.º 16
0
def test_view_account(capsys, app, test_accounts):
    # View the details for an account
    ViewAccount().run('getme')

    # Find the account in question as some details are generate when the account
    # is created.
    getme = Account.one(Q.name == 'getme')

    # Check output is as expected
    expected_out = [
        "About 'getme':", '- created------- ' + str(getme.created),
        '- modified------ ' + str(getme.modified), '- assets-------- 0',
        '- api_key------- ' + getme.api_key, '- backend------- local',
        '- > asset_root-- tests/data/assets'
    ]
    expected_out = '\n'.join(expected_out)
    out = capsys.readouterr()[0].strip()
    assert out == expected_out
Ejemplo n.º 17
0
    def purge(self):
        """Deletes the asset along with all related files."""
        from models.accounts import Account

        # Make sure we have access to the associated account frame
        if not isinstance(self.account, Account):
            self.account = Account.one(Q._id == self.account)

        # Get the backend required to delete the asset
        backend = self.account.get_backend_instance()

        # Delete the original file
        backend.delete(self.store_key)

        # Delete all variation files
        for variation in self.variations:
            backend.delete(variation.store_key)

        self.delete()
Ejemplo n.º 18
0
def test_config_account(capsys, app, test_accounts):
    # Configure an account
    responses = [
        'AKIAIW5ILOAT5ZJ5XWJQ', 'y80Io/ukJhZxaiHd4ngEVxIC7v96D+z+tJOFOoY2',
        'hangar51test'
    ]
    with mock.patch.object(builtins, 'input', mock_input(responses)):
        ConfigAccount().run('hangar51')

    # Check the output is as expected
    assert 'Account configured' == \
        capsys.readouterr()[0].strip().split('\n')[-1]

    # Check the account was configured correctly
    account = Account.one(Q.name == 'hangar51')
    assert account.backend['access_key'] == 'AKIAIW5ILOAT5ZJ5XWJQ'
    assert account.backend['secret_key'] == \
            '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'
    assert account.backend['bucket'] == 'hangar51test'
Ejemplo n.º 19
0
def test_local_account(app):
    """Create a local account"""

    # Add the local account
    with open('tests/data/local.cfg') as f:
        config = json.load(f)

    account = Account(name='local', backend=config)
    account.insert()

    yield account

    # Purge the account
    account.purge()
Ejemplo n.º 20
0
def new_user():
    data = request.get_json()
    user_key = Account.random_api_key()
    hashed_password = Account.hash_password(data.get('password'))
    new_account = Account(data.get('firstname'), data.get('lastname'),
                          data.get('username'), data.get('email'),
                          hashed_password, user_key)
    new_account._insert()
    return jsonify({
        'session_id': new_account.user_key,
        'firstname': new_account.firstname,
        'lastname': new_account.lastname,
        'username': new_account.username
    })
Ejemplo n.º 21
0
    def generate_variations(account_id, asset_uid, variations, webhook=''):
        """Generate a set of variations for an image asset"""

        # Find the account
        account = Account.by_id(account_id)
        if not account:
            return

        # Find the asset
        asset = Asset.one(And(Q.account == account, Q.uid == asset_uid))
        if not asset:
            return

        # Check the asset hasn't expired
        if asset.expired:
            return

        # Retrieve the original file
        backend = account.get_backend_instance()
        f = backend.retrieve(asset.store_key)
        im = Image.open(f)

        # Generate the variations
        new_variations = {}
        for name, ops in variations.items():
            variation = asset.add_variation(im, name, ops)
            new_variations[name] = variation.to_json_type()

        # Update the assets modified timestamp
        asset.update('modified')

        # If a webhook has been provide call it with details of the new
        # variations.
        if webhook:
            requests.get(
                webhook,
                data={
                    'account': account.name,
                    'asset': asset.uid,
                    'variations': json.dumps(variations)
                    }
                )
Ejemplo n.º 22
0
    def run(self, name):

        # Validate the parameters
        form = DeleteAccountForm(name=name)
        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to be deleted
        account = Account.one(Q.name == form.data['name'])

        # Confirm the account deletion
        if not self.confirm(
                'Enter the following string to confirm you want to \
delete this account deletion', account.name):
            return

        # Delete the account
        account.delete()

        self.out(('Account deleted', 'bold_green'))
Ejemplo n.º 23
0
def getall():
    acctbl = db.accounts
    data = acctbl.find()
    if data:
        rs = []
        for i in data:
            acc = Account(i['account_number'], i['firstname'], i['lastname'],
                          i['gender'], i['age'], i['email'], i['city'],
                          i['address'], i['state'], i['employer'],
                          i['balance'])
            rs.append(acc)
        return jsonify({
            "data": [x.tojson() for x in rs],
            "size": len(rs),
            "msg": 'get data successed'
        }), 200
    else:
        return jsonify({
            "data": None,
            "size": 0,
            "msg": 'get data failed'
        }), 404
Ejemplo n.º 24
0
    def run(self, name):

        # Validate the parameters
        form = GenerateNewAccountAPIKeyForm(name=name)
        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to generate a new API key for
        account = Account.one(Q.name == form.data['name'])

        # Confirm the account deletion
        if not self.confirm(
                'Enter the following string to confirm you want to \
generate a new API key for this account', account.name):
            return

        # Generate a new API key for the account
        account.api_key = account.generate_api_key()
        account.update('modified', 'api_key')

        self.out(('New key generated: ' + account.api_key, 'bold_green'))
Ejemplo n.º 25
0
def test_backends(app):
    """Create accounts to support each backend"""

    # Add the test accounts for each backend
    accounts = []
    for backend in ['local', 's3']:

        with open('tests/data/{backend}.cfg'.format(backend=backend)) as f:
            config = json.load(f)

        account = Account(name=backend, backend=config)
        account.insert()
        accounts.append(account)

    yield accounts

    # Purge the accounts
    for account in accounts:
        account.purge()
Ejemplo n.º 26
0
def test_accounts(app):
    """Load test accounts"""

    # Load the test account information
    with open('tests/data/accounts.json') as f:
        data = json.load(f)

    # Add the test accounts
    accounts = []
    for account_data in data:

        with open('tests/data/' + account_data['config_filepath']) as f:
            config = json.load(f)

        account = Account(name=account_data['name'], backend=config)
        account.insert()
        accounts.append(account)

    yield accounts

    # Purge the accounts
    for account in accounts:
        account.purge()
Ejemplo n.º 27
0
 def validate_name(form, field):
     """Validate that the account name exists"""
     if Account.count(Q.name == field.data) == 0:
         raise ValidationError('Account not found.')
Ejemplo n.º 28
0
 def validate_new_name(form, field):
     """Validate that the new account name isn't taken"""
     if Account.count(Q.name == field.data) > 0:
         raise ValidationError('Account name already taken.')
Ejemplo n.º 29
0
    def on_push_button_start_released(self):
        self.push_button_test.setEnabled(False)
        self.push_button_start.setEnabled(False)

        url = parse_url(self.line_edit_server_address.text())

        account = Account()
        account.assign_autogenerated_id()
        account.description = ''
        account.account_root_directory = account.id
        account.oxnote_home_folder = Configuration().get_setting(
            'drive_client',
            'api.defaults.oxnote_home_folder.name',
            default='.oxnote')
        account.application_data_folder = Configuration().get_setting(
            'drive_client',
            'api.defaults.application_data_folder.name',
            default='.oxnote')
        account.url_scheme = url.scheme if url.scheme and url.scheme in (
            'http', 'https') else 'https'
        account.url_host = url.host if url.host else None
        account.url_port = url.port if url.port else None
        account.url_uri = url.request_uri if url.request_uri and url.request_uri != '/' else '/ajax/'
        account.username = self.line_edit_username.text()
        account.password = self.line_edit_password.text()
        account.context_id = ''
        account.user_id = ''
        account.enabled = True
        account.drive_quota = -1

        AccountManager().save_account_configuration(account)

        self.close()
        self._oxnote_main_window_widget = MainWindow()
        self._oxnote_main_window_widget.show()