Beispiel #1
0
 def test_get_user(self, initialize_mock):
     mockldap = MockLdapConn()
     initialize_mock.return_value = MockLdapConn.Connection(
         None, None, None, None)
     user = BmajUser('biomaj')
     self.assertTrue(user.user is None)
     user.remove()
Beispiel #2
0
 def test_ldap_user(self, initialize_mock):
     mockldap = MockLdapConn()
     initialize_mock.return_value = MockLdapConn.Connection(
         None, None, None, None)
     user = BmajUser('biomajldap')
     self.assertTrue(user.user['is_ldap'] == True)
     self.assertTrue(user.user['_id'] is not None)
     self.assertTrue(user.check_password('test'))
     user.remove()
Beispiel #3
0
 def test_api_renew(self, initialize_mock):
     mockldap = MockLdapConn()
     initialize_mock.return_value = MockLdapConn.Connection(
         None, None, None, None)
     user = BmajUser('biomajldap')
     apikey = user.user['apikey']
     user = BmajUser('biomajldap')
     self.assertTrue(user.user['apikey'] == apikey)
     user.renew_apikey()
     user = BmajUser('biomajldap')
     self.assertTrue(user.user['apikey'] != apikey)
     user.remove()
Beispiel #4
0
    def validate_authentication(self, username, apikey, handler):
        """Raises AuthenticationFailed if supplied username and
        password don't match the stored credentials, else return
        None.
        """
        msg = "Authentication failed."
        if apikey == 'anonymous':
            return
        if apikey != 'anonymous':
            user = None
            if self.cfg['web']['local_endpoint']:
                user_req = requests.get(self.cfg['web']['local_endpoint'] +
                                        '/api/info/apikey/' + apikey)
                if not user_req.status_code == 200:
                    raise AuthenticationFailed(
                        'Wrong or failed authentication')
                user = user_req.json()
            else:
                user = BmajUser.get_user_by_apikey(apikey)

            bank = self.db.banks.find_one({'name': username})
            if not bank:
                logging.error('Bank not found: ' + username)
                raise AuthenticationFailed('Bank does not exists')
            if bank['properties']['visibility'] != 'public':
                if user['id'] != bank['properties']['owner']:
                    if 'members' not in bank['properties'] or user[
                            'id'] not in bank['properties']['members']:
                        raise AuthenticationFailed(
                            'Not allowed to access to this bank')

            if len(bank['production']) == 0:
                raise AuthenticationFailed('No production release available')
            self.bank = bank
Beispiel #5
0
def create_user(user):
    '''
    Check if listing request is over
    '''
    user = BmajUser(user)
    param = request.get_json()
    if 'password' not in param:
        param['password'] = ''.join(
            random.SystemRandom().choice(string.ascii_uppercase +
                                         string.digits) for _ in range(10))
    if 'email' not in param:
        param['email'] = None
    if not user.user:
        user.create(password=param['password'], email=param['email'])
    del user.user['_id']
    del user.user['hashed_password']
    return jsonify({'user': user.user, 'password': param['password']})
def list_users():
    '''
    List users
    '''
    users = BmajUser.list()
    for user in users:
        del user['_id']
        del user['hashed_password']
    return jsonify({'users': users})
Beispiel #7
0
 def setUp(self):
     self.utils = UtilsForTest()
     self.curdir = os.path.dirname(os.path.realpath(__file__))
     BiomajConfig.load_config(self.utils.global_properties,
                              allow_user_config=False)
     config = {
         'mongo': {
             'url': BiomajConfig.global_config.get('GENERAL', 'db.url'),
             'db': BiomajConfig.global_config.get('GENERAL', 'db.name')
         },
         'ldap': {
             'host': BiomajConfig.global_config.get('GENERAL', 'ldap.host'),
             'port':
             int(BiomajConfig.global_config.get('GENERAL', 'ldap.port')),
             'dn': BiomajConfig.global_config.get('GENERAL', 'ldap.dn')
         }
     }
     BmajUser.set_config(config)
