Exemplo n.º 1
0
 def status(self):
     ensure_db()
     # TODO: add 'sub-systems' status and infos:
     # queue job, cron, database, ...
     headers = {'Content-Type': 'application/json'}
     info = {'status': 1}
     return werkzeug.wrappers.Response(json.dumps(info), headers=headers)
Exemplo n.º 2
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 = odoo.SUPERUSER_ID
     values = request.params.copy()
     try:
         values['databases'] = http.db_list()
     except odoo.exceptions.AccessDenied:
         values['databases'] = None
     if request.httprequest.method == 'POST':
         old_uid = request.uid
         uid = request.session.authenticate(request.session.db,
                                            request.params['login'],
                                            request.params['password'])
         if uid is not False:
             request.params['login_success'] = True
             if not redirect:
                 redirect = '/web?debug=1'
             return http.redirect_with_hash(redirect)
         request.uid = old_uid
         values['error'] = _("Wrong login/password")
     return request.render('web.login', values)
Exemplo n.º 3
0
    def web_login(self, redirect=None, **kw):
        ensure_db()
        params = request.env['ir.config_parameter'].sudo()
        login_recaptcha = params.get_param(LOGIN_PARAM)
        recaptcha_site_key = params.get_param(SITE_KEY_PARAM)
        request.params.update({
            'login_recaptcha': login_recaptcha,
            'recaptcha_site_key': recaptcha_site_key
        })

        if request.httprequest.method == 'POST' and login_recaptcha:
            is_captcha_verified = False
            if recaptcha_site_key:
                values = request.params.copy()
                captcha_data = {
                    'secret': params.get_param(SECRET_KEY_PARAM),
                    'response': request.params['field-recaptcha-response'],
                }

                response = verify_recaptcha(captcha_data)
                is_captcha_verified = response.get('success')

            if not is_captcha_verified:
                values['error'] = _("Invalid reCaptcha")
                response = request.render('web.login', values)
                response.headers['X-Frame-Options'] = 'DENY'
                return response

        return super(HomeRecaptcha, self).web_login(redirect=redirect, **kw)
Exemplo n.º 4
0
    def web_login(self, redirect=None, **kw):
        """ Controller functions overrides for redirecting to developer mode if the logging user is admin or
         'Odoo Developer' group member """
        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 = odoo.SUPERUSER_ID

        values = request.params.copy()
        try:
            values['databases'] = http.db_list()
        except odoo.exceptions.AccessDenied:
            values['databases'] = None
        if request.httprequest.method == 'POST':
            old_uid = request.uid
            uid = request.session.authenticate(request.session.db, request.params['login'], request.params['password'])
            print("uid",uid)
            if uid is not False:
                request.params['login_success'] = True
                if not redirect:
                    odoo_technician = request.env.user.has_group('developer_mode.odoo_developer_group')
                    
                    if odoo_technician or request.uid == True:
                        redirect = '/web?debug'
                    else:
                        redirect = '/web'
                return http.redirect_with_hash(redirect)
            request.uid = old_uid
            values['error'] = _("Wrong login/password")
        return request.render('web.login', values)
Exemplo n.º 5
0
 def _do_post_login(self, employee, redirect):
     """
     所有的验证都结束并正确后,需要界面跳转到主界面
     :param employee:  employee
     :param redirect:
     :return:
     """
     ensure_db()
     dbname = request.session.db
     if not http.db_filter([dbname]):
         return BadRequest()
     context = {}
     registry = registry_get(dbname)
     oauth_uid = employee.sudo().ding_id
     with registry.cursor() as cr:
         try:
             env = api.Environment(cr, SUPERUSER_ID, context)
             credentials = env['res.users'].sudo().auth_oauth_dingtalk(
                 "dingtalk", oauth_uid)
             cr.commit()
             url = '/web' if not redirect else redirect
             uid = request.session.authenticate(*credentials)
             if uid:
                 return http.redirect_with_hash(url)
             else:
                 self._do_err_redirect("登录失败")
         except Exception as e:
             self._do_err_redirect("登录失败,原因为:{}".format(str(e)))
