Example #1
0
def export(ctx, language, db_name, module, fix):
    modules = module or ['all']

    from odoo.modules.registry import Registry
    from odooku.api import environment
    from odoo.tools import trans_export

    with tempfile.TemporaryFile() as t:

        # Perform checks (and possible fixes)
        registry = Registry(db_name)
        with registry.cursor() as cr:
            with environment(cr) as env:
                lang = env['res.lang'].with_context(
                    dict(active_test=False)).search([('code', '=', language)])
                if not lang:
                    raise ValueError("Language %s does not exist" % language)
                if not lang[0].active:
                    if not fix:
                        raise ValueError("Language %s is not activated" %
                                         language)
                    else:
                        installed = env['ir.module.module'].search([
                            ('state', '=', 'installed')
                        ])
                        installed._update_translations(language)

                if module:
                    installed = env['ir.module.module'].search([
                        ('name', 'in', module), ('state', '=', 'installed')
                    ])
                    missing = set(module) - set(
                        [mod.name for mod in installed])
                    if missing:
                        if not fix:
                            raise ValueError("Modules '%s' are not installed" %
                                             ", ".join(missing))
                        else:
                            ctx.obj['config']['init'] = {
                                module_name: 1
                                for module_name in module
                            }

        # Export
        registry = Registry.new(db_name, update_module=fix)
        with registry.cursor() as cr:
            with environment(cr) as env:
                trans_export(language, modules, t, 'po', cr)

        t.seek(0)
        # Pipe to stdout
        while True:
            chunk = t.read(CHUNK_SIZE)
            if not chunk:
                break
            sys.stdout.buffer.write(chunk)
Example #2
0
class TestLocker(InforTestCase):
    def setUp(self):
        super().setUp()
        self.registry2 = Registry(common.get_db_name())
        self.cr2 = self.registry2.cursor()
        self.env2 = api.Environment(self.cr2, self.env.uid, {})

        @self.addCleanup
        def reset_cr2():
            # rollback and close the cursor, and reset the environments
            self.env2.reset()
            self.cr2.rollback()
            self.cr2.close()

        self.backend2 = self.env2['infor.backend'].browse(self.backend.id)

    def test_lock(self):
        """Lock a record"""
        main_partner = self.env.ref('base.main_partner')
        work = WorkContext(model_name='res.partner', collection=self.backend)
        locker = work.component_by_name('infor.record.locker')
        locker.lock(main_partner)

        main_partner2 = self.env2.ref('base.main_partner')
        work2 = WorkContext(model_name='res.partner', collection=self.backend2)
        locker2 = work2.component_by_name('infor.record.locker')
        with self.assertRaises(RetryableJobError):
            locker2.lock(main_partner2)
Example #3
0
class TestLocker(TransactionComponentRegistryCase):
    def setUp(self):
        super().setUp()
        self.backend = mock.MagicMock(name="backend")
        self.backend.env = self.env

        self.registry2 = Registry(common.get_db_name())
        self.cr2 = self.registry2.cursor()
        self.env2 = api.Environment(self.cr2, self.env.uid, {})
        self.backend2 = mock.MagicMock(name="backend2")
        self.backend2.env = self.env2

        @self.addCleanup
        def reset_cr2():
            # rollback and close the cursor, and reset the environments
            self.env2.reset()
            self.cr2.rollback()
            self.cr2.close()

    def test_lock(self):
        """Lock a record"""
        main_partner = self.env.ref("base.main_partner")
        work = WorkContext(model_name="res.partner", collection=self.backend)
        work.component("record.locker").lock(main_partner)

        main_partner2 = self.env2.ref("base.main_partner")
        work2 = WorkContext(model_name="res.partner", collection=self.backend2)
        locker2 = work2.component("record.locker")
        with self.assertRaises(RetryableJobError):
            locker2.lock(main_partner2)