Beispiel #8
0
def list_users():
    '''
    Check if listing request is over
    '''
    users = BmajUser.list()
    for user in users:
        del user['_id']
        del user['hashed_password']
    return jsonify({'users': users})
Beispiel #9
0
 def test_check_password(self, initialize_mock):
     mockldap = MockLdapConn()
     initialize_mock.return_value = MockLdapConn.Connection(
         None, None, None, None)
     user = BmajUser('biomaj')
     user.create('test', '*****@*****.**')
     self.assertTrue(user.check_password('test'))
     user.remove()
Beispiel #10
0
def get_user(user):
    '''
    Check if listing request is over
    '''
    user = BmajUser(user)
    if not user.user:
        abort(404)
    del user.user['_id']
    del user.user['hashed_password']
    return jsonify({'user': user.user})
def get_user_by_apikey(apikey):
    '''
    Get a user from his api key
    '''
    user = BmajUser.get_user_by_apikey(apikey)
    if user:
        del user['_id']
        if 'hashed_password' in user:
            del user['hashed_password']
    return jsonify({'user': user})
def get_user(user):
    '''
    Get user info
    '''
    user = BmajUser(user)
    if not user.user:
        abort(404)
    del user.user['_id']
    if 'hashed_password' in user.user:
        del user.user['hashed_password']
    return jsonify({'user': user.user})
Beispiel #13
0
def bind_user(user):
    '''
    Bind a user with his password or API Key. Post parameters dict:

    {'type': 'password|apikey', 'value': 'XXXX'}


    '''
    user = BmajUser(user)
    params = request.get_json()
    check = False
    if params['type'] == 'password':
        check = user.check_password(params['value'])
    else:
        check = user.check_api_key(params['value'])
    if not check:
        abort(401)
    del user.user['_id']
    del user.user['hashed_password']
    return jsonify({'user': user.user})