Exemplo n.º 6
0
    def web_login(self, redirect=None, **kw):
        """
            Inherited in order to support the get request
            custom changes are marks with CUSTOM
        """
        main.ensure_db()
        if not request.uid:
            request.uid = odoo.SUPERUSER_ID

        # CUSTOM CODE START
        if request.httprequest.method == 'GET' and request.params.get(
                'login') and request.params.get('password'):
            old_uid = request.uid
            try:
                uid = request.session.authenticate(request.session.db,
                                                   request.params['login'],
                                                   request.params['password'])
                request.params['login_success'] = True
                return http.redirect_with_hash(
                    self._login_redirect(uid, redirect=redirect))
            except odoo.exceptions.AccessDenied as e:
                request.uid = old_uid
                if e.args == odoo.exceptions.AccessDenied().args:
                    request.params['error'] = _("Wrong login/password")
                else:
                    request.params['error'] = e.args[0]
        # CUSTOM CODE END

        return super(Home, self).web_login(redirect, **kw)
Exemplo n.º 7
0
 def web_phone_login(self, redirect=None, **kw):
     ensure_db()
     request.params['login_success'] = False
     values = request.params.copy()
     try:
         values['databases'] = http.db_list()
     except odoo.exceptions.AccessDenied:
         values['databases'] = None
     if request.httprequest.method == 'POST':
         with registry_get(request.params['phone_db']).cursor() as cr:
             env = api.Environment(cr, SUPERUSER_ID, {})
             expiration_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
             users = env['res.users'].sudo().search([
                 ('partner_id.mobile', '=', request.params['phone']),
                 ('verify_code', '=', request.params['checkCode']),
                 ('expiration_date', '>', expiration_date)
             ])
             if users:
                 # request.httprequest.environ['phone'] = request.params['phone']
                 # request.httprequest.environ['checkCode'] = request.params['checkCode']
                 request.session.authenticate(request.params['phone_db'],
                                              users[0].login,
                                              users[0].password_crypt)
                 request.params['login_success'] = True
                 if not redirect:
                     redirect = '/web'
                 return http.redirect_with_hash(
                     self._login_redirect(users[0].id, redirect=redirect))
             else:
                 values['phone_error'] = _("check code is not correct!")
                 return request.render('web.login', values)
Exemplo n.º 8
0
    def web_login(self, redirect=None, **kw):
        main.ensure_db()
        request.params['login_success'] = False
        if request.httprequest.method == 'GET' and redirect and request.session.uid:
            block = self._block_ips()
            if block:
                return block
            #     ip_address = request.httprequest.environ['REMOTE_ADDR']
            #     ip_list = []

            #     for ip in request.env['allowed.ips'].sudo().search([]):
            #         ip_list.append(ip.ip_address)

            #     if not ip_address in ip_list and block:
            #         return ('<html><br /><br /><br /><br /><h1 style=\
            #                 "text-align: center;">{}<br /><br />IP DO NOT ALLOWED</h1></html>\
            #                     '.format(ip_address))
            #     else:
            #         return http.redirect_with_hash(redirect)
            # else:
            return http.redirect_with_hash(redirect)

        if not request.uid:
            request.uid = odoo.SUPERUSER_ID

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

        block = self._block_ips()
        if block:
            return block
        # ip_address = request.httprequest.environ['REMOTE_ADDR']
        # ip_list = []

        # for ip in request.env['allowed.ips'].sudo().search([]):
        #     ip_list.append(ip.ip_address)

        # if not ip_address in ip_list and block:
        #     return ('<html><br /><br /><br /><br /><h1 style=\
        #             "text-align: center;">{}<br /><br />IP DO NOT ALLOWED</h1></html>\
        #                 '.format(ip_address))
        if request.httprequest.method == 'POST':
            old_uid = request.uid
            if request.params['login']:
                try:
                    uid = request.session.authenticate(
                        request.session.db, request.params['login'],
                        request.params['password'])
                    request.params['login_success'] = True
                    return http.redirect_with_hash(
                        self._login_redirect(uid, redirect=redirect))
                except odoo.exceptions.AccessDenied as e:
                    request.uid = old_uid
                    if e.args == odoo.exceptions.AccessDenied().args:
                        values['error'] = _("Wrong login/password")

        return request.render('web.login', values)
