Esempio n. 1
0
def get_account(_id=None):
	logger.debug("Get Account:")

	if not _id:
		s = bottle.request.environ.get('beaker.session')
		_id = s.get('account_id', None)

	logger.debug(" + _id: %s" % _id)

	if not _id:
		logger.debug("  + Failed")
		return session_accounts['anonymous']

	logger.debug("Load account from cache")
	account = session_accounts.get(_id, None)

	if account:
		return account

	logger.debug("  + Failed")

	logger.debug("Load account from DB")
	
	try:
		user = s.get('account_user', None)	
		storage = get_storage(namespace='object')
		account = caccount(storage.get(_id, account=caccount(user=user)))
	except Exception as err:
		logger.debug("  + Failed: %s" % err)
		return session_accounts['anonymous']

	session_accounts[_id] = account
	return account
Esempio n. 2
0
def autoLogin(key=None):
	if not key:
		return HTTPError(400, "No key provided")
	#---------------------Get storage/account-------------------
	storage = get_storage(namespace='object')
	
	mfilter = {
				'crecord_type':'account',
				'authkey':key,
			}
	
	logger.debug('Try to find %s key' % key)

	foundByKey = storage.find(mfilter=mfilter, account=caccount(user='******'))
	#-------------------------if found, create session and redirect------------------------
	if len(foundByKey) == 1:
		account = caccount(foundByKey[0])

		if not account.is_enable():
			return HTTPError(403, "This account is not enabled")

		s = bottle.request.environ.get('beaker.session')
		s['account_id'] = account._id
		s['account_user'] = account.user
		s['account_group'] = account.group
		s['account_groups'] = account.groups
		s['auth_on'] = True
		s.save()
		#logger.debug('Autologin success, redirecting browser')
		#redirect('/static/canopsis/index.html')
		account = caccount(foundByKey[0])
		return {'total':1,'data':[account.dump()],'success':True}
	else:
		logger.debug('Autologin failed, no key match the provided one')
		return {'total':0,'data':{},'success':False}
Esempio n. 3
0
def auth(login=None, password=None):
	if not login:
		login = request.params.get('login', default=None)

	if not password:
		password = request.params.get('password', default=None)

	if not login or not password:
		return HTTPError(400, "Invalid arguments")

	mode = 'plain'

	if request.params.get('shadow', default=False):
		mode = 'shadow'
	
	if request.params.get('cryptedKey', default=False) or request.params.get('crypted', default=False):
		mode = 'crypted'

	_id = "account.%s" % login

	logger.debug(" + _id:      %s" % _id)
	logger.debug(" + Login:    %s" % login)
	logger.debug(" + Mode:     %s" % mode)

	storage = get_storage(namespace='object')
	account = None

	## Local
	try:
		account = caccount(storage.get(_id, account=caccount(user=login)))
	except Exception, err:
		logger.error(err)
Esempio n. 4
0
def auth(login=None, password=None):
    if not login:
        login = request.params.get('login', default=None)

    if not password:
        password = request.params.get('password', default=None)

    if not login or not password:
        return HTTPError(400, "Invalid arguments")

    mode = 'plain'

    if request.params.get('shadow', default=False):
        mode = 'shadow'

    if request.params.get('cryptedKey', default=False) or request.params.get(
            'crypted', default=False):
        mode = 'crypted'

    _id = "account.%s" % login

    logger.debug(" + _id:      %s" % _id)
    logger.debug(" + Login:    %s" % login)
    logger.debug(" + Mode:     %s" % mode)

    storage = get_storage(namespace='object')
    account = None

    ## Local
    try:
        account = caccount(storage.get(_id, account=caccount(user=login)))
    except Exception, err:
        logger.error(err)
Esempio n. 5
0
def reload_account(_id=None,record=None):
	try:
		logger.debug('Reload Account %s' % _id)
		account = get_account()
		storage = get_storage(namespace='object')
		account_to_update = None
		
		if not record:
			if _id:	
				record = storage.get(_id, account=account)
				account_to_update = caccount(record)
			else:
				record = storage.get(account._id, account=account )
				account_to_update = caccount(record)
				
		if not account_to_update:
			account_to_update = caccount(record)
			
		session_accounts[account_to_update._id] = account_to_update
		s = bottle.request.environ.get('beaker.session')
		logger.debug(s)
		logger.debug(s['account_group'])
		logger.debug(s['account_groups'])
		s['account_group'] = account_to_update.group
		s['account_groups'] = account_to_update.groups
		logger.debug('Account %s is in following groups : %s' % (_id,str(account_to_update.groups)))
		s.save()
		return True
	except Exception,err:
		logger.error('Account reloading failed : %s' % err)
		return False