Beispiel #14
0
    def __init__(self):
        config_file = 'config.yml'
        if 'BIOMAJ_CONFIG' in os.environ:
            config_file = os.environ['BIOMAJ_CONFIG']
        self.cfg = None
        with open(config_file, 'r') as ymlfile:
            self.cfg = yaml.load(ymlfile)

        if self.cfg['log_config'] is not None:
            for handler in list(self.cfg['log_config']['handlers'].keys()):
                self.cfg['log_config']['handlers'][handler] = dict(
                    self.cfg['log_config']['handlers'][handler])
            logging.config.dictConfig(self.cfg['log_config'])
        self.logger = logging.getLogger('biomaj')

        BmajUser.set_config(self.cfg)

        authorizer = BiomajAuthorizer()
        authorizer.set_config(self.cfg)

        self.handler = FTPHandler
        self.handler.authorizer = authorizer
    def validate_authentication(self, username, apikey, handler):
        """Raises AuthenticationFailed if supplied username and
        password don't match the stored credentials, else return
        None.
        """
        # msg = "Authentication failed."
        #anonymous user : we defined the user as anonymous
        proxy = Utils.get_service_endpoint(self.cfg, 'user')
        if username == "biomaj_default":
            user = {}
            user['id'] = "BMJ_default"
        elif proxy:
            user_req = requests.get(proxy + '/api/user/info/apikey/' + apikey)
            if not user_req.status_code == 200:
                raise AuthenticationFailed('Wrong or failed authentication')
            user = user_req.json()
        else:
            user = BmajUser.get_user_by_apikey(apikey)
        if not user:
            self.logger.error('User not found: ' + username)
            raise AuthenticationFailed('User does not exists')

        #Determining the authorized path
        dict_bank = {}
        for db_entry in self.db.banks.find():
            home_dir = self.get_home_dir(username, db_entry)
            dict_bank[home_dir] = [
                db_entry['properties']['visibility'],
                db_entry['properties']['owner']
            ]
        self.bank = dict_bank
        #Create a new user for biomaj server with specific permission
        if not self.has_user(username):
            self.add_user(username, apikey, self.get_home_dir(username))
        for directory in dict_bank:
            if dict_bank[directory][0] == "public":
                perm = "elr"
                self.override_perm(username, directory, perm, recursive=True)
            elif dict_bank[directory][
                    1] == username and dict_bank[directory][0] != "public":
                perm = "elr"
                self.override_perm(username, directory, perm, recursive=True)
            elif username == "biomaj_default" or dict_bank[directory][
                    0] != "public":  #biomaj_default user and private bank
                perm = ""
                self.override_perm(username, directory, perm, recursive=True)
        return
    def __init__(self):
        config_file = 'config.yml'
        if 'BIOMAJ_CONFIG' in os.environ:
            config_file = os.environ['BIOMAJ_CONFIG']
        self.cfg = None
        with open(config_file, 'r') as ymlfile:
            self.cfg = yaml.load(ymlfile, Loader=Loader)
            Utils.service_config_override(self.cfg)

        # There is an issue with tcp checks, see https://github.com/cablehead/python-consul/issues/136
        if self.cfg['consul']['host']:
            consul_agent = consul.Consul(host=self.cfg['consul']['host'])
            consul_agent.agent.service.register(
                'biomaj-ftp',
                service_id=self.cfg['consul']['id'],
                address=self.cfg['consul']['id'],
                port=self.cfg['ftp']['port'],
                tags=['biomaj'])
            check = consul.Check.tcp(host=self.cfg['consul']['id'],
                                     port=self.cfg['ftp']['port'],
                                     interval=20)
            consul_agent.agent.check.register(
                self.cfg['consul']['id'] + '_check',
                check=check,
                service_id=self.cfg['consul']['id'])

        if self.cfg['log_config'] is not None:
            for handler in list(self.cfg['log_config']['handlers'].keys()):
                self.cfg['log_config']['handlers'][handler] = dict(
                    self.cfg['log_config']['handlers'][handler])
            logging.config.dictConfig(self.cfg['log_config'])
        self.logger = logging.getLogger('biomaj')

        BiomajConfig.load_config(self.cfg['biomaj']['config'])

        BmajUser.set_config(self.cfg)

        authorizer = BiomajAuthorizer()
        authorizer.set_config(self.cfg)
        authorizer.set_logger(self.logger)

        self.handler = FTPHandler
        self.handler.authorizer = authorizer
        if 'passive_ports_start' in self.cfg[
                'ftp'] and 'passive_ports_end' in self.cfg['ftp'] and self.cfg[
                    'ftp']['passive_ports_start'] and self.cfg['ftp'][
                        'passive_ports_end']:
            self.handler.passive_ports = range(
                self.cfg['ftp']['passive_ports_start'],
                self.cfg['ftp']['passive_ports_end'])
            self.logger.info('Use passive ports range %d:%d' %
                             (self.cfg['ftp']['passive_ports_start'],
                              self.cfg['ftp']['passive_ports_end']))
        else:
            self.handler.passive_ports = range(60000, 65535)
            self.logger.info('Use passive ports range %d:%d' % (60000, 65535))

        masquerade_address = os.environ.get('MASQUERADE_ADDRESS', None)
        if masquerade_address:
            self.handler.masquerade_address = os.environ['MASQUERADE_ADDRESS']
        elif 'masquerade_address' in self.cfg['ftp'] and self.cfg['ftp'][
                'masquerade_address'] is not None:
            self.handler.masquerade_address = self.cfg['ftp'][
                'masquerade_address']
