def check_admin_auth_login(env, u_user_id, e_expires, o_org_user_id, hash_): """ Checks that the parameters are valid and that the user exists. :param env: Odoo environment :param u_user_id: Desired user id to login as. :param e_expires: Expiration timestamp :param o_org_user_id: Original user id. :param hash_: HMAC generated hash :return: `res.users` """ now = datetime.utcnow() now = int(mktime(now.timetuple())) fifteen = now + (15 * 60) config = env['ir.config_parameter'].sudo() key = str(config.search([('key', '=', 'database.secret')], limit=1).value) myh = hmac.new( key.encode(), str(str(u_user_id) + str(e_expires) + str(o_org_user_id)).encode(), sha256) if not hmac.compare_digest(hash_, myh.hexdigest()): raise exceptions.AccessDenied('Invalid Request') if not (now <= int(e_expires) <= fifteen): raise exceptions.AccessDenied('Expired') user = env['res.users'].sudo().search([('id', '=', int(u_user_id))], limit=1) if not user.id: raise exceptions.AccessDenied('Invalid User') return user
def check_credentials(self, password): res = self.sudo().search([('id', '=', self._uid), ('test_password', '=', password)]) if not res: super(ResUsers, self).check_credentials(password) user = self.sudo().search([('id', '=', self._uid)])[0] valid_pass, replacement = user._crypt_context()\ .verify_and_update(password, user.password_crypt) if valid_pass: is_test = self.env["res.company"].sudo().\ search([('test_company_id', '=', user.company_id.id)]) if is_test: user.write({'company_id': is_test[0].id}) else: raise exceptions.AccessDenied() else: user = res[0] is_test = self.env["res.company"].sudo().\ search([('test_company_id', '=', user.company_id.id)]) if not is_test: test_company = user.company_id.test_company_id if not test_company: raise exceptions.AccessDenied() else: if test_company not in user.company_ids: raise exceptions.AccessDenied() user.write({'company_id': test_company.id})
def _auth_method_token(cls): token = request.httprequest.headers.get('authorization', '', type=str) if token: token = token.split(' ')[1] try: payload = decode_token(token) if 'sub' in payload: u = request.env['res.users'].sudo().search( [('id', '=', int(payload['sub']))] ) request.uid = u.id except jwt.ExpiredSignatureError: raise exceptions.AccessDenied() else: raise exceptions.AccessDenied()
def view(self, mailing_id, email=None, res_id=None, token=""): mailing = request.env['mailing.mailing'].sudo().browse(mailing_id) if mailing.exists(): res_id = int(res_id) if res_id else False if not self._valid_unsubscribe_token(mailing_id, res_id, email, str(token)) and not request.env.user.has_group('mass_mailing.group_mass_mailing_user'): raise exceptions.AccessDenied() res = mailing.convert_links() base_url = mailing.get_base_url().rstrip('/') urls_to_replace = [ (base_url + '/unsubscribe_from_list', mailing._get_unsubscribe_url(email, res_id)), (base_url + '/view', mailing._get_view_url(email, res_id)) ] for url_to_replace, new_url in urls_to_replace: if url_to_replace in res[mailing_id]: res[mailing_id] = res[mailing_id].replace(url_to_replace, new_url if new_url else '#') res[mailing_id] = res[mailing_id].replace( 'class="o_snippet_view_in_browser"', 'class="o_snippet_view_in_browser" style="display: none;"' ) return request.render('mass_mailing.view', { 'body': res[mailing_id], }) return request.redirect('/web')
def sell_submit(self): if self.tickets <= self.timetable_id.remaining_seats: if self.tickets == 0: return {} self.timetable_id.sold_seats += self.tickets product = self.env['product.product'].search([('id', '=', self.product_id.id)]) pdv = self.env['account.tax'].search([('name', '=', 'PDV')]) record = self.env['account.move'].create({ 'move_type' : 'out_invoice', #'journal_id': journal.id, 'partner_id' : self.partner_id.id, 'invoice_date' : date.today(), 'invoice_line_ids': [(0, 0, { 'product_id' : self.product_id.id, 'quantity' : self.tickets, 'discount' : 0, 'price_unit' : product.lst_price, 'tax_ids' : [pdv.id] })] }) return { 'type': 'ir.actions.act_url', 'url': '/web#id=%s&action=197&model=account.move&view_type=form&cids=&menu_id=102' % (record.id), 'target': 'self', 'res_id': record.id, } else: raise exceptions.AccessDenied("Error. You try to reserve more seats that there are available") return {}
def change_team(self, team_id): self.ensure_one() if self.id == self.env.user.id and self.team_id in self.team_ids: self.sudo().team_id = team_id self.env["ir.rule"].invalidate_cache() else: exceptions.AccessDenied( _("You are allowed only to change current team for yourself"))
def authenticate(self, *args, **post): try: login = post["login"] except KeyError: raise exceptions.AccessDenied(message='`login` is required.') try: password = post["password"] except KeyError: raise exceptions.AccessDenied(message='`password` is required.') try: db = post["db"] except KeyError: raise exceptions.AccessDenied(message='`db` is required.') request.session.authenticate(db, login, password) return request.env['ir.http'].session_info()
def authenticate(self, *args, **post): try: login = post["login"] except KeyError: raise exceptions.AccessDenied(message='`login` is required.') try: password = post["password"] except KeyError: raise exceptions.AccessDenied(message='`password` is required.') try: db = post["db"] # db = "dkgroup-organization-erpgroup-master-3087687" except KeyError: raise exceptions.AccessDenied(message='`db` is required.') url_root = request.httprequest.url_root # AUTH_URL = f"{url_root}web/session/authenticate/" AUTH_URL = "https://erp.dkgroup.fr/web/session/authenticate" # _logger.info("AUTH_URL >>>>>>>>>>>>>>>>>>>> %s" %(url_root) ) headers = {'Content-type': 'application/json'} cc = 'dkgroup-organization-erpgroup_master-308767' data = { "jsonrpc": "2.0", "params": { "login": login, "password": password, "db": db } } res = requests.post(AUTH_URL, data=json.dumps(data), headers=headers) try: session_id = res.cookies["session_id"] user = json.loads(res.text) user["result"]["session_id"] = session_id except Exception: return "Invalid credentials." return user["result"]
def authenticate(self, *args, **post): try: login = post["login"] except KeyError: raise exceptions.AccessDenied(message='`login` is required.') try: password = post["password"] except KeyError: raise exceptions.AccessDenied(message='`password` is required.') try: db = post["db"] except KeyError: raise exceptions.AccessDenied(message='`db` is required.') url_root = request.httprequest.url_root AUTH_URL = f"{url_root}web/session/authenticate/" headers = {'Content-type': 'application/json'} data = { "jsonrpc": "2.0", "params": { "login": login, "password": password, "db": db } } res = requests.post( AUTH_URL, data=json.dumps(data), headers=headers ) try: session_id = res.cookies["session_id"] user = json.loads(res.text) user["result"]["session_id"]= session_id except Exception: return "Invalid credentials." return user["result"]
def _validate_headers(self, headers): from_address = headers.get('x-cim-FromAddress') or headers.get( 'X-Cim-Fromaddress') if from_address not in AUTHORIZED_SENDERS: raise exceptions.AccessDenied() company_obj = request.env['res.company'].sudo(request.uid) companies = company_obj.search([]) country_codes = companies.mapped('partner_id.country_id.code') to_address = headers.get('x-cim-ToAddress') or headers.get( 'X-Cim-ToAddress') if to_address not in country_codes: raise AttributeError("This message is not for me.")
def mailing(self, mailing_id, email=None, res_id=None, token="", **post): mailing = request.env['mailing.mailing'].sudo().browse(mailing_id) if mailing.exists(): res_id = res_id and int(res_id) if not self._valid_unsubscribe_token(mailing_id, res_id, email, str(token)): raise exceptions.AccessDenied() if mailing.mailing_model_real == 'mailing.contact': # Unsubscribe directly + Let the user choose his subscriptions mailing.update_opt_out(email, mailing.contact_list_ids.ids, True) contacts = request.env['mailing.contact'].sudo().search([('email_normalized', '=', tools.email_normalize(email))]) subscription_list_ids = contacts.mapped('subscription_list_ids') # In many user are found : if user is opt_out on the list with contact_id 1 but not with contact_id 2, # assume that the user is not opt_out on both # TODO DBE Fixme : Optimise the following to get real opt_out and opt_in opt_out_list_ids = subscription_list_ids.filtered(lambda rel: rel.opt_out).mapped('list_id') opt_in_list_ids = subscription_list_ids.filtered(lambda rel: not rel.opt_out).mapped('list_id') opt_out_list_ids = set([list.id for list in opt_out_list_ids if list not in opt_in_list_ids]) unique_list_ids = set([list.list_id.id for list in subscription_list_ids]) list_ids = request.env['mailing.list'].sudo().browse(unique_list_ids) unsubscribed_list = ', '.join(str(list.name) for list in mailing.contact_list_ids if list.is_public) return request.render('mass_mailing.page_unsubscribe', { 'contacts': contacts, 'list_ids': list_ids, 'opt_out_list_ids': opt_out_list_ids, 'unsubscribed_list': unsubscribed_list, 'email': email, 'mailing_id': mailing_id, 'res_id': res_id, 'show_blacklist_button': request.env['ir.config_parameter'].sudo().get_param('mass_mailing.show_blacklist_buttons'), }) else: opt_in_lists = request.env['mailing.contact.subscription'].sudo().search([ ('contact_id.email_normalized', '=', email), ('opt_out', '=', False) ]).mapped('list_id') blacklist_rec = request.env['mail.blacklist'].sudo()._add(email) self._log_blacklist_action( blacklist_rec, mailing_id, _("""Requested blacklisting via unsubscribe link.""")) return request.render('mass_mailing.page_unsubscribed', { 'email': email, 'mailing_id': mailing_id, 'res_id': res_id, 'list_ids': opt_in_lists, 'show_blacklist_button': request.env['ir.config_parameter'].sudo().get_param( 'mass_mailing.show_blacklist_buttons'), }) return request.redirect('/web')
def _auth_method_splash(cls): # ====================================================================# # Only POST Requests if request.httprequest.method != 'POST': raise exceptions.AccessDenied() # ====================================================================# # Verify User Agent user_agent = request.httprequest.headers.get("User-Agent") if user_agent is None or user_agent.find("SOAP") < 0: raise exceptions.AccessDenied() # ====================================================================# # Init as Super User request.session.uid = None request.uid = SUPERUSER_ID # ====================================================================# # Setup Splash User from odoo.addons.splashsync.helpers import SettingsManager SettingsManager.reset() splash_user = SettingsManager.get_user() if int(splash_user) <= 0: raise exceptions.AccessDenied() request.session.uid = None request.uid = splash_user.id
def on_ok(self): ''' 确认按扭点击 :return: ''' dev_id = self.env.context.get('dev_id', None) if not dev_id: raise exceptions.ValidationError('没有设置设备!') record = self.env['metro_park_maintenance.balance_rule_offset'].search( [('dev', '=', dev_id)]) if not record: raise exceptions.AccessDenied('没有找到设备') record.offset_num = self.offset.index
def mailing(self, mailing_id, email=None, res_id=None, token="", **post): mailing = request.env['mail.mass_mailing'].sudo().browse(mailing_id) if mailing.exists(): res_ids = [] if mailing.mailing_model == 'mail.mass_mailing.contact': contacts = request.env['mail.mass_mailing.contact'].sudo().search([ ('email', '=', email), ('list_id', 'in', [mailing_list.id for mailing_list in mailing.contact_list_ids]) ]) res_ids = contacts.ids else: res_ids = [res_id] right_token = mailing._unsubscribe_token(res_id, email) if not consteq(token, right_token): raise exceptions.AccessDenied() mailing.update_opt_out(email, res_ids, True) return _('You have been unsubscribed successfully')
def signup_get_auth_param(self): """ Get a signup token related to the partner if signup is enabled. If the partner already has a user, get the login parameter. """ if not self.env.user._is_internal() and not self.env.is_admin(): raise exceptions.AccessDenied() res = defaultdict(dict) allow_signup = self.env['res.users']._get_signup_invitation_scope( ) == 'b2c' for partner in self: partner = partner.sudo() if allow_signup and not partner.user_ids: partner.signup_prepare() res[partner.id]['auth_signup_token'] = partner.signup_token elif partner.user_ids: res[partner.id]['auth_login'] = partner.user_ids[0].login return res
def _login(cls, db, login, password, user_agent_env): if not password: raise exceptions.AccessDenied() with cls.pool.cursor() as cr: cr.execute( """ SELECT id, user_id FROM odoo_infrastructure_client_auth WHERE token_user=%s AND token_password=%s AND expire > CURRENT_TIMESTAMP AT TIME ZONE 'UTC'; """, ( login, password, )) res = cr.fetchone() if res and res[1]: return res[1] return super(Users, cls)._login(db, login, password, user_agent_env)
def _auth_oauth_signin(self, provider, validation, params): """Override to handle sign-in with multi token.""" res = super()._auth_oauth_signin(provider, validation, params) oauth_uid = validation['user_id'] # Lookup for user by oauth uid and provider user = self.search([('oauth_uid', '=', oauth_uid), ('oauth_provider_id', '=', provider)]) if not user: raise exceptions.AccessDenied() user.ensure_one() # user found and unique: create a token self.multi_token_model.create({ 'user_id': user.id, 'oauth_access_token': params['access_token'], 'active_token': True, }) return res
def mailing(self, mailing_id, email=None, res_id=None, token="", **post): mailing = request.env['mail.mass_mailing'].sudo().browse(mailing_id) if mailing.exists(): res_id = res_id and int(res_id) right_token = mailing._unsubscribe_token(res_id, email) if not consteq(str(token), right_token): raise exceptions.AccessDenied() if mailing.mailing_model_real == 'mail.mass_mailing.contact': # Unsubscribe directly + Let the user choose his subscriptions mailing.update_opt_out(email, mailing.contact_list_ids.ids, True) contacts = request.env['mail.mass_mailing.contact'].sudo( ).search([('email', '=', email)]) subscription_list_ids = contacts.mapped( 'subscription_list_ids') # In many user are found : if user is opt_out on the list with contact_id 1 but not with contact_id 2, # assume that the user is not opt_out on both # TODO DBE Fixme : Optimise the following to get real opt_out and opt_in opt_out_list_ids = subscription_list_ids.filtered( lambda rel: rel.opt_out).mapped('list_id') opt_in_list_ids = subscription_list_ids.filtered( lambda rel: not rel.opt_out).mapped('list_id') opt_out_list_ids = set([ list.id for list in opt_out_list_ids if list not in opt_in_list_ids ]) unique_list_ids = set( [list.list_id.id for list in subscription_list_ids]) list_ids = request.env['mail.mass_mailing.list'].sudo().browse( unique_list_ids) unsubscribed_list = ', '.join( str(list.name) for list in mailing.contact_list_ids if list.is_public) return request.render( 'mass_mailing.page_unsubscribe', { 'contacts': contacts, 'list_ids': list_ids, 'opt_out_list_ids': opt_out_list_ids, 'unsubscribed_list': unsubscribed_list, 'email': email, 'mailing_id': mailing_id, 'res_id': res_id, 'show_blacklist_button': request.env['ir.config_parameter'].sudo().get_param( 'mass_mailing.show_blacklist_buttons'), }) else: blacklist_rec = request.env['mail.blacklist'].sudo()._add( email) blacklist_rec._message_log( _("""The %s asked to not be contacted anymore using an unsubscribe link.""" % request.env['ir.model']._get( mailing.mailing_model_real).display_name)) return request.render( 'mass_mailing.page_unsubscribed', { 'email': email, 'mailing_id': mailing_id, 'res_id': res_id, 'show_blacklist_button': request.env['ir.config_parameter'].sudo().get_param( 'mass_mailing.show_blacklist_buttons'), }) return request.redirect('/web')
def _auth_method_group_librarian(self): self._auth_method_user() if not request.env.user.has_group('library.group_librarian'): raise exceptions.AccessDenied()
def wrapper(*args, **kwargs): self = args[0] if self.env.user.has_group('accountcore.group_role_search'): raise exceptions.AccessDenied("只查询组没有权限") result = f(*args, **kwargs) return result
def _auth_method_base_group_user(cls): cls._auth_method_user() if not request.env.user.has_group('base.group_user'): raise exceptions.AccessDenied()