Esempio n. 6
0
def get_account(_id=None):
    logger.debug("Get Account:")

    if not _id:
        s = bottle.request.environ.get('beaker.session')
        _id = s.get('account_id', None)

    logger.debug(" + _id: %s" % _id)

    if not _id:
        logger.debug("  + Failed")
        return session_accounts['anonymous']

    logger.debug("Load account from cache")
    account = session_accounts.get(_id, None)

    if account:
        return account

    logger.debug("  + Failed")

    logger.debug("Load account from DB")

    try:
        user = s.get('account_user', None)
        storage = get_storage(namespace='object')
        account = caccount(storage.get(_id, account=caccount(user=user)))
    except Exception as err:
        logger.debug("  + Failed: %s" % err)
        return session_accounts['anonymous']

    session_accounts[_id] = account
    return account
Esempio n. 7
0
	def test_01_Init(self):
		global ACCOUNT
		ACCOUNT = caccount(user="******", lastname="Pain", firstname="William", mail="*****@*****.**", group="capensis", groups=['group.titi', 'group.tata'])
		global GROUP
		
		user_account = caccount(user="******", group="capensis")
		user_account.cat()
Esempio n. 8
0
def get_account(_id=None):
	logger.debug("Get Account:")
	if not _id:
		s = bottle.request.environ.get('beaker.session')
		_id = s.get('account_id',0)
		logger.debug(" + Get _id from Beaker Session (%s)" % _id)

	user = s.get('account_user',0)

	logger.debug(" + Try to load account %s ('%s') ..." % (user, _id))

	storage = get_storage(namespace='object')

	try:
		account = session_accounts[_id]
		logger.debug(" + Load account from memory.")
	except:
		if _id:
			record = storage.get(_id, account=caccount(user=user) )
			logger.debug(" + Load account from DB.")
			account = caccount(record)
			session_accounts[_id] = account
		else:
			logger.debug(" + Impossible to load account, return Anonymous account.")
			try:
				return session_accounts['anonymous']
			except:
				session_accounts['anonymous'] = caccount()
				return session_accounts['anonymous']

	return account
Esempio n. 9
0
def auth(login=None, password=None):
	if not login:
		login = request.params.get('login', default=None)

	shadow = request.params.get('shadow', default=False)
	if shadow:
		shadow = True
	
	cryptedKey = request.params.get('cryptedKey', default=False)

	if not password:
		password = request.params.get('password', default=None)

	if not login or not password:
		return HTTPError(400, "Invalid arguments")

	_id = "account." + login

	logger.debug(" + _id: "+_id)
	logger.debug(" + Login: "******" + Password: "******"    + is Shadow: "+str(shadow))
	logger.debug("    + is cryptedKey: "+str(cryptedKey))

	storage = get_storage(namespace='object')

	try:
		account = caccount(storage.get(_id, account=caccount(user=login)))
		logger.debug(" + Check password ...")

		if not account.is_enable():
			return HTTPError(403, "This account is not enabled")

		if shadow:
			access = account.check_shadowpasswd(password)
			
		elif cryptedKey:
			logger.debug(" + Valid auth key: %s" % (account.make_tmp_cryptedKey()))
			access = account.check_tmp_cryptedKey(password)
			
		else:
			access = account.check_passwd(password)

		if access:
			s = bottle.request.environ.get('beaker.session')
			s['account_id'] = account._id
			s['account_user'] = account.user
			s['account_group'] = account.group
			s['account_groups'] = account.groups
			s['auth_on'] = True
			s.save()

			output = [ account.dump() ]
			output = {'total': len(output), 'success': True, 'data': output}
			return output
		else:
			logger.debug(" + Invalid password ...")
	except Exception, err:
		logger.error(err)
Esempio n. 10
0
	def setUp(self):
		self.anonymous_account = caccount()
		self.root_account = caccount(user="******", group="root")
		self.storage = cstorage(self.root_account, namespace='unittest')
		self.data = {}

		self.my_file = '/opt/canopsis/bin/pydoc'
		self.my_data = 'JAMBON123'
