def wrapper(request, *args, **kwargs): pool = Pool() UserApplication = pool.get('res.user.application') authorization = wsgi_to_bytes(request.headers['Authorization']) try: auth_type, auth_info = authorization.split(None, 1) auth_type = auth_type.lower() except ValueError: abort(HTTPStatus.UNAUTHORIZED) if auth_type != b'bearer': abort(HTTPStatus.FORBIDDEN) application = UserApplication.check(bytes_to_wsgi(auth_info), name) if not application: abort(HTTPStatus.FORBIDDEN) transaction = Transaction() # TODO language with transaction.set_user(application.user.id), \ transaction.set_context(_check_access=True): try: response = func(request, *args, **kwargs) except Exception as e: if isinstance(e, HTTPException): raise logger.error('%s', request, exc_info=True) abort(HTTPStatus.INTERNAL_SERVER_ERROR, e) if not isinstance(response, Response) and json: response = Response(json_.dumps(response, cls=JSONEncoder), content_type='application/json') return response
def run(self): transaction = Transaction() Model = Pool().get(self.data['model']) with transaction.set_user(self.data['user']), \ transaction.set_context(self.data['context']): instances = self.data['instances'] # Ensure record ids still exist if isinstance(instances, int): with transaction.set_context(active_test=False): if Model.search([('id', '=', instances)]): instances = Model(instances) else: instances = None else: ids = set() with transaction.set_context(active_test=False): for sub_ids in grouped_slice(instances): records = Model.search([('id', 'in', list(sub_ids))]) ids.update(map(int, records)) if ids: instances = Model.browse( [i for i in instances if i in ids]) else: instances = None if instances is not None: getattr(Model, self.data['method'])( instances, *self.data['args'], **self.data['kwargs']) if not self.dequeued_at: self.dequeued_at = datetime.datetime.now() self.finished_at = datetime.datetime.now() self.save()
def domain_get(cls, model_name, mode='read'): transaction = Transaction() # root user above constraint if transaction.user == 0: if not transaction.context.get('user'): return with transaction.set_user(Transaction().context['user']): return cls.domain_get(model_name, mode=mode) assert mode in cls.modes key = (model_name, mode) + cls._get_cache_key() domain = cls._domain_get_cache.get(key, False) if domain is not False: return domain clause, clause_global = cls.get(model_name, mode=mode) clause = list(clause.values()) if clause: clause.insert(0, 'OR') clause_global = list(clause_global.values()) if clause_global: clause_global.insert(0, 'AND') if clause and clause_global: clause = ['AND', clause_global, clause] elif clause_global: clause = clause_global cls._domain_get_cache.set(key, clause) return clause
def wrapper(request, *args, **kwargs): pool = Pool() UserApplication = pool.get('res.user.application') authorization = request.headers['Authorization'] try: auth_type, auth_info = authorization.split(None, 1) auth_type = auth_type.lower() except ValueError: abort(401) if auth_type != b'bearer': abort(403) application = UserApplication.check(auth_info, name) if not application: abort(403) transaction = Transaction() # TODO language with transaction.set_user(application.user.id), \ transaction.set_context(_check_access=True): try: response = func(request, *args, **kwargs) except Exception, e: if isinstance(e, HTTPException): raise logger.error('%s', request, exc_info=True) abort(500, e)
def run(self): transaction = Transaction() Model = Pool().get(self.data['model']) with transaction.set_user(self.data['user']), \ transaction.set_context(self.data['context']): instances = self.data['instances'] # Ensure record ids still exist if isinstance(instances, int): if Model.search([('id', '=', instances)]): instances = Model(instances) else: instances = None else: ids = set() for sub_ids in grouped_slice(instances): records = Model.search([('id', 'in', list(sub_ids))]) ids.update(map(int, records)) if ids: instances = Model.browse( [i for i in instances if i in ids]) else: instances = None resultant_args = copy.copy(self.data['args']) if instances is not None: resultant_args = [instances] + resultant_args getattr(Model, self.data['method'])(*resultant_args, **self.data['kwargs']) self.finished()
def _get_context(): User = Pool().get('res.user') transaction = Transaction() user_id = transaction.user with transaction.set_context(_check_access=False, _datetime=None), \ transaction.set_user(0): user = EvalEnvironment(User(user_id), User) return { 'user': user, 'groups': User.get_groups() }
def test_user_employee(self): "Test user employee" pool = Pool() User = pool.get('res.user') transaction = Transaction() company = create_company() employee1 = create_employee(company, "Jim Halper") employee2 = create_employee(company, "Pam Bessly") employee3 = create_employee(company, "Michael Scott") user1, user2 = User.create([{ 'name': "Jim Halper", 'login': "******", 'companies': [('add', [company.id])], 'company': company.id, 'employees': [('add', [employee1.id, employee2.id])], 'employee': employee1.id, }, { 'name': "Pam Beesly", 'login': "******", 'companies': [('add', [company.id])], 'company': company.id, 'employees': [('add', [employee2.id])], 'employee': employee2.id, }]) with transaction.set_user(user1.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee1) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=employee2.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee2) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=None): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, None) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=employee3.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee1) self.assertEqual(user2.employee, employee2)
def test_user_root_company(self): "Test root user company" pool = Pool() User = pool.get('res.user') transaction = Transaction() company = create_company() root = User(0) root.company = None root.main_company = None root.save() with transaction.set_user(0): with Transaction().set_context(company=company.id): root = User(0) self.assertEqual(root.company, company)
def test_user_root_employee(self): "Test root user employee" pool = Pool() User = pool.get('res.user') transaction = Transaction() company = create_company() employee = create_employee(company, "Jim Halper") root = User(0) root.employee = None root.employees = None root.save() with transaction.set_user(0): with Transaction().set_context(employee=employee.id): root = User(0) self.assertEqual(root.employee, employee)
def push(cls, name, data, scheduled_at=None, expected_at=None): transaction = Transaction() database = transaction.database cursor = transaction.connection.cursor() with transaction.set_user(0): record, = cls.create([{ 'name': name, 'data': data, 'scheduled_at': scheduled_at, 'expected_at': expected_at, }]) if database.has_channel(): cursor.execute('NOTIFY "%s"', (cls.__name__,)) if not has_worker: transaction.tasks.append(record.id) return record.id
def test_user_company(self): 'Test user company' pool = Pool() User = pool.get('res.user') transaction = Transaction() company1 = create_company() company2 = create_company('Michael Scott Paper Company', currency=company1.currency) company2.save() company3 = create_company() user1, user2 = User.create([{ 'name': 'Jim Halper', 'login': '******', 'companies': [('add', [company1.id, company2.id])], 'company': company1.id, }, { 'name': 'Pam Beesly', 'login': '******', 'companies': [('add', [company2.id])], 'company': company2.id, }]) self.assertTrue(user1) with transaction.set_user(user1.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company1) self.assertEqual(user2.company, company2) with transaction.set_context({'company': company2.id}): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company2) self.assertEqual(user2.company, company2) with transaction.set_context({'company': None}): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, None) self.assertEqual(user2.company, company2) with transaction.set_context(company=company3.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company1) self.assertEqual(user2.company, company2)
def test_user_employee(self): "Test user employee" pool = Pool() User = pool.get('res.user') transaction = Transaction() company = create_company() employee1 = create_employee(company, "Jim Halper") employee2 = create_employee(company, "Pam Bessly") employee3 = create_employee(company, "Michael Scott") user1, user2 = User.create([{ 'name': "Jim Halper", 'login': "******", 'main_company': company.id, 'company': company.id, 'employees': [('add', [employee1.id, employee2.id])], 'employee': employee1.id, }, { 'name': "Pam Beesly", 'login': "******", 'main_company': company.id, 'company': company.id, 'employees': [('add', [employee2.id])], 'employee': employee2.id, }]) with transaction.set_user(user1.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee1) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=employee2.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee2) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=None): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, None) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=employee3.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee1) self.assertEqual(user2.employee, employee2)
def test_user_company(self): 'Test user company' pool = Pool() User = pool.get('res.user') transaction = Transaction() company1 = create_company() company2 = create_company('Michael Scott Paper Company', currency=company1.currency) company2.parent = company1 company2.save() company3 = create_company() user1, user2 = User.create([{ 'name': 'Jim Halper', 'login': '******', 'main_company': company1.id, 'company': company1.id, }, { 'name': 'Pam Beesly', 'login': '******', 'main_company': company2.id, 'company': company2.id, }]) self.assertTrue(user1) with transaction.set_user(user1.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company1) self.assertEqual(user2.company, company2) with transaction.set_context({'company': company2.id}): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company2) self.assertEqual(user2.company, company2) with transaction.set_context({'company': None}): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, None) self.assertEqual(user2.company, company2) with transaction.set_context(company=company3.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company1) self.assertEqual(user2.company, company2)
def transition_create_account(self): pool = Pool() AnalyticAccountTemplate = \ pool.get('analytic_account.account.template') Config = pool.get('ir.configuration') Account = pool.get('analytic_account.account') transaction = Transaction() company = self.account.company # Skip access rule with transaction.set_user(0): accounts = Account.search([('company', '=', company.id), ('type','=','root'), ('parent','=',None), ('root','=',None)]) if len(accounts)>=3: self.raise_user_warning('duplicated_chart.%d' % company, 'account_chart_exists', { 'company': company.rec_name, }) with transaction.set_context(language=Config.get_language(), company=company.id): # Create analytic plan analytic_templates = AnalyticAccountTemplate.search([ ('type','=','root'), ('parent','=',None), ('root','=',None) ]) for template in analytic_templates: template2account = {} #print ("TEMPLATE: ", str(template)) template.create_analytic_account( company.id, template2account=template2account, ) return 'end'
def transition_create_account(self): pool = Pool() AnalyticAccountTemplate = \ pool.get('analytic_account.account.template') Config = pool.get('ir.configuration') Account = pool.get('analytic_account.account') transaction = Transaction() company = self.account.company # Skip access rule with transaction.set_user(0): accounts = Account.search([('company', '=', company.id), ('type', '=', 'root'), ('parent', '=', None), ('root', '=', None)]) if len(accounts) >= 3: self.raise_user_warning('duplicated_chart.%d' % company, 'account_chart_exists', { 'company': company.rec_name, }) with transaction.set_context(language=Config.get_language(), company=company.id): # Create analytic plan analytic_templates = AnalyticAccountTemplate.search([ ('type', '=', 'root'), ('parent', '=', None), ('root', '=', None) ]) for template in analytic_templates: template2account = {} #print ("TEMPLATE: ", str(template)) template.create_analytic_account( company.id, template2account=template2account, ) return 'end'
def transition_create_budget(self): pool = Pool() BudgetTemplate = \ pool.get('account.budget.template') Budget = pool.get('account.budget') Config = pool.get('ir.configuration') transaction = Transaction() company = self.account.company fiscalyear = self.account.fiscalyear template = self.account.template # Skip access rule with transaction.set_user(0): budgets = Budget.search([ ('company', '=', company.id), ('fiscalyear','=',fiscalyear), ('parent','=',None), ]) if budgets: #raise BudgetExistForFiscalYear( # gettext('account_budget.msg_budget_already_exist', # fiscalyear=fiscalyear.name, # company=company.rec_name)) self.raise_user_error('budget_already_exists', { 'fiscalyear': fiscalyear.name, 'company': company.rec_name, }) with transaction.set_context(language=Config.get_language(), company=company.id): template2budget = {} template.create_budget( company.id, fiscalyear.id, template2budget=template2budget, ) return 'end'
def transition_create_account(self): pool = Pool() Config = pool.get('ir.configuration') Account = pool.get('account.account.meta.type') transaction = Transaction() company = self.account.company # Skip access rule with transaction.set_user(0): accounts = Account.search([()]) if accounts: self.raise_user_error('account_chart_exists') with transaction.set_context(language=Config.get_language(), company=company.id): account_template = self.account.account_template # Create account types template2type = {} account_template.create_type(company.id, template2type=template2type) return 'end'
def transition_create_account(self): pool = Pool() Config = pool.get('ir.configuration') Account = pool.get('account.account.meta.type') transaction = Transaction() company = self.account.company # Skip access rule with transaction.set_user(0): accounts = Account.search([()]) if accounts: self.raise_user_error('account_chart_exists') with transaction.set_context(language=Config.get_language(), company=company.id): account_template = self.account.account_template # Create account types template2type = {} account_template.create_type( company.id, template2type=template2type) return 'end'
def get(cls, model_name, mode='read'): "Return dictionary of non-global and global rules" pool = Pool() RuleGroup = pool.get('ir.rule.group') Model = pool.get('ir.model') RuleGroup_Group = pool.get('ir.rule.group-res.group') User_Group = pool.get('res.user-res.group') rule_table = cls.__table__() rule_group = RuleGroup.__table__() rule_group_group = RuleGroup_Group.__table__() user_group = User_Group.__table__() model = Model.__table__() transaction = Transaction() assert mode in cls.modes cursor = transaction.connection.cursor() user_id = transaction.user # root user above constraint if user_id == 0: user_id = transaction.context.get('user') if not user_id: return {}, {} cursor.execute(*rule_table.join( rule_group, condition=rule_group.id == rule_table.rule_group ).join(model, condition=rule_group.model == model.id).select( rule_table.id, where=(model.model == model_name) & (getattr(rule_group, 'perm_%s' % mode) == Literal(True)) & (rule_group.id.in_( rule_group_group.join( user_group, condition=(rule_group_group.group == user_group.group )).select(rule_group_group.rule_group, where=user_group.user == user_id)) | (rule_group.default_p == Literal(True)) | (rule_group.global_p == Literal(True))))) ids = [x for x, in cursor] # Test if there is no rule_group that have no rule cursor.execute(*rule_group.join( model, condition=rule_group.model == model.id).select( rule_group.id, where=(model.model == model_name) & ~rule_group.id.in_(rule_table.select(rule_table.rule_group)) & rule_group.id.in_( rule_group_group.join(user_group, condition=rule_group_group.group == user_group.group). select(rule_group_group.rule_group, where=user_group.user == user_id)))) no_rules = cursor.fetchone() clause = defaultdict(lambda: ['OR']) clause_global = defaultdict(lambda: ['OR']) decoder = PYSONDecoder(cls._get_context()) # Use root user without context to prevent recursion with transaction.set_user(0), transaction.set_context(user=0): for rule in cls.browse(ids): assert rule.domain, ('Rule domain empty,' 'check if migration was done') dom = decoder.decode(rule.domain) if rule.rule_group.global_p: clause_global[rule.rule_group].append(dom) else: clause[rule.rule_group].append(dom) if no_rules: group_id = no_rules[0] clause[RuleGroup(group_id)] = [] return clause, clause_global
def transition_create_account(self): pool = Pool() TaxCodeTemplate = pool.get('account.tax.code.template') TaxCodeLineTemplate = pool.get('account.tax.code.line.template') TaxTemplate = pool.get('account.tax.template') TaxRuleTemplate = pool.get('account.tax.rule.template') TaxRuleLineTemplate = \ pool.get('account.tax.rule.line.template') Config = pool.get('ir.configuration') Account = pool.get('account.account') transaction = Transaction() company = self.account.company # Skip access rule with transaction.set_user(0): accounts = Account.search([('company', '=', company.id)], limit=1) if accounts: self.raise_user_warning('duplicated_chart.%d' % company.id, 'account_chart_exists', { 'company': company.rec_name, }) with transaction.set_context(language=Config.get_language(), company=company.id): account_template = self.account.account_template account_meta_template = self.account.meta_type # Get account meta types template2meta_type = {} account_meta_template.update_type(template2type=template2meta_type) # Create account types template2type = {} account_template.type.create_type( company.id, template2type=template2type, template2meta_type=template2meta_type) # Create accounts template2account = {} account_template.create_account( company.id, template2account=template2account, template2type=template2type) # Create taxes template2tax = {} TaxTemplate.create_tax( account_template.id, company.id, template2account=template2account, template2tax=template2tax) # Create tax codes template2tax_code = {} TaxCodeTemplate.create_tax_code( account_template.id, company.id, template2tax_code=template2tax_code) # Create tax code lines template2tax_code_line = {} TaxCodeLineTemplate.create_tax_code_line( account_template.id, template2tax=template2tax, template2tax_code=template2tax_code, template2tax_code_line=template2tax_code_line) # Update taxes and replaced_by on accounts account_template.update_account2(template2account, template2tax) # Create tax rules template2rule = {} TaxRuleTemplate.create_rule( account_template.id, company.id, template2rule=template2rule) # Create tax rule lines template2rule_line = {} TaxRuleLineTemplate.create_rule_line( account_template.id, template2tax, template2rule, template2rule_line=template2rule_line) return 'properties'
def get(cls, model_name, mode='read'): "Return dictionary of non-global and global rules" pool = Pool() RuleGroup = pool.get('ir.rule.group') Model = pool.get('ir.model') RuleGroup_Group = pool.get('ir.rule.group-res.group') User_Group = pool.get('res.user-res.group') rule_table = cls.__table__() rule_group = RuleGroup.__table__() rule_group_group = RuleGroup_Group.__table__() user_group = User_Group.user_group_all_table() model = Model.__table__() transaction = Transaction() assert mode in cls.modes model_names = [] model2field = defaultdict(list) def update_model_names(Model, path=None): if Model.__name__ in model_names: return model_names.append(Model.__name__) if path: model2field[Model.__name__].append(path) for field_name in Model.__access__: field = getattr(Model, field_name) Target = field.get_target() if path: target_path = path + '.' + field_name else: target_path = field_name update_model_names(Target, target_path) update_model_names(pool.get(model_name)) cursor = transaction.connection.cursor() user_id = transaction.user # root user above constraint if user_id == 0: return {}, {} cursor.execute(*rule_table.join(rule_group, condition=rule_group.id == rule_table.rule_group ).join(model, condition=rule_group.model == model.id ).select(rule_table.id, where=(model.model.in_(model_names)) & (getattr(rule_group, 'perm_%s' % mode) == Literal(True)) & (rule_group.id.in_( rule_group_group.join( user_group, condition=(rule_group_group.group == user_group.group) ).select(rule_group_group.rule_group, where=user_group.user == user_id) ) | (rule_group.default_p == Literal(True)) | (rule_group.global_p == Literal(True)) ))) ids = [x for x, in cursor] # Test if there is no rule_group that have no rule cursor.execute(*rule_group.join(model, condition=rule_group.model == model.id ).select(rule_group.id, where=(model.model.in_(model_names)) & ~rule_group.id.in_(rule_table.select(rule_table.rule_group)) & rule_group.id.in_(rule_group_group.join(user_group, condition=rule_group_group.group == user_group.group ).select(rule_group_group.rule_group, where=user_group.user == user_id)))) no_rules = cursor.fetchone() clause = defaultdict(lambda: ['OR']) clause_global = defaultdict(lambda: ['OR']) decoder = PYSONDecoder(cls._get_context()) # Use root user without context to prevent recursion with transaction.set_user(0), transaction.set_context(user=0): for rule in cls.browse(ids): assert rule.domain, ('Rule domain empty,' 'check if migration was done') dom = decoder.decode(rule.domain) target_model = rule.rule_group.model.model if target_model in model2field: target_dom = ['OR'] for field in model2field[target_model]: target_dom.append((field, 'where', dom)) dom = target_dom if rule.rule_group.global_p: clause_global[rule.rule_group].append(dom) else: clause[rule.rule_group].append(dom) if no_rules: group_id = no_rules[0] clause[RuleGroup(group_id)] = [] return clause, clause_global