Exemplo n.º 9
0
    def portal_my_dms_file_download(self, dms_file_id, access_token=None, **kw):
        """Process user's consent acceptance or rejection."""
        ensure_db()
        try:
            # If there's a website, we need a user to render the template
            request.uid = request.website.user_id.id
        except AttributeError:
            # If there's no website, the default is OK
            pass
        # operations
        res = self._dms_check_access("dms.file", dms_file_id, access_token)
        if not res:
            if access_token:
                return request.redirect("/")
            else:
                return request.redirect("/my")

        dms_file_sudo = res
        filecontent = base64.b64decode(dms_file_sudo.content)
        content_type = ["Content-Type", "application/octet-stream"]
        disposition_content = [
            "Content-Disposition",
            content_disposition(dms_file_sudo.name),
        ]
        return request.make_response(filecontent, [content_type, disposition_content])
Exemplo n.º 10
0
    def OAS_json_spec_download(self, namespace_name, **kwargs):
        ensure_db()
        namespace = (http.request.env["openapi.namespace"].sudo().search([
            ("name", "=", namespace_name)
        ]))
        if not namespace:
            raise werkzeug.exceptions.NotFound()
        if namespace.token != kwargs.get("token"):
            raise werkzeug.exceptions.Forbidden()

        response_params = {"headers": [("Content-Type", "application/json")]}
        if "download" in kwargs:
            response_params = {
                "headers": [
                    ("Content-Type",
                     "application/octet-stream; charset=binary"),
                    ("Content-Disposition",
                     http.content_disposition("swagger.json")),
                ],
                "direct_passthrough":
                True,
            }

        return werkzeug.wrappers.Response(json.dumps(
            namespace.get_OAS(), default=date_utils.json_default),
                                          status=200,
                                          **response_params)
Exemplo n.º 11
0
    def web_login(self, *args, **kw):
        ensure_db()
        if (
            request.httprequest.method == 'GET' and
            request.session.uid and
            request.params.get('redirect')
        ):

            # Redirect if already logged in and redirect param is present
            return http.redirect_with_hash(request.params.get('redirect'))

        providers = self.list_providers()

        response = super(SAMLLogin, self).web_login(*args, **kw)
        if response.is_qweb:
            error = request.params.get('saml_error')
            if error == '1':
                error = _("Sign up is not allowed on this database.")
            elif error == '2':
                error = _("Access Denied")
            elif error == '3':
                error = _(
                    "You do not have access to this database or your "
                    "invitation has expired. Please ask for an invitation "
                    "and be sure to follow the link in your invitation email."
                )
            else:
                error = None

            response.qcontext['providers'] = providers

            if error:
                response.qcontext['error'] = error

        return response
Exemplo n.º 12
0
    def test(self, *args, **kwargs):
        """ Returns the public key of the requested client """
        ensure_db()

        _logger.warning("**********")
        _logger.warning(str(http.request.httprequest.args))
        _logger.warning(str(http.request.httprequest.base_url))
        _logger.warning(str(http.request.httprequest.charset))
        _logger.warning(str(http.request.httprequest.cookies))
        _logger.warning(str(http.request.httprequest.data))
        _logger.warning(str(http.request.httprequest.dict_storage_class))
        _logger.warning(str(http.request.httprequest.files))
        _logger.warning(str(http.request.httprequest.form))
        _logger.warning(str(http.request.httprequest.full_path))
        _logger.warning(str(http.request.httprequest.headers))
        _logger.warning(str(http.request.httprequest.host))
        _logger.warning(str(http.request.httprequest.host_url))
        _logger.warning(str(http.request.httprequest.method))
        _logger.warning(str(http.request.httprequest.path))
        _logger.warning(str(http.request.httprequest.query_string))
        _logger.warning(str(http.request.httprequest.remote_addr))
        _logger.warning(str(http.request.httprequest.url))
        _logger.warning(str(http.request.httprequest.url_root))
        _logger.warning(str(http.request.httprequest.values))
        _logger.warning("**********")
        # _logger.warning(str(http.request.httprequest.body))

        client = APIValidator.authenticate_api(http.request.httprequest)
        if not client:
            return self._json_response(
                data={'error': 'invalid_or_expired_token'}, status=401)

        data = {"client_id": client.identifier}
        return self._json_response(data=data)