Esempio n. 11
0
def launch_celery_task(*args, **kwargs):
    if kwargs.has_key('task') and kwargs.has_key('method'):
        try:
            amqp = camqp(logging_name="aps-amqp")
            amqp.start()

            timer_begin = int(time.time())

            #----------Get task informations
            task_name = kwargs['_scheduled']
            celery_task_name = kwargs['task']

            module = __import__(kwargs['task'])
            exec "task = module.%s" % kwargs['method']

            #-------------Clear arguments
            methodargs = kwargs
            del methodargs['task']
            del methodargs['method']
            del kwargs['_scheduled']

            #-------------execute task
            success = True

            try:
                result = task.delay(*args, **methodargs)
                result.get()
                result = result.result

                if not result['success']:
                    raise Exception('Celery task failed')

            except Exception, err:
                success = False
                aps_error = str(err)
                logger.error(err)

            #------------Get account and storage
            try:
                if isinstance(kwargs['account'], unicode) or isinstance(
                        kwargs['account'], str):
                    account = caccount(user=kwargs['account'])
                else:
                    account = kwargs['account']
                #logger.error(account)
                logger.info('Caccount create from passed arguments')
            except Exception, err:
                logger.info('No account specified in the task')
                account = caccount()

            try:
                storage = cstorage(account=account, namespace='object')
            except Exception, err:
                logger.info('Error while fecthing storages : %s' % err)
                success = False
                aps_error = str(err)
Esempio n. 12
0
    def setUp(self):
        self.anonymous_account = caccount()
        self.root_account = caccount(user="******", group="root")
        self.user_account = caccount(user="******", group="capensis")

        self.data = {
            'mydata1': 'data1',
            'mydata2': 'data2',
            'mydata3': 'data3'
        }
Esempio n. 13
0
def launch_celery_task(*args,**kwargs):
	if kwargs.has_key('task') and kwargs.has_key('method'):
		try:
			amqp = camqp(logging_name="aps-amqp")
			amqp.start()

			timer_begin = int(time.time())
			
			#----------Get task informations
			task_name = kwargs['_scheduled']
			celery_task_name = kwargs['task']
			
			module = __import__(kwargs['task'])
			exec "task = module.%s" % kwargs['method']
			
			#-------------Clear arguments
			methodargs = kwargs
			del methodargs['task']
			del methodargs['method']
			del kwargs['_scheduled']
			
			#-------------execute task
			success = True
			
			try:
				result = task.delay(*args,**methodargs)
				result.get()
				result = result.result
				
				if not result['success']:
					raise Exception('Celery task failed')
				
			except Exception, err:
				success = False
				aps_error = str(err)
				logger.error(err)

			#------------Get account and storage
			try:
				if isinstance(kwargs['account'],unicode) or isinstance(kwargs['account'],str):
					account = caccount(user=kwargs['account'])
				else:
					account = kwargs['account']
				#logger.error(account)
				logger.info('Caccount create from passed arguments')
			except Exception, err:
				logger.info('No account specified in the task')
				account = caccount()
			
			try:
				storage = cstorage(account=account, namespace='object')
			except Exception, err:
				logger.info('Error while fecthing storages : %s' % err)
				success = False
				aps_error = str(err)
Esempio n. 14
0
	def setUp(self):
		self.anonymous_account = caccount()
		self.root_account = caccount(user="******", group="root")
		self.user_account = caccount(user="******", group="capensis")
		self.user2_account = caccount(user="******", group="capensis")
		
		#self.anonymous_account.cat()
		#self.user_account.cat()
		#self.root_account.cat()
	
		self.data = {'mydata1': 'data1', 'mydata2': 'data2', 'mydata3': 'data3'}
Esempio n. 15
0
    def setUp(self):
        self.anonymous_account = caccount()
        self.root_account = caccount(user="******", group="root")
        self.user_account = caccount(user="******", group="capensis")
        self.user2_account = caccount(user="******", group="capensis")

        # self.anonymous_account.cat()
        # self.user_account.cat()
        # self.root_account.cat()

        self.data = {"mydata1": "data1", "mydata2": "data2", "mydata3": "data3"}
Esempio n. 16
0
    def test_01_Init(self):
        global ACCOUNT
        ACCOUNT = caccount(user="******",
                           lastname="Pain",
                           firstname="William",
                           mail="*****@*****.**",
                           group="capensis",
                           groups=['group.titi', 'group.tata'])
        global GROUP

        user_account = caccount(user="******", group="capensis")
        user_account.cat()
Esempio n. 17
0
	def test_22_admin_group_access(self):
		root_account = caccount(user="******", group="root")
		storage = STORAGE
		group = cgroup(name='administrator')
		record = crecord(_id='test_record',admin_group='group.administrator')
		account = caccount(user='******',group='user')
		
		storage.put(record,account=root_account)
		group.add_accounts(account)
		storage.put(account,account=root_account)
		
		try:
			output= storage.get(record._id,account=account)
		except:
			raise Exception('admin group can\'t access all the ressources of his group')
Esempio n. 18
0
    def test_22_admin_group_access(self):
        root_account = caccount(user="******", group="root")
        storage = STORAGE
        group = cgroup(name="administrator")
        record = crecord(_id="test_record", admin_group="group.administrator")
        account = caccount(user="******", group="user")

        storage.put(record, account=root_account)
        group.add_accounts(account)
        storage.put(account, account=root_account)

        try:
            output = storage.get(record._id, account=account)
        except:
            raise Exception("admin group can't access all the ressources of his group")
Esempio n. 19
0
	def pre_run(self):
		self.storage = get_storage(namespace='object', account=caccount(user="******", group="root"))
		
		# TODO: Not compatible with HA !
		self.topo_unloadAll()
		
		self.beat()
Esempio n. 20
0
def account_newAuthKey(dest_account):
	if not dest_account:
		return HTTPError(404, 'No account specified')
	
	#------------------------get accounts----------------------
	account = get_account()
	storage = get_storage(namespace='object',account=account)
	
	_id = 'account.%s' % dest_account
	
	try:
		aim_account = caccount(storage.get(_id,account=account))
	except:
		logger.debug('aimed account not found')
		return HTTPError(404, 'Wrong account name or no enough rights')
	
	#---------------------generate new key-------------------
	logger.debug('Change AuthKey for : %s' % aim_account.user)
	
	try:
		aim_account.generate_new_authkey()
		storage.put(aim_account,account=account)
		logger.debug('New auth key is : %s' % aim_account.get_authkey())
		return {'total': 0, 'success': True, 'data': {'authkey': aim_account.get_authkey(),'account':aim_account.user}}
	except Exception,err:
		logger.error('Error while updating auth key : %s' % err)
		return {'total': 0, 'success': False, 'data': {}}
Esempio n. 21
0
def remove_account_from_group(group_id=None,account_id=None):
	session_account = get_account()
	storage = get_storage(namespace='object',account=session_account)
	
	if not group_id or not account_id:
		return HTTPError(400, 'Bad request, must specified group and account')
	
	#get group && account
	if group_id.find('group.') == -1:
		group_id = 'group.%s' % group_id
		
	if account_id.find('account.') == -1:
		account_id = 'account.%s' % account_id
		
	logger.debug('Try to get %s and %s' % (account_id,group_id))
		
	try:
		account_record = storage.get(account_id,account=session_account)
		account = caccount(account_record)
		group_record = storage.get(group_id,account=session_account)
		group = cgroup(group_record)
		
	except Exception,err:
		logger.error('error while fetching %s and %s : %s' % (account_id,group_id,err))
		return HTTPError(403, 'Record not found or insufficient rights')
Esempio n. 22
0
    def pre_run(self):
        #load selectors
        self.storage = get_storage(namespace='object',
                                   account=caccount(user="******", group="root"))

        self.unload_all_selectors()
        self.load_selectors()
Esempio n. 23
0
def remove_account_from_group(group_id=None, account_id=None):
    session_account = get_account()
    storage = get_storage(namespace='object', account=session_account)

    if not group_id or not account_id:
        return HTTPError(400, 'Bad request, must specified group and account')

    #get group && account
    if group_id.find('group.') == -1:
        group_id = 'group.%s' % group_id

    if account_id.find('account.') == -1:
        account_id = 'account.%s' % account_id

    logger.debug('Try to get %s and %s' % (account_id, group_id))

    try:
        account_record = storage.get(account_id, account=session_account)
        account = caccount(account_record)
        group_record = storage.get(group_id, account=session_account)
        group = cgroup(group_record)

    except Exception, err:
        logger.error('error while fetching %s and %s : %s' %
                     (account_id, group_id, err))
        return HTTPError(403, 'Record not found or insufficient rights')
