multiple refactoring with authentication

bzr revid: nicolas.vanhoren@openerp.com-20130621121510-gx22b6j9pwsfe352
This commit is contained in:
niv-openerp 2013-06-21 14:15:10 +02:00
parent c90e8119bb
commit 2fd53a468c
4 changed files with 88 additions and 88 deletions

View File

@ -572,7 +572,7 @@ html_template = """<!DOCTYPE html>
class Home(http.Controller): class Home(http.Controller):
@http.route('/', type='http', authentication="nodb") @http.route('/', type='http', auth="none")
def index(self, s_action=None, db=None, **kw): def index(self, s_action=None, db=None, **kw):
db, redir = db_monodb_redirect() db, redir = db_monodb_redirect()
if redir: if redir:
@ -589,30 +589,30 @@ class Home(http.Controller):
} }
return r return r
@http.route('/login', type='http', authentication="auth") @http.route('/login', type='http', auth="user")
def login(self, db, login, key): def login(self, db, login, key):
return login_and_redirect(db, login, key) return login_and_redirect(db, login, key)
@http.route('/jsonrpc', type='json', authentication="nodb") @http.route('/jsonrpc', type='json', auth="none")
def jsonrpc(self, service, method, args): def jsonrpc(self, service, method, args):
""" Method used by client APIs to contact OpenERP. """ """ Method used by client APIs to contact OpenERP. """
return openerp.netsvc.dispatch_rpc(service, method, args) return openerp.netsvc.dispatch_rpc(service, method, args)
class WebClient(http.Controller): class WebClient(http.Controller):
@http.route('/web/webclient/csslist', type='json', authentication="nodb") @http.route('/web/webclient/csslist', type='json', auth="none")
def csslist(self, mods=None): def csslist(self, mods=None):
return manifest_list('css', mods=mods) return manifest_list('css', mods=mods)
@http.route('/web/webclient/jslist', type='json', authentication="nodb") @http.route('/web/webclient/jslist', type='json', auth="none")
def jslist(self, mods=None): def jslist(self, mods=None):
return manifest_list('js', mods=mods) return manifest_list('js', mods=mods)
@http.route('/web/webclient/qweblist', type='json', authentication="nodb") @http.route('/web/webclient/qweblist', type='json', auth="none")
def qweblist(self, mods=None): def qweblist(self, mods=None):
return manifest_list('qweb', mods=mods) return manifest_list('qweb', mods=mods)
@http.route('/web/webclient/css', type='http', authentication="nodb") @http.route('/web/webclient/css', type='http', auth="none")
def css(self, mods=None, db=None): def css(self, mods=None, db=None):
files = list(manifest_glob('css', addons=mods, db=db)) files = list(manifest_glob('css', addons=mods, db=db))
last_modified = get_last_modified(f[0] for f in files) last_modified = get_last_modified(f[0] for f in files)
@ -663,7 +663,7 @@ class WebClient(http.Controller):
request.make_response(content, [('Content-Type', 'text/css')]), request.make_response(content, [('Content-Type', 'text/css')]),
last_modified, checksum) last_modified, checksum)
@http.route('/web/webclient/js', type='http', authentication="nodb") @http.route('/web/webclient/js', type='http', auth="none")
def js(self, mods=None, db=None): def js(self, mods=None, db=None):
files = [f[0] for f in manifest_glob('js', addons=mods, db=db)] files = [f[0] for f in manifest_glob('js', addons=mods, db=db)]
last_modified = get_last_modified(files) last_modified = get_last_modified(files)
@ -676,7 +676,7 @@ class WebClient(http.Controller):
request.make_response(content, [('Content-Type', 'application/javascript')]), request.make_response(content, [('Content-Type', 'application/javascript')]),
last_modified, checksum) last_modified, checksum)
@http.route('/web/webclient/qweb', type='http', authentication="nodb") @http.route('/web/webclient/qweb', type='http', auth="none")
def qweb(self, mods=None, db=None): def qweb(self, mods=None, db=None):
files = [f[0] for f in manifest_glob('qweb', addons=mods, db=db)] files = [f[0] for f in manifest_glob('qweb', addons=mods, db=db)]
last_modified = get_last_modified(files) last_modified = get_last_modified(files)
@ -689,7 +689,7 @@ class WebClient(http.Controller):
request.make_response(content, [('Content-Type', 'text/xml')]), request.make_response(content, [('Content-Type', 'text/xml')]),
last_modified, checksum) last_modified, checksum)
@http.route('/web/webclient/bootstrap_translations', type='json', authentication="nodb") @http.route('/web/webclient/bootstrap_translations', type='json', auth="none")
def bootstrap_translations(self, mods): def bootstrap_translations(self, mods):
""" Load local translations from *.po files, as a temporary solution """ Load local translations from *.po files, as a temporary solution
until we have established a valid session. This is meant only until we have established a valid session. This is meant only
@ -712,7 +712,7 @@ class WebClient(http.Controller):
return {"modules": translations_per_module, return {"modules": translations_per_module,
"lang_parameters": None} "lang_parameters": None}
@http.route('/web/webclient/translations', type='json', authentication="auth") @http.route('/web/webclient/translations', type='json', auth="user")
def translations(self, mods, lang): def translations(self, mods, lang):
res_lang = request.session.model('res.lang') res_lang = request.session.model('res.lang')
ids = res_lang.search([("code", "=", lang)]) ids = res_lang.search([("code", "=", lang)])
@ -737,13 +737,13 @@ class WebClient(http.Controller):
return {"modules": translations_per_module, return {"modules": translations_per_module,
"lang_parameters": lang_params} "lang_parameters": lang_params}
@http.route('/web/webclient/version_info', type='json', authentication="nodb") @http.route('/web/webclient/version_info', type='json', auth="none")
def version_info(self): def version_info(self):
return openerp.service.common.exp_version() return openerp.service.common.exp_version()
class Proxy(http.Controller): class Proxy(http.Controller):
@http.route('/web/proxy/load', type='json', authentication="nodb") @http.route('/web/proxy/load', type='json', auth="none")
def load(self, path): def load(self, path):
""" Proxies an HTTP request through a JSON request. """ Proxies an HTTP request through a JSON request.
@ -760,11 +760,11 @@ class Proxy(http.Controller):
class Database(http.Controller): class Database(http.Controller):
@http.route('/web/database/get_list', type='json', authentication="nodb") @http.route('/web/database/get_list', type='json', auth="none")
def get_list(self): def get_list(self):
return db_list() return db_list()
@http.route('/web/database/create', type='json', authentication="nodb") @http.route('/web/database/create', type='json', auth="none")
def create(self, fields): def create(self, fields):
params = dict(map(operator.itemgetter('name', 'value'), fields)) params = dict(map(operator.itemgetter('name', 'value'), fields))
return request.session.proxy("db").create_database( return request.session.proxy("db").create_database(
@ -774,7 +774,7 @@ class Database(http.Controller):
params['db_lang'], params['db_lang'],
params['create_admin_pwd']) params['create_admin_pwd'])
@http.route('/web/database/duplicate', type='json', authentication="nodb") @http.route('/web/database/duplicate', type='json', auth="none")
def duplicate(self, fields): def duplicate(self, fields):
params = dict(map(operator.itemgetter('name', 'value'), fields)) params = dict(map(operator.itemgetter('name', 'value'), fields))
duplicate_attrs = ( duplicate_attrs = (
@ -785,7 +785,7 @@ class Database(http.Controller):
return request.session.proxy("db").duplicate_database(*duplicate_attrs) return request.session.proxy("db").duplicate_database(*duplicate_attrs)
@http.route('/web/database/drop', type='json', authentication="nodb") @http.route('/web/database/drop', type='json', auth="none")
def drop(self, fields): def drop(self, fields):
password, db = operator.itemgetter( password, db = operator.itemgetter(
'drop_pwd', 'drop_db')( 'drop_pwd', 'drop_db')(
@ -798,7 +798,7 @@ class Database(http.Controller):
except Exception: except Exception:
return {'error': _('Could not drop database !'), 'title': _('Drop Database')} return {'error': _('Could not drop database !'), 'title': _('Drop Database')}
@http.route('/web/database/backup', type='http', authentication="nodb") @http.route('/web/database/backup', type='http', auth="none")
def backup(self, backup_db, backup_pwd, token): def backup(self, backup_db, backup_pwd, token):
try: try:
db_dump = base64.b64decode( db_dump = base64.b64decode(
@ -816,7 +816,7 @@ class Database(http.Controller):
except Exception, e: except Exception, e:
return simplejson.dumps([[],[{'error': openerp.tools.ustr(e), 'title': _('Backup Database')}]]) return simplejson.dumps([[],[{'error': openerp.tools.ustr(e), 'title': _('Backup Database')}]])
@http.route('/web/database/restore', type='http', authentication="nodb") @http.route('/web/database/restore', type='http', auth="none")
def restore(self, db_file, restore_pwd, new_db): def restore(self, db_file, restore_pwd, new_db):
try: try:
data = base64.b64encode(db_file.read()) data = base64.b64encode(db_file.read())
@ -825,7 +825,7 @@ class Database(http.Controller):
except openerp.exceptions.AccessDenied, e: except openerp.exceptions.AccessDenied, e:
raise Exception("AccessDenied") raise Exception("AccessDenied")
@http.route('/web/database/change_password', type='json', authentication="nodb") @http.route('/web/database/change_password', type='json', auth="none")
def change_password(self, fields): def change_password(self, fields):
old_password, new_password = operator.itemgetter( old_password, new_password = operator.itemgetter(
'old_pwd', 'new_pwd')( 'old_pwd', 'new_pwd')(
@ -849,13 +849,13 @@ class Session(http.Controller):
"username": request.session._login, "username": request.session._login,
} }
@http.route('/web/session/get_session_info', type='json', authentication="nodb") @http.route('/web/session/get_session_info', type='json', auth="none")
def get_session_info(self): def get_session_info(self):
request.uid = request.session._uid request.uid = request.session._uid
request.db = request.session._db request.db = request.session._db
return self.session_info() return self.session_info()
@http.route('/web/session/authenticate', type='json', authentication="nodb") @http.route('/web/session/authenticate', type='json', auth="none")
def authenticate(self, db, login, password, base_location=None): def authenticate(self, db, login, password, base_location=None):
wsgienv = request.httprequest.environ wsgienv = request.httprequest.environ
env = dict( env = dict(
@ -867,7 +867,7 @@ class Session(http.Controller):
return self.session_info() return self.session_info()
@http.route('/web/session/change_password', type='json', authentication="auth") @http.route('/web/session/change_password', type='json', auth="user")
def change_password(self, fields): def change_password(self, fields):
old_password, new_password,confirm_password = operator.itemgetter('old_pwd', 'new_password','confirm_pwd')( old_password, new_password,confirm_password = operator.itemgetter('old_pwd', 'new_password','confirm_pwd')(
dict(map(operator.itemgetter('name', 'value'), fields))) dict(map(operator.itemgetter('name', 'value'), fields)))
@ -883,24 +883,24 @@ class Session(http.Controller):
return {'error': _('The old password you provided is incorrect, your password was not changed.'), 'title': _('Change Password')} return {'error': _('The old password you provided is incorrect, your password was not changed.'), 'title': _('Change Password')}
return {'error': _('Error, password not changed !'), 'title': _('Change Password')} return {'error': _('Error, password not changed !'), 'title': _('Change Password')}
@http.route('/web/session/sc_list', type='json', authentication="auth") @http.route('/web/session/sc_list', type='json', auth="user")
def sc_list(self): def sc_list(self):
return request.session.model('ir.ui.view_sc').get_sc( return request.session.model('ir.ui.view_sc').get_sc(
request.session._uid, "ir.ui.menu", request.context) request.session._uid, "ir.ui.menu", request.context)
@http.route('/web/session/get_lang_list', type='json', authentication="nodb") @http.route('/web/session/get_lang_list', type='json', auth="none")
def get_lang_list(self): def get_lang_list(self):
try: try:
return request.session.proxy("db").list_lang() or [] return request.session.proxy("db").list_lang() or []
except Exception, e: except Exception, e:
return {"error": e, "title": _("Languages")} return {"error": e, "title": _("Languages")}
@http.route('/web/session/modules', type='json', authentication="auth") @http.route('/web/session/modules', type='json', auth="user")
def modules(self): def modules(self):
# return all installed modules. Web client is smart enough to not load a module twice # return all installed modules. Web client is smart enough to not load a module twice
return module_installed() return module_installed()
@http.route('/web/session/save_session_action', type='json', authentication="auth") @http.route('/web/session/save_session_action', type='json', auth="user")
def save_session_action(self, the_action): def save_session_action(self, the_action):
""" """
This method store an action object in the session object and returns an integer This method store an action object in the session object and returns an integer
@ -924,7 +924,7 @@ class Session(http.Controller):
saved_actions["next"] = key + 1 saved_actions["next"] = key + 1
return key return key
@http.route('/web/session/get_session_action', type='json', authentication="auth") @http.route('/web/session/get_session_action', type='json', auth="user")
def get_session_action(self, key): def get_session_action(self, key):
""" """
Gets back a previously saved action. This method can return None if the action Gets back a previously saved action. This method can return None if the action
@ -940,18 +940,18 @@ class Session(http.Controller):
return None return None
return saved_actions["actions"].get(key) return saved_actions["actions"].get(key)
@http.route('/web/session/check', type='json', authentication="auth") @http.route('/web/session/check', type='json', auth="user")
def check(self): def check(self):
request.session.assert_valid() request.session.assert_valid()
return None return None
@http.route('/web/session/destroy', type='json', authentication="auth") @http.route('/web/session/destroy', type='json', auth="user")
def destroy(self): def destroy(self):
request.session._suicide = True request.session._suicide = True
class Menu(http.Controller): class Menu(http.Controller):
@http.route('/web/menu/get_user_roots', type='json', authentication="auth") @http.route('/web/menu/get_user_roots', type='json', auth="user")
def get_user_roots(self): def get_user_roots(self):
""" Return all root menu ids visible for the session user. """ Return all root menu ids visible for the session user.
@ -973,7 +973,7 @@ class Menu(http.Controller):
return Menus.search(menu_domain, 0, False, False, request.context) return Menus.search(menu_domain, 0, False, False, request.context)
@http.route('/web/menu/load', type='json', authentication="auth") @http.route('/web/menu/load', type='json', auth="user")
def load(self): def load(self):
""" Loads all menu items (all applications and their sub-menus). """ Loads all menu items (all applications and their sub-menus).
@ -1024,7 +1024,7 @@ class Menu(http.Controller):
return menu_root return menu_root
@http.route('/web/menu/load_needaction', type='json', authentication="auth") @http.route('/web/menu/load_needaction', type='json', auth="user")
def load_needaction(self, menu_ids): def load_needaction(self, menu_ids):
""" Loads needaction counters for specific menu ids. """ Loads needaction counters for specific menu ids.
@ -1033,7 +1033,7 @@ class Menu(http.Controller):
""" """
return request.session.model('ir.ui.menu').get_needaction_data(menu_ids, request.context) return request.session.model('ir.ui.menu').get_needaction_data(menu_ids, request.context)
@http.route('/web/menu/action', type='json', authentication="auth") @http.route('/web/menu/action', type='json', auth="user")
def action(self, menu_id): def action(self, menu_id):
# still used by web_shortcut # still used by web_shortcut
actions = load_actions_from_ir_values('action', 'tree_but_open', actions = load_actions_from_ir_values('action', 'tree_but_open',
@ -1042,7 +1042,7 @@ class Menu(http.Controller):
class DataSet(http.Controller): class DataSet(http.Controller):
@http.route('/web/dataset/search_read', type='json', authentication="auth") @http.route('/web/dataset/search_read', type='json', auth="user")
def search_read(self, model, fields=False, offset=0, limit=False, domain=None, sort=None): def search_read(self, model, fields=False, offset=0, limit=False, domain=None, sort=None):
return self.do_search_read(model, fields, offset, limit, domain, sort) return self.do_search_read(model, fields, offset, limit, domain, sort)
def do_search_read(self, model, fields=False, offset=0, limit=False, domain=None def do_search_read(self, model, fields=False, offset=0, limit=False, domain=None
@ -1084,7 +1084,7 @@ class DataSet(http.Controller):
'records': records 'records': records
} }
@http.route('/web/dataset/load', type='json', authentication="auth") @http.route('/web/dataset/load', type='json', auth="user")
def load(self, model, id, fields): def load(self, model, id, fields):
m = request.session.model(model) m = request.session.model(model)
value = {} value = {}
@ -1110,26 +1110,26 @@ class DataSet(http.Controller):
return getattr(request.session.model(model), method)(*args, **kwargs) return getattr(request.session.model(model), method)(*args, **kwargs)
@http.route('/web/dataset/call', type='json', authentication="auth") @http.route('/web/dataset/call', type='json', auth="user")
def call(self, model, method, args, domain_id=None, context_id=None): def call(self, model, method, args, domain_id=None, context_id=None):
return self._call_kw(model, method, args, {}) return self._call_kw(model, method, args, {})
@http.route(['/web/dataset/call_kw', '/web/dataset/call_kw/<path:path>'], type='json', authentication="auth") @http.route(['/web/dataset/call_kw', '/web/dataset/call_kw/<path:path>'], type='json', auth="user")
def call_kw(self, model, method, args, kwargs, path=None): def call_kw(self, model, method, args, kwargs, path=None):
return self._call_kw(model, method, args, kwargs) return self._call_kw(model, method, args, kwargs)
@http.route('/web/dataset/call_button', type='json', authentication="auth") @http.route('/web/dataset/call_button', type='json', auth="user")
def call_button(self, model, method, args, domain_id=None, context_id=None): def call_button(self, model, method, args, domain_id=None, context_id=None):
action = self._call_kw(model, method, args, {}) action = self._call_kw(model, method, args, {})
if isinstance(action, dict) and action.get('type') != '': if isinstance(action, dict) and action.get('type') != '':
return clean_action(action) return clean_action(action)
return False return False
@http.route('/web/dataset/exec_workflow', type='json', authentication="auth") @http.route('/web/dataset/exec_workflow', type='json', auth="user")
def exec_workflow(self, model, id, signal): def exec_workflow(self, model, id, signal):
return request.session.exec_workflow(model, id, signal) return request.session.exec_workflow(model, id, signal)
@http.route('/web/dataset/resequence', type='json', authentication="auth") @http.route('/web/dataset/resequence', type='json', auth="user")
def resequence(self, model, ids, field='sequence', offset=0): def resequence(self, model, ids, field='sequence', offset=0):
""" Re-sequences a number of records in the model, by their ids """ Re-sequences a number of records in the model, by their ids
@ -1154,7 +1154,7 @@ class DataSet(http.Controller):
class View(http.Controller): class View(http.Controller):
@http.route('/web/view/add_custom', type='json', authentication="auth") @http.route('/web/view/add_custom', type='json', auth="user")
def add_custom(self, view_id, arch): def add_custom(self, view_id, arch):
CustomView = request.session.model('ir.ui.view.custom') CustomView = request.session.model('ir.ui.view.custom')
CustomView.create({ CustomView.create({
@ -1164,7 +1164,7 @@ class View(http.Controller):
}, request.context) }, request.context)
return {'result': True} return {'result': True}
@http.route('/web/view/undo_custom', type='json', authentication="auth") @http.route('/web/view/undo_custom', type='json', auth="user")
def undo_custom(self, view_id, reset=False): def undo_custom(self, view_id, reset=False):
CustomView = request.session.model('ir.ui.view.custom') CustomView = request.session.model('ir.ui.view.custom')
vcustom = CustomView.search([('user_id', '=', request.session._uid), ('ref_id' ,'=', view_id)], vcustom = CustomView.search([('user_id', '=', request.session._uid), ('ref_id' ,'=', view_id)],
@ -1179,7 +1179,7 @@ class View(http.Controller):
class TreeView(View): class TreeView(View):
@http.route('/web/treeview/action', type='json', authentication="auth") @http.route('/web/treeview/action', type='json', auth="user")
def action(self, model, id): def action(self, model, id):
return load_actions_from_ir_values( return load_actions_from_ir_values(
'action', 'tree_but_open',[(model, id)], 'action', 'tree_but_open',[(model, id)],
@ -1187,7 +1187,7 @@ class TreeView(View):
class Binary(http.Controller): class Binary(http.Controller):
@http.route('/web/binary/image', type='http', authentication="auth") @http.route('/web/binary/image', type='http', auth="user")
def image(self, model, id, field, **kw): def image(self, model, id, field, **kw):
last_update = '__last_update' last_update = '__last_update'
Model = request.session.model(model) Model = request.session.model(model)
@ -1242,7 +1242,7 @@ class Binary(http.Controller):
addons_path = http.addons_manifest['web']['addons_path'] addons_path = http.addons_manifest['web']['addons_path']
return open(os.path.join(addons_path, 'web', 'static', 'src', 'img', image), 'rb').read() return open(os.path.join(addons_path, 'web', 'static', 'src', 'img', image), 'rb').read()
@http.route('/web/binary/saveas', type='http', authentication="auth") @http.route('/web/binary/saveas', type='http', auth="user")
def saveas(self, model, field, id=None, filename_field=None, **kw): def saveas(self, model, field, id=None, filename_field=None, **kw):
""" Download link for files stored as binary fields. """ Download link for files stored as binary fields.
@ -1275,7 +1275,7 @@ class Binary(http.Controller):
[('Content-Type', 'application/octet-stream'), [('Content-Type', 'application/octet-stream'),
('Content-Disposition', content_disposition(filename))]) ('Content-Disposition', content_disposition(filename))])
@http.route('/web/binary/saveas_ajax', type='http', authentication="auth") @http.route('/web/binary/saveas_ajax', type='http', auth="user")
def saveas_ajax(self, data, token): def saveas_ajax(self, data, token):
jdata = simplejson.loads(data) jdata = simplejson.loads(data)
model = jdata['model'] model = jdata['model']
@ -1308,7 +1308,7 @@ class Binary(http.Controller):
('Content-Disposition', content_disposition(filename))], ('Content-Disposition', content_disposition(filename))],
cookies={'fileToken': int(token)}) cookies={'fileToken': int(token)})
@http.route('/web/binary/upload', type='http', authentication="auth") @http.route('/web/binary/upload', type='http', auth="user")
def upload(self, callback, ufile): def upload(self, callback, ufile):
# TODO: might be useful to have a configuration flag for max-length file uploads # TODO: might be useful to have a configuration flag for max-length file uploads
out = """<script language="javascript" type="text/javascript"> out = """<script language="javascript" type="text/javascript">
@ -1323,7 +1323,7 @@ class Binary(http.Controller):
args = [False, e.message] args = [False, e.message]
return out % (simplejson.dumps(callback), simplejson.dumps(args)) return out % (simplejson.dumps(callback), simplejson.dumps(args))
@http.route('/web/binary/upload_attachment', type='http', authentication="auth") @http.route('/web/binary/upload_attachment', type='http', auth="user")
def upload_attachment(self, callback, model, id, ufile): def upload_attachment(self, callback, model, id, ufile):
Model = request.session.model('ir.attachment') Model = request.session.model('ir.attachment')
out = """<script language="javascript" type="text/javascript"> out = """<script language="javascript" type="text/javascript">
@ -1346,7 +1346,7 @@ class Binary(http.Controller):
args = {'error': "Something horrible happened"} args = {'error': "Something horrible happened"}
return out % (simplejson.dumps(callback), simplejson.dumps(args)) return out % (simplejson.dumps(callback), simplejson.dumps(args))
@http.route('/web/binary/company_logo', type='http', authentication="nodb") @http.route('/web/binary/company_logo', type='http', auth="none")
def company_logo(self, dbname=None): def company_logo(self, dbname=None):
# TODO add etag, refactor to use /image code for etag # TODO add etag, refactor to use /image code for etag
uid = None uid = None
@ -1388,7 +1388,7 @@ class Binary(http.Controller):
class Action(http.Controller): class Action(http.Controller):
@http.route('/web/action/load', type='json', authentication="auth") @http.route('/web/action/load', type='json', auth="user")
def load(self, action_id, do_not_eval=False): def load(self, action_id, do_not_eval=False):
Actions = request.session.model('ir.actions.actions') Actions = request.session.model('ir.actions.actions')
value = False value = False
@ -1414,7 +1414,7 @@ class Action(http.Controller):
value = clean_action(action[0]) value = clean_action(action[0])
return value return value
@http.route('/web/action/run', type='json', authentication="auth") @http.route('/web/action/run', type='json', auth="user")
def run(self, action_id): def run(self, action_id):
return_action = request.session.model('ir.actions.server').run( return_action = request.session.model('ir.actions.server').run(
[action_id], request.context) [action_id], request.context)
@ -1425,7 +1425,7 @@ class Action(http.Controller):
class Export(http.Controller): class Export(http.Controller):
@http.route('/web/export/formats', type='json', authentication="auth") @http.route('/web/export/formats', type='json', auth="user")
def formats(self): def formats(self):
""" Returns all valid export formats """ Returns all valid export formats
@ -1439,7 +1439,7 @@ class Export(http.Controller):
fields = Model.fields_get(False, request.context) fields = Model.fields_get(False, request.context)
return fields return fields
@http.route('/web/export/get_fields', type='json', authentication="auth") @http.route('/web/export/get_fields', type='json', auth="user")
def get_fields(self, model, prefix='', parent_name= '', def get_fields(self, model, prefix='', parent_name= '',
import_compat=True, parent_field_type=None, import_compat=True, parent_field_type=None,
exclude=None): exclude=None):
@ -1488,7 +1488,7 @@ class Export(http.Controller):
return records return records
@http.route('/web/export/namelist', type='json', authentication="auth") @http.route('/web/export/namelist', type='json', auth="user")
def namelist(self, model, export_id): def namelist(self, model, export_id):
# TODO: namelist really has no reason to be in Python (although itertools.groupby helps) # TODO: namelist really has no reason to be in Python (although itertools.groupby helps)
export = request.session.model("ir.exports").read([export_id])[0] export = request.session.model("ir.exports").read([export_id])[0]
@ -1608,7 +1608,7 @@ class ExportFormat(object):
class CSVExport(ExportFormat, http.Controller): class CSVExport(ExportFormat, http.Controller):
fmt = {'tag': 'csv', 'label': 'CSV'} fmt = {'tag': 'csv', 'label': 'CSV'}
@http.route('/web/export/csv', type='http', authentication="auth") @http.route('/web/export/csv', type='http', auth="user")
def index(self, data, token): def index(self, data, token):
return self.base(data, token) return self.base(data, token)
@ -1650,7 +1650,7 @@ class ExcelExport(ExportFormat, http.Controller):
'error': None if xlwt else "XLWT required" 'error': None if xlwt else "XLWT required"
} }
@http.route('/web/export/xls', type='http', authentication="auth") @http.route('/web/export/xls', type='http', auth="user")
def index(self, data, token): def index(self, data, token):
return self.base(data, token) return self.base(data, token)
@ -1696,7 +1696,7 @@ class Reports(http.Controller):
'xls': 'application/vnd.ms-excel', 'xls': 'application/vnd.ms-excel',
} }
@http.route('/web/report', type='http', authentication="auth") @http.route('/web/report', type='http', auth="user")
def index(self, action, token): def index(self, action, token):
action = simplejson.loads(action) action = simplejson.loads(action)

View File

@ -87,7 +87,7 @@ TESTING = Template(u"""<!DOCTYPE html>
class TestRunnerController(http.Controller): class TestRunnerController(http.Controller):
@http.route('/web/tests', type='http', authentication="nodb") @http.route('/web/tests', type='http', auth="none")
def index(self, req, mod=None, **kwargs): def index(self, req, mod=None, **kwargs):
ms = module.get_modules() ms = module.get_modules()
manifests = dict( manifests = dict(

View File

@ -135,12 +135,12 @@ Authorization Levels
-------------------- --------------------
By default, all methods can only be used by users logged into OpenERP (OpenERP uses cookies to track logged users). By default, all methods can only be used by users logged into OpenERP (OpenERP uses cookies to track logged users).
There are some cases when you need to enable not-logged in users to access some methods. To do so, add the ``'noauth'`` There are some cases when you need to enable not-logged in users to access some methods. To do so, add the ``'db'``
value to the ``authentication`` parameter of ``http.route()``: value to the ``auth`` parameter of ``http.route()``:
:: ::
@http.route('/hello', type="http", authentication="noauth") @http.route('/hello', type="http", auth="db")
def hello(self): def hello(self):
return "<div>Hello unknown user!</div>" return "<div>Hello unknown user!</div>"
@ -158,7 +158,7 @@ want to override. Example that redefine the home page of your OpenERP applicatio
import openerp.addons.web.controllers.main as main import openerp.addons.web.controllers.main as main
class Home2(main.Home): class Home2(main.Home):
@http.route('/', type="http", authentication="noauth") @http.route('/', type="http", auth="db")
def index(self): def index(self):
return "<div>This is my new home page.</div>" return "<div>This is my new home page.</div>"

View File

@ -86,12 +86,12 @@ class WebRequest(object):
.. attribute:: db .. attribute:: db
``str``, the name of the database linked to the current request. Can be ``None`` ``str``, the name of the database linked to the current request. Can be ``None``
if the current request uses the ``nodb`` authentication. if the current request uses the ``none`` authentication.
.. attribute:: uid .. attribute:: uid
``int``, the id of the user related to the current request. Can be ``None`` ``int``, the id of the user related to the current request. Can be ``None``
if the current request uses the ``nodb`` or the ``noauth`` authenticatoin. if the current request uses the ``none`` or the ``db`` authenticatoin.
""" """
def __init__(self, httprequest): def __init__(self, httprequest):
self.httprequest = httprequest self.httprequest = httprequest
@ -149,10 +149,10 @@ class WebRequest(object):
self.lang = lang.replace('-', '_') self.lang = lang.replace('-', '_')
def _authenticate(self): def _authenticate(self):
if self.auth_method == "nodb": if self.auth_method == "none":
self.db = None self.db = None
self.uid = None self.uid = None
elif self.auth_method == "noauth": elif self.auth_method == "db":
self.db = (self.session._db or openerp.addons.web.controllers.main.db_monodb()).lower() self.db = (self.session._db or openerp.addons.web.controllers.main.db_monodb()).lower()
if not self.db: if not self.db:
raise SessionExpiredException("No valid database for request %s" % self.httprequest) raise SessionExpiredException("No valid database for request %s" % self.httprequest)
@ -169,14 +169,14 @@ class WebRequest(object):
def registry(self): def registry(self):
""" """
The registry to the database linked to this request. Can be ``None`` if the current request uses the The registry to the database linked to this request. Can be ``None`` if the current request uses the
``nodb'' authentication. ``none'' authentication.
""" """
return openerp.modules.registry.RegistryManager.get(self.db) if self.db else None return openerp.modules.registry.RegistryManager.get(self.db) if self.db else None
@property @property
def cr(self): def cr(self):
""" """
The cursor initialized for the current method call. If the current request uses the ``nodb`` authentication The cursor initialized for the current method call. If the current request uses the ``none`` authentication
trying to access this property will raise an exception. trying to access this property will raise an exception.
""" """
# some magic to lazy create the cr # some magic to lazy create the cr
@ -209,7 +209,7 @@ class WebRequest(object):
self.db = None self.db = None
self.uid = None self.uid = None
def route(route, type="http", authentication="auth"): def route(route, type="http", auth="user"):
""" """
Decorator marking the decorated method as being a handler for requests. The method must be part of a subclass Decorator marking the decorated method as being a handler for requests. The method must be part of a subclass
of ``Controller``. of ``Controller``.
@ -222,16 +222,16 @@ def route(route, type="http", authentication="auth"):
method. Can be a single string or an array of strings. See werkzeug's routing documentation for the format of method. Can be a single string or an array of strings. See werkzeug's routing documentation for the format of
route expression ( http://werkzeug.pocoo.org/docs/routing/ ). route expression ( http://werkzeug.pocoo.org/docs/routing/ ).
:param type: The type of request, can be ``'http'`` or ``'json'``. :param type: The type of request, can be ``'http'`` or ``'json'``.
:param authentication: The type of authentication method, can on of the following: :param auth: The type of authentication method, can on of the following:
* ``auth``: The user must be authenticated. * ``auth``: The user must be authenticated.
* ``noauth``: There is no need for the user to be authenticated but there must be a way to find the current * ``db``: There is no need for the user to be authenticated but there must be a way to find the current
database. database.
* ``nodb``: The method is always active, even if there is no database. Mainly used by the framework and * ``none``: The method is always active, even if there is no database. Mainly used by the framework and
authentication modules. authentication modules.
""" """
assert type in ["http", "json"] assert type in ["http", "json"]
assert authentication in ["auth", "noauth", "nodb"] assert auth in ["user", "db", "none"]
def decorator(f): def decorator(f):
if isinstance(route, list): if isinstance(route, list):
f.routes = route f.routes = route
@ -239,7 +239,7 @@ def route(route, type="http", authentication="auth"):
f.routes = [route] f.routes = [route]
f.exposed = type f.exposed = type
if getattr(f, "auth", None) is None: if getattr(f, "auth", None) is None:
f.auth = authentication f.auth = auth
return f return f
return decorator return decorator
@ -415,7 +415,7 @@ def jsonrequest(f):
base = f.__name__ base = f.__name__
if f.__name__ == "index": if f.__name__ == "index":
base = "" base = ""
return route([base, os.path.join(base, "<path:_ignored_path>")], type="json", authentication="auth")(f) return route([base, os.path.join(base, "<path:_ignored_path>")], type="json", auth="user")(f)
class HttpRequest(WebRequest): class HttpRequest(WebRequest):
""" Regular GET/POST request """ Regular GET/POST request
@ -498,7 +498,7 @@ def httprequest(f):
base = f.__name__ base = f.__name__
if f.__name__ == "index": if f.__name__ == "index":
base = "" base = ""
return route([base, os.path.join(base, "<path:_ignored_path>")], type="http", authentication="auth")(f) return route([base, os.path.join(base, "<path:_ignored_path>")], type="http", auth="user")(f)
#---------------------------------------------------------- #----------------------------------------------------------
# Local storage of requests # Local storage of requests
@ -604,14 +604,14 @@ class Model(object):
def proxy(*args, **kw): def proxy(*args, **kw):
# Can't provide any retro-compatibility for this case, so we check it and raise an Exception # Can't provide any retro-compatibility for this case, so we check it and raise an Exception
# to tell the programmer to adapt his code # to tell the programmer to adapt his code
if not http.request.db or not http.request.uid or self.session._db != http.request.db \ if not request.db or not request.uid or self.session._db != request.db \
or self.session._uid != http.request.uid: or self.session._uid != request.uid:
raise Exception("Trying to use Model with badly configured database or user.") raise Exception("Trying to use Model with badly configured database or user.")
mod = http.request.registry.get(self.model) mod = request.registry.get(self.model)
meth = getattr(mod, method) meth = getattr(mod, method)
cr = http.request.cr cr = request.cr
result = meth(cr, http.request.uid, *args, **kw) result = meth(cr, request.uid, *args, **kw)
# reorder read # reorder read
if method == "read": if method == "read":
if isinstance(result, list) and len(result) > 0 and "id" in result[0]: if isinstance(result, list) and len(result) > 0 and "id" in result[0]:
@ -659,8 +659,8 @@ class OpenERPSession(object):
self._uid = uid self._uid = uid
self._login = login self._login = login
self._password = password self._password = password
http.request.db = db request.db = db
http.request.uid = uid request.uid = uid
if uid: self.get_context() if uid: self.get_context()
return uid return uid
@ -685,7 +685,7 @@ class OpenERPSession(object):
:returns: the new context :returns: the new context
""" """
assert self._uid, "The user needs to be logged-in to initialize his context" assert self._uid, "The user needs to be logged-in to initialize his context"
self.context = http.request.registry.get('res.users').context_get(http.request.cr, http.request.uid) or {} self.context = request.registry.get('res.users').context_get(request.cr, request.uid) or {}
self.context['uid'] = self._uid self.context['uid'] = self._uid
self._fix_lang(self.context) self._fix_lang(self.context)
return self.context return self.context
@ -1031,7 +1031,7 @@ class Root(object):
members = inspect.getmembers(o) members = inspect.getmembers(o)
for mk, mv in members: for mk, mv in members:
if inspect.ismethod(mv) and getattr(mv, 'exposed', False) and \ if inspect.ismethod(mv) and getattr(mv, 'exposed', False) and \
nodb_only == (getattr(mv, 'auth', None) == "nodb"): nodb_only == (getattr(mv, "user", None) == "none"):
function = (o.get_wrapped_method(mk), mv) function = (o.get_wrapped_method(mk), mv)
for url in mv.routes: for url in mv.routes:
if getattr(mv, "combine", False): if getattr(mv, "combine", False):
@ -1042,7 +1042,7 @@ class Root(object):
modules_set = set(controllers_per_module.keys()) modules_set = set(controllers_per_module.keys())
modules_set -= set("web") modules_set -= set("web")
# building all nodb methods # building all none methods
gen(["web"] + sorted(modules_set), True) gen(["web"] + sorted(modules_set), True)
if not db: if not db:
return routing_map return routing_map
@ -1088,7 +1088,7 @@ class Root(object):
return func(*args, **kwargs) return func(*args, **kwargs)
request.func = nfunc request.func = nfunc
request.auth_method = getattr(original, "auth", "auth") request.auth_method = getattr(original, "auth", "user")
request.func_request_type = original.exposed request.func_request_type = original.exposed
def wsgi_postload(): def wsgi_postload():