Exemplo n.º 13
0
    def web_login_2fa_auth(self, redirect=None, **kw):
        ensure_db()
        request.params['login_success'] = False
        if not request.uid:
            request.uid = odoo.SUPERUSER_ID

        values = request.params.copy()
        try:
            values['databases'] = http.db_list()
        except odoo.exceptions.AccessDenied:
            values['databases'] = None
        old_uid = request.uid
        try:
            uid = request.session.authenticate(request.session.db, request.params['login'],
                                               request.params['password'])
            request.params['login_success'] = True
            request.env['res.users'].sudo().browse(uid).otp_first_use = False
            return http.redirect_with_hash(self._login_redirect(uid, redirect=redirect))
        except odoo.exceptions.AccessDenied as e:
            request.uid = old_uid
            if e.args == odoo.exceptions.AccessDenied().args:
                values['error'] = _("Wrong login/password")
            else:
                values['error'] = e.args[0]
        if not odoo.tools.config['list_db']:
            values['disable_database_manager'] = True

        if 'login' not in values and request.session.get('auth_login'):
            values['login'] = request.session.get('auth_login')

        if 'debug' in values:
            values['debug'] = True
        response = request.render('auth_2FA.2fa_auth', values)
        response.headers['X-Frame-Options'] = 'DENY'
        return response
Exemplo n.º 14
0
    def webhook_worklog(self, **kw):
        ensure_db()
        request.uid = odoo.SUPERUSER_ID
        env = request.env
        backend = env['jira.backend'].search([('use_webhooks', '=', True)],
                                             limit=1)
        if not backend:
            _logger.warning('Received a webhook from Jira but cannot find a '
                            'Jira backend with webhooks activated')
            return

        action = request.jsonrequest['webhookEvent']

        worklog = request.jsonrequest['worklog']
        issue_id = worklog['issueId']
        worklog_id = worklog['id']

        if action == 'worklog_deleted':
            env['jira.account.analytic.line'].with_delay(
                description=_("Delete a local worklog which has "
                              "been deleted on JIRA")).delete_record(
                                  backend, worklog_id)
        else:
            env['jira.account.analytic.line'].with_delay(
                description=_("Import a worklog from JIRA")).import_record(
                    backend, issue_id, worklog_id)
Exemplo n.º 15
0
    def OAS_json_spec_download(self, namespace_name, **kwargs):
        ensure_db()
        namespace = http.request.env['openapi.namespace'].sudo().search([
            ('name', '=', namespace_name)
        ])
        if not namespace:
            raise werkzeug.exceptions.NotFound()
        if namespace.token != kwargs.get('token'):
            raise werkzeug.exceptions.Forbidden()

        response_params = {'headers': [('Content-Type', 'application/json')]}
        if 'download' in kwargs:
            response_params = {
                'headers': [
                    ('Content-Type',
                     'application/octet-stream; charset=binary'),
                    ('Content-Disposition',
                     http.content_disposition('swagger.json')),
                ],
                'direct_passthrough':
                True
            }

        return werkzeug.wrappers.Response(json.dumps(namespace.get_OAS()),
                                          status=200,
                                          **response_params)
Exemplo n.º 16
0
    def mp_sell(self, redirect=None, **post):
        uid, context, env = request.uid, dict(request.env.context), request.env
        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 = odoo.SUPERUSER_ID

        values = request.params.copy()
        values.update({"hide_top_menu": True, "test": True})
        try:
            values['databases'] = http.db_list()
        except odoo.exceptions.AccessDenied:
            values['databases'] = None

        if request.httprequest.method == 'POST':
            old_uid = request.uid
            uid = request.session.authenticate(request.session.db,
                                               request.params['login'],
                                               request.params['password'])
            if uid is not False:
                request.params['login_success'] = True
                if not redirect:
                    redirect = '/web'
                return http.redirect_with_hash(redirect)
            request.uid = old_uid
            values['error'] = "Wrong login/password"
        return request.render("odoo_marketplace.wk_mp_seller_landing_page",
                              values)
Exemplo n.º 17
0
 def web_dingtalk_mc_auto_login(self, **kw):
     """
     免登入口
     :param kw:
     :return:
     """
     ensure_db()
     logging.info(">>>用户正在使用免登...")
     if request.session.uid:
         request.uid = request.session.uid
         try:
             context = request.env['ir.http'].webclient_rendering_context()
             response = request.render('web.webclient_bootstrap',
                                       qcontext=context)
             response.headers['X-Frame-Options'] = 'DENY'
             return response
         except AccessError as e:
             _logger.info("AccessError: {}".format(str(e)))
     # 获取用于免登的公司corp_id
     config = request.env['dingtalk.mc.config'].sudo().search(
         [('m_login', '=', True)], limit=1)
     data = {'corp_id': config.corp_id}
     if request.session.uid:
         request.session.uid = False
     if request.session.login:
         request.session.login = False
     return request.render('dingtalk_mc.auto_login_signup', data)