Esempio n. 24
0
def account_newAuthKey(dest_account):
    if not dest_account:
        return HTTPError(404, 'No account specified')

    #------------------------get accounts----------------------
    account = get_account()
    storage = get_storage(namespace='object', account=account)

    _id = 'account.%s' % dest_account

    try:
        aim_account = caccount(storage.get(_id, account=account))
    except:
        logger.debug('aimed account not found')
        return HTTPError(404, 'Wrong account name or no enough rights')

    #---------------------generate new key-------------------
    logger.debug('Change AuthKey for : %s' % aim_account.user)

    try:
        aim_account.generate_new_authkey()
        storage.put(aim_account, account=account)
        logger.debug('New auth key is : %s' % aim_account.get_authkey())
        return {
            'total': 0,
            'success': True,
            'data': {
                'authkey': aim_account.get_authkey(),
                'account': aim_account.user
            }
        }
    except Exception, err:
        logger.error('Error while updating auth key : %s' % err)
        return {'total': 0, 'success': False, 'data': {}}
Esempio n. 25
0
    def test_22_admin_group_access(self):
        root_account = caccount(user="******", group="root")
        storage = STORAGE
        group = cgroup(name='administrator')
        record = crecord(_id='test_record', admin_group='group.administrator')
        account = caccount(user='******', group='user')

        storage.put(record, account=root_account)
        group.add_accounts(account)
        storage.put(account, account=root_account)

        try:
            output = storage.get(record._id, account=account)
        except:
            raise Exception(
                'admin group can\'t access all the ressources of his group')
Esempio n. 26
0
    def __init__(self,
                 namespace,
                 storage=None,
                 autolog=False,
                 logging_level=logging.ERROR):

        self.logger = logging.getLogger('carchiver')
        self.logger.setLevel(logging_level)

        self.namespace = namespace
        self.namespace_log = namespace + '_log'

        self.autolog = autolog

        self.logger.debug("Init carchiver on %s" % namespace)

        self.account = caccount(user="******", group="root")

        if not storage:
            self.logger.debug(" + Get storage")
            self.storage = get_storage(namespace=namespace,
                                       logging_level=logging_level)
        else:
            self.storage = storage

        self.collection = self.storage.get_backend(namespace)
Esempio n. 27
0
	def test_08_cgroup_with_storage(self):
		global GROUP
		GROUP = cgroup(name='group_name', storage=STORAGE)
		STORAGE.put(GROUP)
		
		global ACCOUNT
		ACCOUNT = caccount(user="******", lastname="Pain", firstname="William", mail="*****@*****.**", group="capensis")
		STORAGE.put(ACCOUNT)
Esempio n. 28
0
def login_plain_ldap():
	storage.remove('account.toto', account=caccount(user='******'))
	resp = get('/auth/toto/aqzsedrftg123;', status=[200])
	logout()

	resp = get('/auth/toto/tata', status=[403])
	resp = get('/auth/toto/aqzsedrftg123;', status=[200])
	logout()
Esempio n. 29
0
def reload_account(_id=None):
	try:
		logger.debug('Reload Account %s' % _id)
		account = get_account()
		storage = get_storage(namespace='object')
		if _id:	
			record = storage.get(_id, account=account)
			account_to_update = caccount(record)
		else:
			record = storage.get(account._id, account=account )
			account_to_update = caccount(record)
			
		session_accounts[account_to_update._id] = account_to_update
		return True
	except Exception,err:
		logger.error('Account reloading failed : %s' % err)
		return False
