def login_user(self, username='******'): from invenio.legacy.websession_model import User from invenio.ext.login import login_user, current_user user_id = User.query.filter_by(nickname=username).one().id login_user(user_id) assert user_id == current_user.get_id() return user_id
def create_and_login_user(self, user_nickname=None, user_password=None): """Create test user and log him in.""" from invenio.modules.accounts.models import User self.user_nickname = user_nickname or "tester" self.user_password = user_password or "tester" # remove the user if he exists self.user = User.query.filter( User.nickname == self.user_nickname).first() if self.user: try: db.session.delete(self.user) db.session.commit() except: db.session.rollback() raise # create the user email = "{}@b2share.com".format(self.user_nickname) self.user = User(email=email, nickname=self.user_nickname) self.user.password = self.user_password try: db.session.add(self.user) db.session.commit() except: db.session.rollback() raise from invenio.ext.login import login_user from flask.ext.login import current_user login_user(self.user.id) current_user.reload() self.assertEqual(current_user.get_id(), self.user.id) self.safe_login_web_user(self.user_nickname, self.user_password) return self.user.id
def login_oauth2_user(valid, oauth): """ Login a user after having been verified """ if valid: login_user(oauth.user.id) return valid, oauth
def setUid(req, uid, remember_me=False): """It sets the userId into the session, and raise the cookie to the client. """ if uid > 0: login_user(uid, remember_me) else: logout_user() return uid
def auth_key(*args, **kwargs): if 'apikey' in request.values: from .models import WebAPIKey from invenio.ext.login import login_user user_id = WebAPIKey.acc_get_uid_from_request() if user_id == -1: abort(401) login_user(user_id) else: abort(401) return f(*args, **kwargs)
def register(): req = request.get_legacy_request() # FIXME if cfg.get('CFG_ACCESS_CONTROL_LEVEL_SITE') > 0: return webuser.page_not_authorized(req, "../youraccount/register?ln=%s" % g.ln, navmenuid='youraccount') form = RegisterForm(request.values, csrf_enabled=False) #uid = current_user.get_id() title = _("Register") messages = [] state = "" if form.validate_on_submit(): ruid = webuser.registerUser(req, form.email.data.encode('utf8'), form.password.data.encode('utf8'), form.nickname.data.encode('utf8'), ln=g.ln) if ruid == 0: title = _("Account created") messages.append(_("Your account has been successfully created.")) state = "success" if cfg.get('CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT') == 1: messages.append(_("In order to confirm its validity, an email message containing an account activation key has been sent to the given email address.")) messages.append(_("Please follow instructions presented there in order to complete the account registration process.")) if cfg.get('CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS') >= 1: messages.append(_("A second email will be sent when the account has been activated and can be used.")) elif cfg.get('CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT') != 1: user = User.query.filter(User.email == form.email.data.lower()).one() login_user(user.get_id()) messages.append(_("You can now access your account.")) else: title = _("Registration failure") state = "danger" if ruid == 5: messages.append(_("Users cannot register themselves, only admin can register them.")) elif ruid == 6 or ruid == 1: # Note, code 1 is used both for invalid email, and email sending # problems, however the email address is validated by the form, # so we only have to report a problem sending the email here messages.append(_("The site is having troubles in sending you an email for confirming your email address.")) messages.append(_("The error has been logged and will be taken in consideration as soon as possible.")) else: # Errors [-2, (1), 2, 3, 4] taken care of by form validation messages.append(_("Internal error %(ruid)s", ruid=ruid)) elif request.method == 'POST': title = _("Registration failure") state = "warning" return render_template('accounts/register.html', form=form, title=title, messages=messages, state=state)
def action_become_user(self, ids): """Inactivate users.""" try: if len(ids) != 1: flash('You can only become one user at a time.', '') user = User.query.get(ids[0]) logout_user() login_user(user) except Exception as ex: if not self.handle_view_exception(ex): raise flash('Failed to become users. %(error)s' % dict(error=str(ex)), 'error')
def decorated(*args, **kwargs): if 'apikey' in request.values: # API key authentication warnings.warn( "API keys will be superseded by OAuth personal access " "tokens", PendingDeprecationWarning ) from invenio.modules.apikeys.models import WebAPIKey from invenio.ext.login import login_user user_id = WebAPIKey.acc_get_uid_from_request() if user_id == -1: restful.abort(401) login_user(user_id) resp = f(None, *args, **kwargs) session.clear() return resp else: # OAuth 2.0 Authentication for func in oauth2._before_request_funcs: func() server = oauth2.server uri, http_method, body, headers = extract_params() valid, req = server.verify_request( uri, http_method, body, headers, scopes ) for func in oauth2._after_request_funcs: valid, req = func(valid, req) if not valid: return restful.abort( 401, message="Unauthorized", status=401, ) resp = f(req, *args, **kwargs) session.clear() return resp restful.abort(401)
def upload(service, src, dest, user=None): """Upload a file.""" from invenio.ext.login import login_user, logout_user from invenio.ext.sqlalchemy import db from invenio_accounts.models import User from invenio.modules.cloudconnector import utils from invenio_oauthclient.views.client import setup_app # Get user instance user = User.query.filter(db.or_( User.nickname == user, User.email == user, User.id == user)).one() login_user(user.id) setup_app() utils.upload(service, src, dest) logout_user()
def do_upgrade(): """Implement your upgrades here.""" from invenio.b2share.modules.b2deposit.edit import get_domain_admin_group from invenio.b2share.modules.b2deposit.b2share_model import metadata_classes from invenio.modules.accounts.models import User from invenio.ext.login import login_user from flask.ext.login import current_user admin_user = User.query.get(1) login_user(admin_user.get_id()) if not current_user.is_super_admin: raise Exception("Cannot find the superadmin user") for domain in metadata_classes(): groupname = get_domain_admin_group(domain) print "Creating domain administrator group: ", groupname create_user_group(groupname, 'Administrators of the {} domain'.format(domain), admin_user)
def decorated(*args, **kwargs): if 'apikey' in request.values: # API key authentication warnings.warn( "API keys will be superseded by OAuth personal access " "tokens", PendingDeprecationWarning ) from invenio.modules.apikeys.models import WebAPIKey from invenio.ext.login import login_user user_id = WebAPIKey.acc_get_uid_from_request() if user_id == -1: restful.abort(401) login_user(user_id) resp = f(None, *args, **kwargs) else: # OAuth 2.0 Authentication resp = f_oauth_required(*args, **kwargs) session.clear() return resp
def test_low_level_login(data, self): users = data.UserData assert current_user.is_guest login_user(users.admin.id) assert current_user.get_id() == users.admin.id logout_user() assert current_user.get_id() != users.admin.id assert current_user.is_guest login_user(users.romeo.id) assert not current_user.is_guest assert current_user.get_id() == users.romeo.id login_user(users.admin.id) assert current_user.get_id() == users.admin.id logout_user()
def login_oauth2_user(valid, oauth): """Log in a user after having been verified.""" if valid: login_user(oauth.user.id) return valid, oauth
def _handler(req): """ This handler is invoked by mod_python with the apache request.""" allowed_methods = ("GET", "POST", "HEAD", "OPTIONS", "PUT") #req.allow_methods(allowed_methods, 1) #if req.method not in allowed_methods: # raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED if req.method == 'OPTIONS': ## OPTIONS is used to now which method are allowed req.headers_out['Allow'] = ', '.join(allowed_methods) raise apache.SERVER_RETURN, apache.OK # Set user agent for fckeditor.py, which needs it here os.environ["HTTP_USER_AGENT"] = req.headers_in.get('User-Agent', '') # Check if REST authentication can be performed if req.args: args = cgi.parse_qs(req.args) if 'apikey' in args and req.is_https(): uid = web_api_key.acc_get_uid_from_request() if uid < 0: raise apache.SERVER_RETURN, apache.HTTP_UNAUTHORIZED else: login_user(uid) guest_p = int(current_user.is_guest) uri = req.uri if uri == '/': path = [''] else: ## Let's collapse multiple slashes into a single / uri = RE_SLASHES.sub('/', uri) path = uri[1:].split('/') if CFG_ACCESS_CONTROL_LEVEL_SITE > 1: ## If the site is under maintainance mode let's return ## 503 to casual crawler to avoid having the site being ## indexed req.status = 503 g = _RE_BAD_MSIE.search(req.headers_in.get('User-Agent', "MSIE 6.0")) bad_msie = g and float(g.group(1)) < 9.0 if uri.startswith('/yours') or not guest_p: ## Private/personalized request should not be cached if bad_msie and req.is_https(): req.headers_out['Cache-Control'] = 'private, max-age=0, must-revalidate' else: req.headers_out['Cache-Control'] = 'private, no-cache, no-store, max-age=0, must-revalidate' req.headers_out['Pragma'] = 'no-cache' req.headers_out['Vary'] = '*' elif not (bad_msie and req.is_https()): req.headers_out['Cache-Control'] = 'public, max-age=3600' req.headers_out['Vary'] = 'Cookie, ETag, Cache-Control' try: if req.header_only and not RE_SPECIAL_URI.match(req.uri): return root._traverse(req, path, True, guest_p) else: ## bibdocfile have a special treatment for HEAD return root._traverse(req, path, False, guest_p) except TraversalError: raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND except apache.SERVER_RETURN: ## This is one of mod_python way of communicating raise except IOError as exc: if 'Write failed, client closed connection' not in "%s" % exc: ## Workaround for considering as false positive exceptions ## rised by mod_python when the user close the connection ## or in some other rare and not well identified cases. register_exception(req=req, alert_admin=True) raise except Exception: # send the error message, much more convenient than log hunting if remote_debugger: args = {} if req.args: args = cgi.parse_qs(req.args) if 'debug' in args: remote_debugger.error_msg(args['debug']) register_exception(req=req, alert_admin=True) raise # Serve an error by default. raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
def _handler(req): """ This handler is invoked by mod_python with the apache request.""" allowed_methods = ("GET", "POST", "HEAD", "OPTIONS", "PUT") #req.allow_methods(allowed_methods, 1) #if req.method not in allowed_methods: # raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED if req.method == 'OPTIONS': ## OPTIONS is used to now which method are allowed req.headers_out['Allow'] = ', '.join(allowed_methods) raise apache.SERVER_RETURN, apache.OK # Set user agent for fckeditor.py, which needs it here os.environ["HTTP_USER_AGENT"] = req.headers_in.get('User-Agent', '') # Check if REST authentication can be performed if req.args: args = cgi.parse_qs(req.args) if 'apikey' in args and req.is_https(): uid = web_api_key.acc_get_uid_from_request() if uid < 0: raise apache.SERVER_RETURN, apache.HTTP_UNAUTHORIZED else: login_user(uid) guest_p = int(current_user.is_guest) uri = req.uri if uri == '/': path = [''] else: ## Let's collapse multiple slashes into a single / uri = RE_SLASHES.sub('/', uri) path = uri[1:].split('/') if CFG_ACCESS_CONTROL_LEVEL_SITE > 1: ## If the site is under maintainance mode let's return ## 503 to casual crawler to avoid having the site being ## indexed req.status = 503 g = _RE_BAD_MSIE.search(req.headers_in.get('User-Agent', "MSIE 6.0")) bad_msie = g and float(g.group(1)) < 9.0 if uri.startswith('/yours') or not guest_p: ## Private/personalized request should not be cached if bad_msie and req.is_https(): req.headers_out[ 'Cache-Control'] = 'private, max-age=0, must-revalidate' else: req.headers_out[ 'Cache-Control'] = 'private, no-cache, no-store, max-age=0, must-revalidate' req.headers_out['Pragma'] = 'no-cache' req.headers_out['Vary'] = '*' elif not (bad_msie and req.is_https()): req.headers_out['Cache-Control'] = 'public, max-age=3600' req.headers_out['Vary'] = 'Cookie, ETag, Cache-Control' try: if req.header_only and not RE_SPECIAL_URI.match(req.uri): return root._traverse(req, path, True, guest_p) else: ## bibdocfile have a special treatment for HEAD return root._traverse(req, path, False, guest_p) except TraversalError: raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND except apache.SERVER_RETURN: ## This is one of mod_python way of communicating raise except IOError as exc: if 'Write failed, client closed connection' not in "%s" % exc: ## Workaround for considering as false positive exceptions ## rised by mod_python when the user close the connection ## or in some other rare and not well identified cases. register_exception(req=req, alert_admin=True) raise except Exception: # send the error message, much more convenient than log hunting register_exception(req=req, alert_admin=True) raise # Serve an error by default. raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND