Exemplo n.º 1
0
    def website_form(self, model_name, **kwargs):
        if model_name == 'hr.applicant':
            job_id = request.params.get('job_id')
            #partner = request.params.get('partner_id')
            survey_id = request.env['hr.job'].sudo().search([
                ('id', '=', int(job_id))
            ]).survey_id
            #partner_id = request.env['res.partner'].search([('id','=',int(partner))])
            # print(partner_id)
            url = "/survey/start/" + str(survey_id.access_token)
            #return http.redirect_with_hash(url)

        # Partial CSRF check, only performed when session is authenticated, as there
        # is no real risk for unauthenticated sessions here. It's a common case for
        # embedded forms now: SameSite policy rejects the cookies, so the session
        # is lost, and the CSRF check fails, breaking the post for no good reason.
        csrf_token = request.params.pop('csrf_token', None)
        if request.session.uid and not request.validate_csrf(csrf_token):
            raise BadRequest('Session expired (invalid CSRF token)')

        try:
            if request.env['ir.http']._verify_request_recaptcha_token(
                    'website_form'):
                return self._handle_website_form(model_name, **kwargs)
            error = _("Suspicious activity detected by Google reCaptcha.")
        except (ValidationError, UserError) as e:
            error = e.args[0]
        return json.dumps({
            'error': error,
        })
Exemplo n.º 2
0
    def website_form(self, model_name, **kwargs):
        # Partial CSRF check, only performed when session is authenticated, as there
        # is no real risk for unauthenticated sessions here. It's a common case for
        # embedded forms now: SameSite policy rejects the cookies, so the session
        # is lost, and the CSRF check fails, breaking the post for no good reason.
        csrf_token = request.params.pop('csrf_token', None)
        if request.session.uid and not request.validate_csrf(csrf_token):
            raise BadRequest('Session expired (invalid CSRF token)')

        model_record = request.env['ir.model'].sudo().search([
            ('model', '=', model_name), ('website_form_access', '=', True)
        ])
        if not model_record:
            return json.dumps(False)

        try:
            data = self.extract_data(model_record, request.params)
        # If we encounter an issue while extracting data
        except ValidationError as e:
            # I couldn't find a cleaner way to pass data to an exception
            return json.dumps({'error_fields': e.args[0]})

        try:
            id_record = self.insert_record(request, model_record,
                                           data['record'], data['custom'],
                                           data.get('meta'))
            if id_record:
                self.insert_attachment(model_record, id_record,
                                       data['attachments'])
                # in case of an email, we want to send it immediately instead of waiting
                # for the email queue to process
                if model_name == 'mail.mail':
                    request.env[model_name].sudo().browse(id_record).send()

        # Some fields have additional SQL constraints that we can't check generically
        # Ex: crm.lead.probability which is a float between 0 and 1
        # TODO: How to get the name of the erroneous field ?
        except IntegrityError:
            return json.dumps(False)

        request.session['form_builder_model_model'] = model_record.model
        request.session['form_builder_model'] = model_record.name
        request.session['form_builder_id'] = id_record

        return json.dumps({'id': id_record})
Exemplo n.º 3
0
    def website_form(self, model_name, **kwargs):
        # Partial CSRF check, only performed when session is authenticated, as there
        # is no real risk for unauthenticated sessions here. It's a common case for
        # embedded forms now: SameSite policy rejects the cookies, so the session
        # is lost, and the CSRF check fails, breaking the post for no good reason.
        csrf_token = request.params.pop('csrf_token', None)
        if request.session.uid and not request.validate_csrf(csrf_token):
            raise BadRequest('Session expired (invalid CSRF token)')

        try:
            if request.env['ir.http']._verify_request_recaptcha_token('website_form'):
                return self._handle_website_form(model_name, **kwargs)
            error = _("Suspicious activity detected by Google reCaptcha.")
        except (ValidationError, UserError) as e:
            error = e.args[0]
        return json.dumps({
            'error': error,
        })
Exemplo n.º 4
0
    def website_form(self, model_name, **kwargs):
        # Partial CSRF check, only performed when session is authenticated, as there
        # is no real risk for unauthenticated sessions here. It's a common case for
        # embedded forms now: SameSite policy rejects the cookies, so the session
        # is lost, and the CSRF check fails, breaking the post for no good reason.
        csrf_token = request.params.pop('csrf_token', None)
        if request.session.uid and not request.validate_csrf(csrf_token):
            raise BadRequest('Session expired (invalid CSRF token)')

        try:
            # The except clause below should not let what has been done inside
            # here be committed. It should not either roll back everything in
            # this controller method. Instead, we use a savepoint to roll back
            # what has been done inside the try clause.
            with request.env.cr.savepoint():
                if request.env['ir.http']._verify_request_recaptcha_token('website_form'):
                    return self._handle_website_form(model_name, **kwargs)
            error = _("Suspicious activity detected by Google reCaptcha.")
        except (ValidationError, UserError) as e:
            error = e.args[0]
        return json.dumps({
            'error': error,
        })
Exemplo n.º 5
0
    def register_products(self, **kwargs):
        # Partial CSRF check, only performed when session is authenticated, as there
        # is no real risk for unauthenticated sessions here. It's a common case for
        # embedded forms now: SameSite policy rejects the cookies, so the session
        # is lost, and the CSRF check fails, breaking the post for no good reason.
        csrf_token = request.params.pop('csrf_token', None)
        if request.session.uid and not request.validate_csrf(csrf_token):
            raise BadRequest('Session expired (invalid CSRF token)')

        try:
            data = self.extract_data(request.params)
        # If we encounter an issue while extracting data, abort registration
        except Exception as e:
            warranty_error = e.args[0]
            return request.render('mc_warranty.warranty_not_activated',
                                  {'error': warranty_error})

        sale_order = request.env['sale.order'].search([
            ('name', '=', data['form_fields']['warranty'])
        ])
        if not sale_order:
            warranty_error = _('This warranty number %s is not correct'
                               ) % data['form_fields']['warranty']
            return request.render('mc_warranty.warranty_not_activated',
                                  {'error': warranty_error})
        elif not any(sale_order.order_line.mapped('sales_lot_id.mc_care')):
            warranty_error = _(
                'This warranty number %s is not related to a Mc Care product'
            ) % data['form_fields']['warranty']
            return request.render('mc_warranty.warranty_not_activated',
                                  {'error': warranty_error})
        elif sale_order.mc_care_warranty:
            warranty_error = _(
                'This warranty number %s has already been activated'
            ) % data['form_fields']['warranty']
            return request.render('mc_warranty.warranty_not_activated',
                                  {'error': warranty_error})

        try:
            country = request.env['res.country'].browse(
                data['form_fields']['country'])
            partner = request.env['res.partner'].search([
                ('email', '=', data['form_fields']['email'])
            ])
            if not partner:
                partner = request.env['res.partner'].create({
                    'name':
                    '{} {}'.format(data['form_fields']['lastname'],
                                   data['form_fields']['firstname']),
                    'street':
                    data['form_fields']['address'],
                    'city':
                    data['form_fields']['city'],
                    'country_id':
                    country.id if country else False,
                    'zip':
                    data['form_fields']['zip'],
                    'email':
                    data['form_fields']['email'],
                    'phone':
                    data['form_fields']['phone'],
                    'lang':
                    data['form_fields']['lang'],
                })
            else:
                # Possible threat: anyone can update those values with a valid sale order name that is not hard to find.
                # update partner
                if country:
                    partner.country_id = country
                partner.write({
                    'name':
                    '{} {}'.format(data['form_fields']['lastname'],
                                   data['form_fields']['firstname']),
                    'street':
                    data['form_fields']['address'],
                    'city':
                    data['form_fields']['city'],
                    'zip':
                    data['form_fields']['zip'],
                    'phone':
                    data['form_fields']['phone'],
                    'lang':
                    data['form_fields']['lang'],
                })
                # post survey on partner record
                if any([
                        key in data['form_fields'] for key in
                    ['mc_known', 'influence', 'find_out', 'household']
                ]):
                    title = _('MC Care Website Survey')
                    q_1 = _(
                        'Did your know Marie\'s Corner before your purchase ?')
                    q_2 = _(
                        'Did the MC Care warranty influence your purchase ?')
                    q_3 = _(
                        'How did you find out about the MC Care Warranty ?')
                    q_4 = _('Household Type')
                    a_1 = data['form_fields']['mc_known'] if 'mc_known' in data[
                        'form_fields'] else _('No Response')
                    a_2 = data['form_fields'][
                        'influence'] if 'influence' in data[
                            'form_fields'] else _('No Response')
                    a_3 = data['form_fields']['find_out'] if 'find_out' in data[
                        'form_fields'] else _('No Response')
                    a_4 = data['form_fields'][
                        'household'] if 'household' in data[
                            'form_fields'] else _('No Response')
                    survey_msg = '<p><strong>{}</strong><br/>{} -> {}<br/>{} -> {}<br/>{} -> {}<br/>{} -> {}</p>'.format(
                        title, q_1, a_1, q_2, a_2, q_3, a_3, q_4, a_4)
                    partner.message_post(body=survey_msg,
                                         subject=title,
                                         message_type='comment',
                                         subtype='mail.mt_note')
            # update sale order
            sale_order.write({
                'mc_care_warranty': True,
                'final_partner_id': partner.id
            })
            # update sales lots
            sale_order.order_line.mapped('sales_lot_id').write({
                'mc_care_warranty':
                True,
                'final_partner_id':
                partner.id
            })
            # send a confirmation email
            mail_template = request.env.ref(
                'mc_warranty.mc_warranty_confirmation_mail',
                raise_if_not_found=False)
            if not mail_template:
                _logger.warning(
                    'the mail template with xmlid mc_warranty.mc_warranty_confirmation_mail has been deleted.'
                )
            else:
                mail_template.with_context(
                    **{
                        'email_to': partner.email,
                        'lang': partner.lang,
                        'company': request.env.company,
                        'partner': partner,
                    }).send_mail(sale_order.id, force_send=True)
        # If we encounter an issue while extracting data, abort registration
        except Exception as e:
            warranty_error = e.args[0]
            return request.render('mc_warranty.warranty_not_activated',
                                  {'error': warranty_error})
        return request.render('mc_warranty.warranty_activated')