Esempio n. 30
0
	def test_11_check_group_func_autosav(self):
		account = caccount(user='******', lastname='testify', storage=STORAGE)
		group = cgroup(name='Mgroup')
		
		STORAGE.put(account)
		STORAGE.put(group)

		account.add_in_groups(group._id)
		
		bdd_account = caccount(STORAGE.get(account._id))
		bdd_group = cgroup(STORAGE.get(group._id))
		
		if group._id not in bdd_account.groups:
			raise Exception('Group corruption while stock in bdd after add in group')
		if account._id not in bdd_group.account_ids:
			raise Exception('Group corruption while stock in bdd after add in group')
		'''
Esempio n. 31
0
	def test_10_remove_from_str_ids(self):
		GROUP.remove_accounts(ACCOUNT._id)
		if ACCOUNT._id in GROUP.account_ids:
			raise Exception('Error while add_accounts, account not added')
			
		bdd_account = caccount(STORAGE.get(ACCOUNT._id))
		if GROUP._id in bdd_account.groups:
			raise Exception('Error while add_accounts, group not added to account')
Esempio n. 32
0
    def pre_run(self):
        self.storage = get_storage(namespace='object',
                                   account=caccount(user="******", group="root"))

        # TODO: Not compatible with HA !
        self.topo_unloadAll()

        self.beat()
Esempio n. 33
0
def check_and_create_authkey():
	storage = get_storage(account=root, namespace='object')
	records = storage.find({'crecord_type': 'account'}, namespace='object', account=root)
	accounts = []
	for record in records:
		if not 'authkey' in record.data:
			#caccount auto create authkey if not provided
			accounts.append(caccount(record))
	storage.put(accounts)
Esempio n. 34
0
def init_callback():
    log("Init plugin")

    from cstorage import get_storage
    from caccount import caccount

    global storage
    root = caccount(user="******", group="root")
    storage = get_storage(account=root, namespace="object")
Esempio n. 35
0
def init_callback():
    log('Init plugin')

    from cstorage import get_storage
    from caccount import caccount

    global storage
    root = caccount(user="******", group="root")
    storage = get_storage(account=root, namespace='object')
Esempio n. 36
0
def get_storage(namespace='object', account=None, logging_level=logging.INFO):
	global STORAGES
	try:
		return STORAGES[namespace]
	except:
		if not account:
			account = caccount()
		
		STORAGES[namespace] = cstorage(account, namespace=namespace, logging_level=logging_level)
		return STORAGES[namespace]
Esempio n. 37
0
def check_user_canopsis_groups():
    try:
        storage = get_storage(account=root, namespace='object')
        record = storage.get('account.canopsis')
        account = caccount(record)
        if not 'group.CPS_view' in account.groups and not 'authkey' in record.data:
            account.groups.append('group.CPS_view')
            storage.put(account)
    except:
        pass
Esempio n. 38
0
def check_user_canopsis_groups() :
	try:
		storage = get_storage(account=root, namespace='object')
		record = storage.get('account.canopsis')
		account = caccount(record)
		if not 'group.CPS_view' in account.groups and not 'authkey' in record.data:
			account.groups.append('group.CPS_view')
			storage.put(account)
	except:
		pass
Esempio n. 39
0
def get_storage(namespace='object', account=None, logging_level=logging.INFO):
	global STORAGES
	try:
		return STORAGES[namespace]
	except:
		if not account:
			account = caccount()
		
		STORAGES[namespace] = cstorage(account, namespace=namespace, logging_level=logging_level)
		return STORAGES[namespace]
Esempio n. 40
0
	def resolve_selectors_name(self):
		if int(time.time()) > (self.last_resolv + 60):
			storage = get_storage(namespace='object', account=caccount(user="******", group="root"))
			records = storage.find(mfilter={'crecord_type': 'selector'}, mfields=['crecord_name'])
			
			self.selectors_name = [record['crecord_name'] for record in records]
			
			self.last_resolv = int(time.time())
			
			del storage
Esempio n. 41
0
    def test_11_check_group_func_autosav(self):
        account = caccount(user='******', lastname='testify', storage=STORAGE)
        group = cgroup(name='Mgroup')

        STORAGE.put(account)
        STORAGE.put(group)

        account.add_in_groups(group._id)

        bdd_account = caccount(STORAGE.get(account._id))
        bdd_group = cgroup(STORAGE.get(group._id))

        if group._id not in bdd_account.groups:
            raise Exception(
                'Group corruption while stock in bdd after add in group')
        if account._id not in bdd_group.account_ids:
            raise Exception(
                'Group corruption while stock in bdd after add in group')
        '''