class TestAdvisoryLock(TransactionComponentCase):
    def setUp(self):
        super(TestAdvisoryLock, self).setUp()
        self.registry2 = Registry(common.get_db_name())
        self.cr2 = self.registry2.cursor()
        self.env2 = api.Environment(self.cr2, self.env.uid, {})

        @self.addCleanup
        def reset_cr2():
            # rollback and close the cursor, and reset the environments
            self.env2.reset()
            self.cr2.rollback()
            self.cr2.close()

    def test_concurrent_lock(self):
        """ 2 concurrent transactions cannot acquire the same lock """
        # the lock is based on a string, a second transaction trying
        # to acquire the same lock won't be able to acquire it
        lock = 'import_record({}, {}, {}, {})'.format(
            'backend.name',
            1,
            'res.partner',
            '999999',
        )
        acquired = pg_try_advisory_lock(self.env, lock)
        self.assertTrue(acquired)
        # we test the base function
        inner_acquired = pg_try_advisory_lock(self.env2, lock)
        self.assertFalse(inner_acquired)

    def test_concurrent_import_lock(self):
        """ A 2nd concurrent transaction must retry """
        # the lock is based on a string, a second transaction trying
        # to acquire the same lock won't be able to acquire it
        lock = 'import_record({}, {}, {}, {})'.format(
            'backend.name',
            1,
            'res.partner',
            '999999',
        )

        backend = mock.MagicMock()
        backend.env = self.env
        work = WorkContext(model_name='res.partner', collection=backend)
        # we test the function through a Component instance
        component = work.component_by_name('base.connector')
        # acquire the lock
        component.advisory_lock_or_retry(lock)

        # instanciate another component using a different odoo env
        # hence another PG transaction
        backend2 = mock.MagicMock()
        backend2.env = self.env2
        work2 = WorkContext(model_name='res.partner', collection=backend2)
        component2 = work2.component_by_name('base.connector')
        with self.assertRaises(RetryableJobError) as cm:
            component2.advisory_lock_or_retry(lock, retry_seconds=3)
            self.assertEqual(cm.exception.seconds, 3)
Example #5
0
def newdbuuid(ctx, db_name):
    config = (ctx.obj['config'])

    from odoo.modules.registry import Registry
    from odooku.api import environment

    registry = Registry(db_name)
    with registry.cursor() as cr:
        with environment(cr) as env:
            env['ir.config_parameter'].init(force=True)
Example #6
0
 def create_user(self, login_name, help_id, db_name):
     result = {}
     result['is_success'] = True
     registry = Registry(db_name)
     cr = registry.cursor()
     env = api.Environment(cr, SUPERUSER_ID, {})
     user_id = env['res.users'].create_wechat_mini_user(login_name, help_id)
     result['user_id'] = user_id
     cr.commit()
     cr.close()
     return json.dumps(result)
Example #7
0
def authenticate(token):
    try:
        a = 4 - len(token) % 4
        if a != 0:
            token += '==' if a == 2 else '='
        SERVER, db, login, uid, ts = base64.urlsafe_b64decode(
            str(token)).split(',')
        if int(ts) + 60 * 60 * 24 * 7 * 10 < time.time():
            return False
        registry = Registry(db)
        cr = registry.cursor()
        env = api.Environment(cr, int(uid), {})
    except Exception as e:
        return str(e)
    return env
Example #8
0
def update(ctx, db_name, module, language, overwrite):
    context = {'overwrite': overwrite}

    from odoo.modules.registry import Registry
    from odooku.api import environment

    domain = [('state', '=', 'installed')]
    if module:
        domain = [('name', 'in', module)]

    for db in db_name:
        registry = Registry(db)
        with registry.cursor() as cr:
            with environment(cr) as env:
                mods = env['ir.module.module'].search(domain)
                mods.with_context(
                    overwrite=overwrite)._update_translations(language)