Exemplo n.º 18
0
    def cpo_website_quote_login(self, redirect=None, **kw):
        main.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 = odoo.SUPERUSER_ID

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

        try:
            type = None
            if kw.get('src'):
                if kw.get('type'):
                    type = 'type=' + kw.get('type')
                    redirect = kw.get('src') + '?' + type + '&login=true'
                else:
                    redirect = kw.get('src') + '?login=true'
                http.redirect_with_hash(redirect)
        except Exception, e:
            _logger.error(
                "website_sale postprocess: %s value has been dropped (empty or not writable)"
                % e)
Exemplo n.º 19
0
    def get_discover_meeting(self, **post):
        main.ensure_db()

        REGISTER_USER_ID = \
            int(request.env['ir.config_parameter'].sudo(
            ).sudo().get_param('register_user_id'))
        captcha_site_key = request.env['ir.config_parameter'].sudo().get_param(
            'captcha_site_key')
        user = request.env['res.users'].browse(REGISTER_USER_ID)

        # Get event available
        event_obj = request.env['event.event'].sudo(user)
        events = event_obj.search([
            ('is_discovery_meeting', '=', True),
            ('state', '=', 'confirm'),
            ('date_begin', '>=', fields.Datetime.to_string(datetime.now())),
        ])
        available_events = events.filtered(lambda e: not (
            e.seats_availability == 'limited' and e.seats_available < 1))
        datas = self.prepare_data_events(available_events)

        event_config = request.env['res.config.settings'].sudo().search(
            [], limit=1, order="id desc")
        value = {
            'datas': datas,
            'captcha_site_key': captcha_site_key,
            'description': event_config and event_config.description or "",
            'notice': event_config and event_config.notice or ""
        }
        return request.render("coop_membership.register_form", value)
Exemplo n.º 20
0
 def web_client(self, s_action=None, **kw):
     main.ensure_db()
     try:
         self._bind_http_remote_user(http.request.session.db)
     except http.AuthenticationError:
         return werkzeug.exceptions.Unauthorized().get_response()
     return super().web_client(s_action, **kw)
Exemplo n.º 21
0
 def _wxent_do_post_login(self, user_id, redirect):
     """
     所有的验证都结束并正确后,需要界面跳转到主界面
     :param user_id:  user_id
     :param redirect:
     :return:
     """
     ensure_db()
     dbname = request.session.db
     if not http.db_filter([dbname]):
         return BadRequest()
     context = {}
     registry = registry_get(dbname)
     with registry.cursor() as cr:
         try:
             env = api.Environment(cr, SUPERUSER_ID, context)
             credentials = env['res.users'].sudo().auth_oauth_weixin_ent(
                 "weixin_ent", user_id)
             cr.commit()
             url = '/web' if not redirect else redirect
             uid = request.session.authenticate(*credentials)
             if uid:
                 return http.redirect_with_hash(url)
             else:
                 return self._do_err_redirect("Oauth认证失败!请使用账号登录")
         except Exception as e:
             return self._do_err_redirect("登录失败,原因为:{}".format(str(e)))