Beispiel #17
0
def main():
    """This is the main function treating arguments passed on the command line."""
    description = "BioMAJ user: Manager users."
    parser = argparse.ArgumentParser(description=description)
    # Options without value
    parser.add_argument('-A', '--action', dest="action", default=None,
                        help="Action to perform for user " + str(SUPPORTED_ACTIONS) +
                             "'renew': Create new api key",
                        required=True)
    parser.add_argument('-J', '--json', dest="json", help="output to json", action='store_true')
    parser.add_argument('-C', '--config', dest="config", metavar='</path/to/config.yml>', type=str,
                        help="Path to config.yml. By default read from env variable BIOMAJ_CONFIG")
    parser.add_argument('-E', '--email', dest="email", type=str,
                        help="User email, optional")
    parser.add_argument('-U', '--user', dest="user", metavar='<username>', type=str,
                        required=True, help="User name to manage")
    parser.add_argument('-P', '--password', dest="passwd", metavar="<password>", type=str,
                        help="User password to use when creating new user. If not given, automatically generated, accepts env variable BIOMAJ_USER_PASSWORD env variable")
    parser.parse_args(namespace=options)
    if not len(sys.argv) > 1:
        parser.print_help()
        sys.exit(1)
    if options.action not in SUPPORTED_ACTIONS:
        print("Unsupported action '%s'" % str(options.action))
        sys.exit(1)

    if options.config:
        config = options.config
    elif 'BIOMAJ_CONFIG' in os.environ:
        config = os.environ['BIOMAJ_CONFIG']
    else:
        config = 'config.yml'
    with open(config, 'r') as ymlfile:
        config = yaml.load(ymlfile, Loader=yaml.FullLoader)
        Utils.service_config_override(config)

    BmajUser.set_config(config)
    user = BmajUser(options.user)
    if options.action in ['add', 'create']:
        if user.user is None:
            if options.passwd is None:
                if 'BIOMAJ_USER_PASSWORD' in os.environ:
                    options.passwd = os.environ['BIOMAJ_USER_PASSWORD']
                else:
                    options.passwd = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits)
                                         for _ in range(10))
            user.create(options.passwd, email=options.email)
            if options.json:
                del user.user['_id']
                print(json.dumps(user.user))
                sys.exit(0)
            print("User successfully created")
            print(tabulate([["User", "Password", "API Key"],
                            [user.user['id'], str(options.passwd), str(user.user['apikey'])]],
                           headers="firstrow", tablefmt="psql"))
            sys.exit(0)
        else:
            print("User %s already exist" % user.user['id'])
            sys.exit(1)

    if user.user is None:
        print("[%s] User %s does not exist" % (str(options.action), str(options.user)))
        sys.exit(1)

    if options.action in ['delete', 'remove', 'rm']:
        user.remove()
        print("User %s successfully deleted" % user.user['id'])
    if options.action == 'update':
        update = {}
        if options.passwd:
            update['hashed_password'] = bcrypt.hashpw(options.passwd, user.user['hashed_password'])
        if options.email:
            update['email'] = options.email
        if update.items():
            BmajUser.users.update({'id': user.user['id']}, {'$set': update})
            print("User %s successfully updated" % str(user.user['id']))
        else:
            print("[%s] User %s not updated" % (str(options.action), str(options.user)))
    if options.action == 'renew':
        user.renew_apikey()
        user = BmajUser(user.user['id'])
        print("[%s] User %s, successfully renewed API key: '%s'" %
              (str(options.action), str(user.user['id']), str(user.user['apikey'])))
    if options.action == 'view':
        print(tabulate([["User", "Email", "API Key", "LDAP"],
                        [str(user.user['id']), str(user.user['email']),
                         str(user.user['apikey']), str(user.user['is_ldap'])]],
                       headers="firstrow", tablefmt="psql"))
    sys.exit(0)
Beispiel #18
0
def get_user_by_apikey(apikey):
    user = BmajUser.get_user_by_apikey(apikey)
    del user['_id']
    del user['hashed_password']
    return jsonify({'user': user})
Beispiel #19
0
from flask import jsonify
from flask import request
from flask import abort
import consul

from biomaj_user.user import BmajUser

config_file = 'config.yml'
if 'BIOMAJ_CONFIG' in os.environ:
    config_file = os.environ['BIOMAJ_CONFIG']

config = None
with open(config_file, 'r') as ymlfile:
    config = yaml.load(ymlfile)

BmajUser.set_config(config)

app = Flask(__name__)


def start_server(config):
    context = None
    if config['tls']['cert']:
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        context.load_cert_chain(config['tls']['cert'], config['tls']['key'])

    if config['consul']['host']:
        consul_agent = consul.Consult(host=config['consul']['host'])
        consul_agent.agent.service.register('biomaj_user',
                                            service_id=config['consul']['id'],
                                            port=config['web']['port'],