Esempio n. 42
0
def create_account(data):
    logger.debug(' + New account')
    new_account = caccount(user=data['user'],
                           group=data.get('aaa_group', None),
                           lastname=data['lastname'],
                           firstname=data['firstname'],
                           mail=data['mail'])

    new_account.external = data.get('external', False)

    #passwd
    passwd = data['passwd']
    new_account.passwd(passwd)
    logger.debug("   + Passwd: '%s'" % passwd)

    #secondary groups
    groups = []
    for group in data.get('groups', []):
        if group.find('group.') == -1:
            groups.append('group.%s' % group)
        else:
            groups.append(group)
    new_account.groups = groups

    storage = get_storage(namespace='object')

    #put record
    logger.debug(' + Save new account')
    new_account.chown(new_account._id)
    storage.put(new_account, account=root_account)

    #get rootdir
    logger.debug(' + Create view directory')
    rootdir = storage.get('directory.root', account=root_account)

    if rootdir:
        userdir = crecord(
            {
                '_id': 'directory.root.%s' % new_account.user,
                'id': 'directory.root.%s' % new_account.user,
                'expanded': 'true'
            },
            type='view_directory',
            name=new_account.user)
        userdir.chown(new_account._id)
        userdir.chgrp(new_account.group)
        userdir.chmod('g-w')
        userdir.chmod('g-r')

        rootdir.add_children(userdir)
        storage.put([rootdir, userdir], account=root_account)
    else:
        logger.error('Impossible to get rootdir')

    return new_account
Esempio n. 43
0
def check_and_create_authkey():
    storage = get_storage(account=root, namespace='object')
    records = storage.find({'crecord_type': 'account'},
                           namespace='object',
                           account=root)
    accounts = []
    for record in records:
        if not 'authkey' in record.data:
            #caccount auto create authkey if not provided
            accounts.append(caccount(record))
    storage.put(accounts)
Esempio n. 44
0
	def test_09_check_admin_rights(self):
		account = caccount(user='******')
		group = cgroup(name='administrator')
		group.add_accounts(account)
		
		record = crecord(admin_group=group._id,group='nothing',owner='refrigerator')
		
		check = record.check_write(account)
		
		if not check:
			raise Exception('Admin group are not handle ...')
Esempio n. 45
0
def get_cache(storage=None):
	global CACHE
		
	if not storage:
		storage = cstorage(caccount(), namespace='cache')

	if CACHE:
		return CACHE
	else:
		#global CACHE
		CACHE = ccache(storage, namespace='cache')	
		return CACHE
Esempio n. 46
0
def get_cache(storage=None):
    global CACHE

    if not storage:
        storage = cstorage(caccount(), namespace='cache')

    if CACHE:
        return CACHE
    else:
        #global CACHE
        CACHE = ccache(storage, namespace='cache')
        return CACHE
Esempio n. 47
0
    def test_09_check_admin_rights(self):
        account = caccount(user='******')
        group = cgroup(name='administrator')
        group.add_accounts(account)

        record = crecord(admin_group=group._id,
                         group='nothing',
                         owner='refrigerator')

        check = record.check_write(account)

        if not check:
            raise Exception('Admin group are not handle ...')
Esempio n. 48
0
    def test_07_CheckGet(self):
        record = STORAGE.get("account.wpain")
        record.cat()
        account = caccount(record)
        account.cat()

        if account.user != 'wpain':
            raise Exception('account.user: Corruption in load ...')

        if account.group != 'group.toto':
            raise Exception('account.group: Corruption in load ...')

        if account.groups != ['group.titi', 'group.tata']:
            raise Exception('account.groups: Corruption in load ...')
Esempio n. 49
0
    def resolve_selectors_name(self):
        if int(time.time()) > (self.last_resolv + 60):
            storage = get_storage(namespace='object',
                                  account=caccount(user="******", group="root"))
            records = storage.find(mfilter={'crecord_type': 'selector'},
                                   mfields=['crecord_name'])

            self.selectors_name = [
                record['crecord_name'] for record in records
            ]

            self.last_resolv = int(time.time())

            del storage