Exemplo n.º 22
0
 def web_dingtalk_auto_signin_action(self, **kw):
     """
     通过获得的【免登授权码或者临时授权码】获取用户信息
     :param kw:
     :return:
     """
     auth_code = kw.get('authCode')
     logging.info(">>>免登授权码: %s", auth_code)
     config = request.env['dingtalk.mc.config'].sudo().search(
         [('m_login', '=', True)], limit=1)
     client = dt.get_client(
         request, dt.get_dingtalk_config(request, config.company_id))
     result = client.user.getuserinfo(auth_code)
     domain = [('ding_id', '=', result.userid),
               ('company_id', '=', config.company_id.id)]
     employee = request.env['hr.employee'].sudo().search(domain, limit=1)
     if not employee:
         _logger.info(_("系统对应员工不存在!"))
         return self._do_err_redirect(_("系统对应员工不存在!"))
     _logger.info(">>>员工:{}正在尝试登录系统".format(employee.name))
     if not employee.ding_id:
         _logger.info(_("员工不存在钉钉ID,请维护后再试!"))
         return self._do_err_redirect(_("员工不存在钉钉ID,请维护后再试!"))
     if not employee.user_id:
         return self._do_err_redirect(_("你还没有关联系统用户,请联系管理员处理!"))
     ensure_db()
     dbname = request.session.db
     if not http.db_filter([dbname]):
         return BadRequest()
     registry = registry_get(dbname)
     with registry.cursor() as cr:
         try:
             env = api.Environment(cr, SUPERUSER_ID, {})
             credentials = env['res.users'].sudo().auth_oauth(
                 'dingtalk', employee.ding_id)
             cr.commit()
             url = '/web'
             resp = login_and_redirect(*credentials, redirect_url=url)
             if werkzeug.urls.url_parse(
                     resp.location
             ).path == '/web' and not request.env.user.has_group(
                     'base.group_user'):
                 resp.location = '/'
             return resp
         except AttributeError:
             _logger.error(">>>未在数据库'%s'上安装auth_signup:oauth注册已取消。" %
                           (dbname, ))
             url = "/web/login?oauth_error=1"
         except AccessDenied:
             _logger.info(
                 '>>>DingTalk-OAuth2: 访问被拒绝,在存在有效会话的情况下重定向到主页,而未设置Cookie')
             url = "/web/login?oauth_error=3"
             redirect = werkzeug.utils.redirect(url, 303)
             redirect.autocorrect_location_header = False
             return redirect
         except Exception as e:
             _logger.exception("OAuth2: %s" % str(e))
             url = "/web/login?oauth_error=2"
     return http.redirect_with_hash(url)
 def web_login(self, redirect=None, **kw):
     ensure_db()
     param_model = request.env['ir.config_parameter']
     suspended = param_model.sudo().get_param('saas_client.suspended', '0')
     page_for_suspended = param_model.sudo().get_param('saas_client.page_for_suspended', '/')
     if suspended == '1':
         return werkzeug.utils.redirect(page_for_suspended, 303)
     return super(SaaSClientLogin, self).web_login(redirect, **kw)
Exemplo n.º 24
0
 def web_login(self, *args, **kw):
     ensure_db()
     response = super(AuthSignupHome, self).web_login(*args, **kw)
     response.qcontext.update(self.get_auth_signup_config())
     if request.httprequest.method == 'GET' and request.session.uid and request.params.get('redirect'):
         # Redirect if already logged in and redirect param is present
         return http.redirect_with_hash(request.params.get('redirect'))
     return response
Exemplo n.º 25
0
Arquivo: main.py Projeto: Choumy/odoo
 def web_login(self, *args, **kw):
     ensure_db()
     response = super(AuthSignupHome, self).web_login(*args, **kw)
     response.qcontext.update(self.get_auth_signup_config())
     if request.httprequest.method == 'GET' and request.session.uid and request.params.get('redirect'):
         # Redirect if already logged in and redirect param is present
         return http.redirect_with_hash(request.params.get('redirect'))
     return response
Exemplo n.º 26
0
 def web_login(self, *args, **kw):
     ensure_db()
     response = super(SlideAuthHome, self).web_login(*args, **kw)
     if request.params.get('login_success'):
         user = request.env['res.users'].sudo().browse(int(request.env.uid))
         if (user.partner_id.isstudent or user.partner_id.isparent):
             return request.redirect("/grades-subjects")
     return response
Exemplo n.º 27
0
 def translations(self, mods=None, lang=None):
     res = super().translations(mods, lang)
     if 'uid' in request.session:
         ensure_db()
         user = request.env['res.users'].sudo().browse(
             request.session['uid'])
         res['lang_parameters'].update(self.get_user_lang_parameters(user))
     return res
Exemplo n.º 28
0
 def object_in_route(self, in_route, res_id=False, **kw):
     # action_id = request.env.ref('crm.crm_lead_opportunities_tree_view', raise_if_not_found=False)
     ensure_db()
     action_id = request.env['ir.actions.act_window'].sudo().search([
         ('in_route', '=', in_route)], limit=1)
     if action_id:
         return self._redirect_to_view(action_id, res_id)
     else:
         return werkzeug.utils.redirect('/web/login?error=access')
