Esempio n. 1
0
    def post(self, path, vals):
        config = self.instance()

        payload = simplejson.dumps(vals)
        url = config.get('cenit_url') + API_PATH + path
        headers = self.headers(config)

        try:
            _logger.info("[POST] %s ? %s {%s}", url, payload, headers)
            r = requests.post(url, data=payload, headers=headers)
        except Exception as e:
            _logger.error(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        if 200 <= r.status_code < 300:
            return r.json()

        try:
            error = r.json()
            _logger.error(error)
        except Exception as e:
            _logger.error(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        if 400 <= error.get('code', 400) < 500:
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        raise exceptions.ValidationError("Cenit returned with errors")
Esempio n. 2
0
    def delete(self, path):
        config = self.instance()

        url = config.get('cenit_url') + API_PATH + path
        headers = self.headers(config)

        try:
            _logger.info("[DEL] %s ? {%s}", url, headers)
            r = requests.delete(url, headers=headers)
        except Exception as e:
            _logger.error(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        if 200 <= r.status_code < 300:
            return True

        try:
            error = r.json()
            _logger.error(error)
        except Exception as e:
            _logger.error(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        if 400 <= error.get('code', 400) < 500:
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        raise exceptions.ValidationError("Cenit returned with errors")
Esempio n. 3
0
    def get(self, path, params=None):
        config = self.instance()

        url = config.get('cenit_url') + API_PATH + path
        headers = self.headers(config)
        try:
            _logger.info("[GET] %s ? %s {%s}", url, params, headers)
            r = requests.get(url, params=params, headers=self.headers(config))
        except Exception as e:
            _logger.error(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        if 200 <= r.status_code < 300:
            return r.json()

        try:
            error = r.json()
            _logger.error(error)
        except Exception as e:
            _logger.error(e)
            _logger.info("\n\n%s\n", r.content)
            raise exceptions.ValidationError("Cenit returned with errors")

        if 400 <= error.get('code', 400) < 500:
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        raise exceptions.ValidationError("Cenit returned with errors")
Esempio n. 4
0
 def create(self, vals):
     res = super(OpFeesTerms, self).create(vals)
     if not res.line_ids:
         raise exceptions.AccessError(_("Fees Terms must be Required!"))
     total = 0.0
     for line in res.line_ids:
         if line.value:
             total += line.value
     if total != 100.0:
         raise exceptions.AccessError(
             _("Fees terms must be divided \
         as such sum up in 100%"))
     return res
Esempio n. 5
0
def jsonrpc(url, method='call', params=None):
    """
    Calls the provided JSON-RPC endpoint, unwraps the result and
    returns JSON-RPC errors as exceptions.
    """
    payload = {
        'jsonrpc': '2.0',
        'method': method,
        'params': params,
        'id': uuid.uuid4().hex,
    }

    _logger.info('iap jsonrpc %s', url)
    try:
        req = requests.post(url, json=payload)
        response = req.json()
        if 'error' in response:
            name = response['error']['data'].get('name').rpartition('.')[-1]
            message = response['error']['data'].get('message')
            if name == 'InsufficientCreditError':
                e_class = InsufficientCreditError
            elif name == 'AccessError':
                e_class = exceptions.AccessError
            else:
                e_class = exceptions.UserError
            e = e_class(message)
            e.data = response['error']['data']
            raise e
        return response.get('result')
    except (ValueError, requests.exceptions.ConnectionError,
            requests.exceptions.MissingSchema,
            urllib3.exceptions.MaxRetryError) as e:
        raise exceptions.AccessError(
            'The url that this service requested returned an error. Please contact the author the app. The url it tried to contact was '
            + url)
Esempio n. 6
0
    def _check_access(self, operation):
        """ Rule to access activities

         * create: check write rights on related document;
         * write: rule OR write rights on document;
         * unlink: rule OR write rights on document;
        """
        self.check_access_rights(
            operation, raise_exception=True)  # will raise an AccessError

        if operation in ('write', 'unlink'):
            try:
                self.check_access_rule(operation)
            except exceptions.AccessError:
                pass
            else:
                return

        doc_operation = 'read' if operation == 'read' else 'write'
        activity_to_documents = dict()
        for activity in self.sudo():
            activity_to_documents.setdefault(activity.res_model,
                                             list()).append(activity.res_id)
        for model, res_ids in activity_to_documents.items():
            self.env[model].check_access_rights(doc_operation,
                                                raise_exception=True)
            try:
                self.env[model].browse(res_ids).check_access_rule(
                    doc_operation)
            except exceptions.AccessError:
                raise exceptions.AccessError(
                    _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)'
                      ) % (self._description, operation) +
                    ' - ({} {}, {} {})'.format(_('Records:'), res_ids[:6],
                                               _('User:'), self._uid))
Esempio n. 7
0
 def _employee_crash(*args, **kwargs):
     """ If employee is test employee, consider he has no access on document """
     recordset = args[0]
     if recordset.env.uid == self.user_employee.id:
         raise exceptions.AccessError(
             'Hop hop hop Ernest, please step back.')
     return DEFAULT
Esempio n. 8
0
 def _contact_iap(local_endpoint, params):
     sim_result = {
         'name': 'Simulator INC',
         'location': 'Simulator Street',
         'city': 'SimCity',
         'postal_code': '9876',
         'country_code': 'BE',
         'clearbit_id': 'idontknow',
         'phone_numbers': ['+3269001122', '+32456001122'],
         'twitter': 'testtwitter',
         'facebook': 'testfacebook',
     }
     if default_data:
         sim_result.update(default_data)
     # mock single sms sending
     if local_endpoint == '/iap/clearbit/1/lead_enrichment_email':
         result = {}
         for lead_id, email in params['domains'].items():
             if sim_error and sim_error == 'credit':
                 raise iap_tools.InsufficientCreditError(
                     'InsufficientCreditError')
             elif sim_error and sim_error == 'jsonrpc_exception':
                 raise exceptions.AccessError(
                     'The url that this service requested returned an error. Please contact the author of the app. The url it tried to contact was '
                     + local_endpoint)
             result[str(lead_id)] = dict(sim_result)
             if email_data and email_data.get(email):
                 result[str(lead_id)].update(email_data[email])
         return result
 def schedule_exam(self):
     for exam in self:
         if exam.total_student > exam.room_capacity:
             raise exceptions.AccessError(
                 _("Room capacity must be greater than total number \
                   of student"))
         student_ids = []
         for student in exam.student_ids:
             student_ids.append(student.id)
         for room in exam.room_ids:
             for i in range(room.capacity):
                 if not student_ids:
                     continue
                 self.env['op.exam.attendees'].create({
                     'exam_id':
                     exam.exam_id.id,
                     'student_id':
                     student_ids[0],
                     'status':
                     'present',
                     'course_id':
                     exam.course_id.id,
                     'batch_id':
                     exam.batch_id.id,
                     'room_id':
                     room.id
                 })
                 student_ids.remove(student_ids[0])
         exam.exam_id.state = 'schedule'
         return True
Esempio n. 10
0
 def _contact_iap(local_endpoint, params):
     # mock single sms sending
     if local_endpoint == '/iap/message_send':
         self._sms += [{
             'number': number,
             'body': params['message'],
         } for number in params['numbers']]
         return True  # send_message v0 API returns always True
     # mock batch sending
     if local_endpoint == '/iap/sms/2/send':
         result = []
         for to_send in params['messages']:
             res = {'res_id': to_send['res_id'], 'state': 'success', 'credit': 1}
             error = sim_error or (nbr_t_error and nbr_t_error.get(to_send['number']))
             if error and error == 'credit':
                 res.update(credit=0, state='insufficient_credit')
             elif error and error == 'wrong_number_format':
                 res.update(state='wrong_number_format')
             elif error and error == 'unregistered':
                 res.update(state='unregistered')
             elif error and error == 'jsonrpc_exception':
                 raise exceptions.AccessError(
                     'The url that this service requested returned an error. Please contact the author of the app. The url it tried to contact was ' + local_endpoint
                 )
             result.append(res)
             if res['state'] == 'success':
                 self._sms.append({
                     'number': to_send['number'],
                     'body': to_send['content'],
                 })
         return result
Esempio n. 11
0
    def unlink(self, **kwargs):
        rc = True
        try:
            rc = self.drop_from_cenit()
        except requests.ConnectionError as e:
            _logger.exception(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except exceptions.AccessError:
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except Exception as e:
            _logger.exception(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        if not rc:
            raise exceptions.ValidationError("Cenit returned with errors")

        rc = super(CenitApi, self).unlink(**kwargs)
        return rc
Esempio n. 12
0
 def write(self, values):
     if values.get('publisher_comment'):
         if not self.env.user.has_group("website.group_website_publisher"):
             raise exceptions.AccessError(_("Only the publisher of the website can change the rating comment"))
         if not values.get('publisher_datetime'):
             values['publisher_datetime'] = fields.Datetime.now()
         if not values.get('publisher_id'):
             values['publisher_id'] = self.env.user.partner_id.id
     return super(Rating, self).write(values)
Esempio n. 13
0
    def create(self, vals):
        obj = super(CenitApi, self).create(vals)

        local = self.env.context.get('local', False)
        if local:
            return obj

        rc = False
        try:
            rc = obj.push_to_cenit()
        except requests.ConnectionError as e:
            _logger.exception(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except exceptions.AccessError:
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except Exception as e:
            _logger.exception(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        if not rc:
            raise exceptions.ValidationError("Cenit returned with errors")

        return obj
Esempio n. 14
0
    def write(self, vals):
        res = super(CenitApi, self).write(vals)

        local = self.env.context.get('local', False)
        if local:
            return res

        cp = vals.copy()
        if cp.pop('cenitID', False):
            if len(cp.keys()) == 0:
                return res

        try:
            self.push_to_cenit()
        except requests.ConnectionError as e:
            _logger.exception(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except exceptions.AccessError:
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except Exception as e:
            _logger.exception(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        return res
Esempio n. 15
0
    def fields_view_get(self,
                        view_id=None,
                        view_type='tree',
                        context=None,
                        toolbar=False):

        rc = super(CenitAccountSettings,
                   self).fields_view_get(view_id=view_id,
                                         view_type=view_type,
                                         toolbar=toolbar)

        if self.env.context.get('next_view'):
            arch = rc['arch']

            email = self.env.context.get('email')
            passwd = self.env.context.get('passwd')
            confirmation = self.env.context.get('confirmation')

            icp = self.env["ir.config_parameter"]
            hub_host = icp.get_param("flectra_cenit.cenit_url",
                                     default='https://cenit.io')
            if hub_host.endswith("/"):
                hub_host = hub_host[:-1]
            path = "/setup/user"
            vals = {
                "email": email,
                "password": passwd,
                "password_confirmation": confirmation
            }

            payload = simplejson.dumps(vals)
            url = hub_host + "/api/v2" + path

            try:
                _logger.info("[POST] %s", url)
                r = requests.post(url, data=payload)
            except Exception as e:
                _logger.error(e)
                raise exceptions.AccessError(
                    "Error trying to connect to Cenit.")

            if 200 <= r.status_code < 300:
                response = r.json()
            else:
                try:
                    error = r.json()
                    _logger.error(error)
                except Exception as e:
                    _logger.error(e)
                    raise exceptions.ValidationError(
                        "Cenit returned with errors")

                if r.status_code == 406:
                    key = str(error.keys()[0])
                    raise exceptions.ValidationError(key.capitalize() + " " +
                                                     str(error[key][0]))
                else:
                    raise exceptions.AccessError(
                        "Error trying to connect to Cenit.")

            token = response.get('token', False)

            icp = self.env['ir.config_parameter']

            hub_hook = "captcha"
            hub_url = "{}/{}/{}".format(hub_host, hub_hook, token)

            try:
                r = requests.get(hub_url)
            except Exception as e:
                _logger.error("\n\Error: %s\n", e)
                raise exceptions.AccessError(
                    "Error trying to connect to Cenit.")

            icp.set_param('cenit.captcha.token', token)

            arch = arch.replace('img_data_here', '{}'.format(hub_url))

            rc['arch'] = arch
        return rc
Esempio n. 16
0
def iap_jsonrpc_mocked(*args, **kwargs):
    raise exceptions.AccessError("Unavailable during tests.")