Example #9
0
def shell(ctx, input_file, db_name):
    from odoo.modules.registry import Registry
    from odooku.api import environment
    registry = Registry(db_name)

    with registry.cursor() as cr:
        with environment(cr) as env:
            context = {
                'env': env,
                'self': env.user
            }

            args = []
            if input_file is not None:
                args = [input_file]

            bpython.embed(context, args=args, banner='Odooku shell')
Example #10
0
    def cenit_post(self, action, root=None):
        status_code = 400
        environ = request.httprequest.headers.environ.copy()

        key = environ.get('HTTP_X_USER_ACCESS_KEY', False)
        token = environ.get('HTTP_X_USER_ACCESS_TOKEN', False)
        db_name = environ.get('HTTP_TENANT_DB', False)

        if not db_name:
            host = environ.get('HTTP_HOST', "")
            db_name = host.replace(".", "_").split(":")[0]

        registry = Registry(db_name)
        with registry.cursor() as cr:
            connection_model = registry['cenit.connection']
            domain = [('key', '=', key), ('token', '=', token)]
            _logger.info(
                "Searching for a 'cenit.connection' with key '%s' and "
                "matching token", key)
            rc = connection_model.search(cr, SUPERUSER_ID, domain)
            _logger.info("Candidate connections: %s", rc)
            if rc:
                p = inflect.engine()
                flow_model = registry['cenit.flow']
                context = {'sender': 'client', 'action': action}

                if root is None:
                    for root, data in request.jsonrequest.items():
                        root = p.singular_noun(root) or root
                        rc = flow_model.receive(cr, SUPERUSER_ID, root, data,
                                                context)
                        if rc:
                            status_code = 200
                else:
                    root = p.singular_noun(root) or root
                    rc = flow_model.receive(cr, SUPERUSER_ID, root,
                                            request.jsonrequest, context)
                    if rc:
                        status_code = 200
            else:
                status_code = 404

        return {'status': status_code}
Example #11
0
def execute(conf_attrs, dbname, uid, obj, method, *args, **kwargs):
    _logger.info(str([dbname, uid, obj, method, args, kwargs]))

    if conf_attrs and len(conf_attrs.keys()) > 1:
        for attr, value in conf_attrs.items():
            odoo.tools.config[attr] = value
    with Environment.manage():
        registry = Registry(dbname)
        cr = registry.cursor()
        context = 'context' in kwargs and kwargs.pop('context') or {}
        env = Environment(cr, uid, context)
        cr.autocommit(True)
        # odoo.api.Environment._local.environments = env
        try:
            Model = env[obj]
            args = list(args)
            _logger.info('>>> %s' % str(args))
            ids = args.pop(0)
            if ids:
                target = Model.search([('id', 'in', ids)])
            else:
                target = Model
            getattr(env.registry[obj], method)(target, *args, **kwargs)
            # Commit only when function finish
            # env.cr.commit()
        except Exception as exc:
            env.cr.rollback()
            import traceback
            traceback.print_exc()
            raise exc
            #try:
            #    raise execute.retry(
            #        queue=execute.request.delivery_info['routing_key'],
            #        exc=exc, countdown=(execute.request.retries + 1) * 60,
            #        max_retries=5)
            #except Exception as retry_exc:
            #    raise retry_exc
        finally:
            env.cr.close()
    return True
Example #12
0
def import_(ctx, language, db_name, overwrite):
    context = {'overwrite': overwrite}

    from odoo.modules.registry import Registry
    from odooku.api import environment
    from odoo.tools import trans_load

    with tempfile.NamedTemporaryFile(suffix='.po', delete=False) as t:
        registry = Registry(db_name)

        # Read from stdin
        while True:
            chunk = sys.stdin.buffer.read(CHUNK_SIZE)
            if not chunk:
                break
            t.write(chunk)
        t.close()

        with registry.cursor() as cr:
            with environment(cr) as env:
                trans_load(cr, t.name, language, context=context)

        os.unlink(t.name)