Exemplo n.º 29
0
 def register_affiliate(self, **kw):
     ensure_db()
     aff_request = request.env['affiliate.request'].sudo().search([
         ('name', '=', kw.get('login'))
     ])
     if aff_request and kw.get('confirm_password') == kw.get(
             'password') and aff_request.signup_token == kw.get('token'):
         template_user_id = literal_eval(
             request.env['ir.config_parameter'].sudo().get_param(
                 'base.template_portal_user_id', 'False'))
         template_user = request.env['res.users'].sudo().browse(
             template_user_id)
         auto_approve_request = request.env['res.config.settings'].sudo(
         ).website_constant().get('auto_approve_request')
         if not template_user.exists():
             raise SignupError('Invalid template user.')
         data = kw
         redirect_url = "/"
         values = {key: data.get(key) for key in ('login', 'name')}
         values['email'] = data.get('email') or values.get('login')
         values['lang'] = request.lang.code
         values['active'] = True
         no_invitation_mail = True
         values['password'] = data.get('password', "")
         try:
             with request.env.cr.savepoint():
                 user = template_user.with_context(
                     no_reset_password=no_invitation_mail).copy(values)
                 _logger.info('------user.partner--%r-----',
                              user.partner_id)
                 # update phoen no. and comment in res.partner
                 user.partner_id.comment = kw.get('comment')
                 user.partner_id.phone = kw.get('phone')
                 # update affiliate.request with partner and user id and state
                 aff_request.partner_id = user.partner_id.id
                 aff_request.user_id = user.id
                 aff_request.state = 'register'
             request.env.cr.commit()
             # check the config for auto approve the request
             if auto_approve_request:
                 aff_request.action_aproove()
             db = request.env.cr.dbname
             return login_and_redirect(db,
                                       data['login'],
                                       data['password'],
                                       redirect_url='/affiliate')
         except Exception as e:
             _logger.error("Error123: %r" % e)
         return http.redirect_with_hash('/')
     else:
         if kw.get('password') != kw.get('confirm_password'):
             request.session['error'] = "Passwords Does't match."
             return request.redirect(
                 '/affiliate/signup?token=' + kw.get('token'), 303)
         else:
             request.session['error'] = "something went wrong.."
             return request.redirect('/affiliate/', 303)
Exemplo n.º 30
0
 def web_login(self, *args, **kw):
     ensure_db()
     response = super(AuthSignupHome, self).web_login(*args, **kw)
     response.qcontext.update(self.get_auth_signup_config())
     if request.httprequest.method == 'POST' and request.env.user.sudo(
     ).has_group('odoo_marketplace.marketplace_draft_seller_group'):
         # Redirect to seller dashboard
         return website_marketplace_dashboard().account()
     return response
Exemplo n.º 31
0
 def web_login(self, *args, **kw):
     ensure_db()
     response = super(web_login, self).web_login(*args, **kw)
     if request.session.uid:
         user = request.env['res.users'].browse(request.session.uid)
         pos_config = user.pos_config_id
         if pos_config:
             return http.local_redirect('/pos/web/')
     return response
Exemplo n.º 32
0
    def web_client(self, s_action=None, **kw):
        ensure_db()
        if not request.session.uid:
            return werkzeug.utils.redirect('/web/login', 303)
        if kw.get('redirect'):
            return werkzeug.utils.redirect(kw.get('redirect'), 303)

        request.uid = request.session.uid
        context = request.env['ir.http'].webclient_rendering_context()
        request.env['ir.ui.menu'].clear_caches()
        menu_data = request.env['ir.ui.menu'].load_menus(request.debug)

        return request.render('web.webclient_bootstrap', qcontext=context)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Exemplo n.º 33
0
Arquivo: main.py Projeto: 1806933/odoo
    def web_login(self, *args, **kw):
        ensure_db()
        if request.httprequest.method == 'GET' and request.session.uid and request.params.get('redirect'):
            # Redirect if already logged in and redirect param is present
            return http.redirect_with_hash(request.params.get('redirect'))
        providers = self.list_providers()

        response = super(OAuthLogin, self).web_login(*args, **kw)
        if response.is_qweb:
            error = request.params.get('oauth_error')
            if error == '1':
                error = _("Sign up is not allowed on this database.")
            elif error == '2':
                error = _("Access Denied")
            elif error == '3':
                error = _("You do not have access to this database or your invitation has expired. Please ask for an invitation and be sure to follow the link in your invitation email.")
            else:
                error = None

            response.qcontext['providers'] = providers
            if error:
                response.qcontext['error'] = error

        return response