Esempio n. 50
0
def create_account(data):
	logger.debug(' + New account')
	new_account = caccount(
		user=data['user'],
		group=data.get('aaa_group', None),
		lastname=data['lastname'],
		firstname=data['firstname'],
		mail=data['mail']
	)

	new_account.external = data.get('external', False)

	#passwd
	passwd = data['passwd']
	new_account.passwd(passwd)
	logger.debug("   + Passwd: '%s'" % passwd)

	#secondary groups
	groups = []
	for group in data.get('groups', []):
		if group.find('group.') == -1:
			groups.append('group.%s' % group)
		else:
			groups.append(group)
	new_account.groups = groups
	
	storage = get_storage(namespace='object')

	#put record
	logger.debug(' + Save new account')
	new_account.chown(new_account._id)
	storage.put(new_account, account=root_account)
	
	#get rootdir
	logger.debug(' + Create view directory')
	rootdir = storage.get('directory.root', account=root_account)
	
	if rootdir:
		userdir = crecord({'_id': 'directory.root.%s' % new_account.user,'id': 'directory.root.%s' % new_account.user ,'expanded':'true'}, type='view_directory', name=new_account.user)
		userdir.chown(new_account._id)
		userdir.chgrp(new_account.group)
		userdir.chmod('g-w')
		userdir.chmod('g-r')

		rootdir.add_children(userdir)
		storage.put([rootdir,userdir], account=root_account)
	else:
		logger.error('Impossible to get rootdir')

	return new_account
Esempio n. 51
0
	def test_07_CheckGet(self):
		record = STORAGE.get("account.wpain")
		record.cat()
		account = caccount(record)
		account.cat()

		if account.user != 'wpain':
			raise Exception('account.user: Corruption in load ...')

		if account.group != 'group.toto':
			raise Exception('account.group: Corruption in load ...')

		if account.groups != ['group.titi', 'group.tata']:
			raise Exception('account.groups: Corruption in load ...')
Esempio n. 52
0
def check_authkey(key, account=None):
    storage = get_storage(namespace='object')

    mfilter = {
        'crecord_type': 'account',
        'authkey': key,
    }

    logger.debug("Search authkey: '%s'" % key)

    record = storage.find_one(mfilter=mfilter, account=caccount(user='******'))

    if not record:
        return None

    logger.debug(" + Done")
    key_account = caccount(record)

    if account and account._id != key_account._id:
        logger.debug(" + Account missmatch")
        return None

    return key_account
Esempio n. 53
0
def keyAuth(login=None, key=None):
	#-----------------------Get info------------------------
	if not login:
		login = request.params.get('login', default=None)
	if not key:
		key = request.params.get('key', default=None)
		
	if not login or not key:
		return HTTPError(404, "Invalid arguments")
	
	#---------------------Get storage/account-------------------
	_id = "account.%s" % login
	
	logger.debug(" + _id: %s" % _id)
	logger.debug(" + Login: %s" % login)
	logger.debug(" + key: %s" % key)
	
	storage = get_storage(namespace='object')

	try:
		account = caccount(storage.get(_id, account=caccount(user=login)))
	except Exception, err:
		logger.error('Error while fetching %s : %s' % (_id,err))
		return HTTPError(403, "There is no account for this login")
Esempio n. 54
0
def add_rotate_task():
    #### TODO: Remove this !!

    from crecord import crecord
    from caccount import caccount
    from cstorage import get_storage

    account = caccount(user="******", group="root")
    storage = get_storage(account=account, namespace='object')

    _id = 'schedule.pyperfstore_rotate'
    try:
        storage.remove(_id)
    except:
        pass
Esempio n. 55
0
    def __init__(self,
                 account,
                 namespace='object',
                 logging_level=logging.ERROR,
                 mongo_host="127.0.0.1",
                 mongo_port=27017,
                 mongo_db='canopsis',
                 mongo_autoconnect=True,
                 groups=[],
                 mongo_safe=True):

        try:
            self.mongo_host = CONFIG.get("master", "host")
        except:
            self.mongo_host = mongo_host

        try:
            self.mongo_port = CONFIG.getint("master", "port")
        except:
            self.mongo_port = mongo_port

        try:
            self.mongo_db = CONFIG.get("master", "db")
        except:
            self.mongo_db = mongo_db

        self.mongo_safe = mongo_safe

        self.account = account
        self.root_account = caccount(user="******", group="root")

        self.namespace = namespace
        self.backend = None

        self.logger = logging.getLogger('cstorage')
        self.logger.setLevel(logging_level)

        self.gridfs_namespace = "binaries"

        self.logger.debug("Object initialised.")

        self.backend = {}

        if mongo_autoconnect:
            self.backend_connect()