Example #13
0
    return hash_gen.hexdigest()[:length]


# Read OAuth2 constants and setup the token store:
db_name = odoo.tools.config.get('db_name')
if not db_name:
    _logger.error(
        "ERROR: To proper setup OAuth2 and Token Store - it's necessary to set the parameter 'db_name' in Odoo config file!"
    )
    print(
        "ERROR: To proper setup OAuth2 and Token Store - it's necessary to set the parameter 'db_name' in Odoo config file!"
    )
else:
    # Read system parameters...
    registry = Registry(db_name)
    with registry.cursor() as cr:
        cr.execute("SELECT value FROM ir_config_parameter \
            WHERE key = 'rest_api.use_redis_token_store'")
        res = cr.fetchone()
        use_redis_token_store = res and res[0].strip()
        if use_redis_token_store in ('0', 'False', 'None', 'false'):
            use_redis_token_store = False
        if not use_redis_token_store:
            # Setup Simple token store
            _logger.info("Setup Simple token store...")
            from . import simple_token_store
            token_store = simple_token_store.SimpleTokenStore()
        else:
            # Setup Redis token store
            _logger.info("Setup Redis token store...")
            cr.execute("SELECT value FROM ir_config_parameter \
Example #14
0
    def web_login(self, redirect=None, **kw):
        ensure_db()
        request.params['login_success'] = False
        if request.httprequest.method == 'GET' and redirect and request.session.uid:
            return http.redirect_with_hash(redirect)

        if not request.uid:
            request.uid = SUPERUSER_ID
        values = request.params.copy()
        try:
            values['databases'] = http.db_list()
        except exceptions.AccessDenied:
            values['databases'] = None

        # 只特殊处理post的情况
        if request.httprequest.method == 'POST':
            registry = Registry(request.session.db)
            with registry.cursor() as cr:
                env = api.Environment(cr, 1, {})
                login_user = env['res.users'].search([
                    ('login', '=', request.params['login'])
                ])
                time_limit = int(env['ir.config_parameter'].get_param(
                    'auth_time_limit.login_error_times'))

                # 9次失败之后,不再后台验证密码,直接返回
                if login_user and login_user.login_error_times >= time_limit:
                    values['error'] = u'账户已被锁定!'
                    return request.render('web.login', values)

                old_uid = request.uid
                uid = request.session.authenticate(request.session.db,
                                                   request.params['login'],
                                                   request.params['password'])

                # 登录成功
                if uid is not False:
                    login_user.login_error_times = 0
                    request.params['login_success'] = True
                    if not redirect:
                        redirect = '/web'
                    return http.redirect_with_hash(redirect)

                # 登录失败
                request.uid = old_uid
                if login_user.exists():
                    try:
                        login_user.sudo(login_user.id).check_credentials(
                            request.params['password'])
                    except exceptions.AccessDenied:
                        # 密码错误
                        login_user.login_error_times += 1
                        if login_user.login_error_times == time_limit:
                            values['error'] = u'账户已被锁定!'
                        elif login_user.login_error_times >= time_limit - 3:
                            values['error'] = u"您还有%s次机会!" % (
                                time_limit - login_user.login_error_times)
                        else:
                            values['error'] = _("Wrong login/password")
                    else:
                        # 密码正确, 其他验证失败, allowed_ips
                        values['error'] = u'访问受限,请与管理员联系。'
                else:
                    # 无此用户, 或者此用户active = False
                    values['error'] = u"无此用户"

        return request.render('web.login', values)
Example #15
0
def register(db, uid):
    registry = Registry(db)
    cr = registry.cursor()
    env = api.Environment(cr, int(uid), {})
    return env
Example #16
0
File: models.py Project: lnkdel/bq
def register(db, uid, lang=None):
    registry = Registry(db)
    cr = registry.cursor()
    context = {lang: lang} if lang else {}
    env = api.Environment(cr, int(uid), context)
    return env