예제 #1
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)
예제 #2
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
예제 #3
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'],
예제 #4
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)
예제 #5
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, 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']