def test_force_logout_if_cookie_is_missing(self): """Should silently disconnect user if YouCKAN cookie is missing""" with self.app.test_client() as client: self.login(client=client) response = self.get(url_for("site.dashboard"), base_url="https://localhost", client=client) self.assert200(response) self.assertFalse(current_user.is_authenticated())
def set_dataset_identity(identity, dataset): if not current_user.is_authenticated(): return if dataset.owner and current_user.id == dataset.owner.id: identity.provides.add(DatasetOwnerNeed(str(dataset.id))) for resource in dataset.resources + dataset.community_resources: if resource.owner and current_user.id == resource.owner.id: identity.provides.add(ResourceOwnerNeed(str(resource.id)))
def wrapper(*args, **kwargs): if not current_user.is_authenticated(): self.abort(401) if permission is not None: with permission.require(403): return func(*args, **kwargs) else: return func(*args, **kwargs)
def wrapper(*args, **kwargs): if not current_user.is_authenticated(): self.abort(401) if permission is not None: with permission.require(403): return func(*args, **kwargs) else: return func(*args, **kwargs)
def reject_source(ident, comment): '''Reject a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_REFUSED if current_user.is_authenticated(): source.validation.by = current_user._get_current_object() source.save() return source
def reject_source(ident, comment): '''Reject a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_REFUSED if current_user.is_authenticated(): source.validation.by = current_user._get_current_object() source.save() return source
def check_youckan_cookie(): # Do not interfere with authorize endpoint if request.endpoint == 'youckan.authorized': return # Force session open and close depending on the youckan session state session_cookie_name = current_app.config['YOUCKAN_SESSION_COOKIE'] logged_cookie_name = '{0}.logged'.format(current_app.config['YOUCKAN_AUTH_COOKIE']) if session_cookie_name in request.cookies and logged_cookie_name in request.cookies: session_id = request.cookies[session_cookie_name] if not current_user.is_authenticated() or not 'youckan.token' in session: return youckan.authorize( callback=url_for('youckan.authorized', _external=True, _scheme='https'), state=encode_state(session_id), next=request.url.replace('http://', 'https://') ) elif current_user.is_authenticated(): logout_user()
def test_log_user_on_authorize_callback(self): """Should log the user in on authorize callback""" user = UserFactory() with self.mock_authorize(slug=user.slug) as (profile, client): response = self.get(url_for("youckan.authorized", code="code"), client=client) self.assertRedirects(response, url_for("site.home")) self.assertIn("youckan.token", session) self.assertTrue(current_user.is_authenticated()) self.assertEqual(len(User.objects), 1)
def validate_source(ident, comment=None): '''Validate a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_ACCEPTED if current_user.is_authenticated(): source.validation.by = current_user._get_current_object() source.save() launch(ident) return source
def validate_source(ident, comment=None): '''Validate a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_ACCEPTED if current_user.is_authenticated(): source.validation.by = current_user._get_current_object() source.save() launch(ident) return source
def test_logout_redirect_to_youckan(self): """Logout should trigger a YouCKAN logout""" with self.app.test_client() as client: self.login(client=client) response = self.get(url_for("security.logout"), base_url="https://localhost", client=client) self.assertStatus(response, 302) self.assertFalse(current_user.is_authenticated()) expected_url = urlparse(YouckanSettings.YOUCKAN_URL + "logout") response_url = urlparse(response.location) self.assertEqual(response_url.hostname, expected_url.hostname) self.assertEqual(response_url.path, expected_url.path)
def wrapper(*args, **kwargs): if current_user.is_authenticated(): return func(*args, **kwargs) apikey = request.headers.get(HEADER_API_KEY) if not apikey: self.abort(401) try: user = User.objects.get(apikey=apikey) except User.DoesNotExist: self.abort(401, 'Invalid API Key') if not login_user(user, False): self.abort(401, 'Inactive user') return func(*args, **kwargs)
def wrapper(*args, **kwargs): if current_user.is_authenticated(): return func(*args, **kwargs) apikey = request.headers.get(HEADER_API_KEY) if apikey: try: user = User.objects.get(apikey=apikey) except User.DoesNotExist: self.abort(401, "Invalid API Key") if not login_user(user, False): self.abort(401, "Inactive user") else: oauth2.check_credentials() return func(*args, **kwargs)
def wrapper(*args, **kwargs): if current_user.is_authenticated(): return func(*args, **kwargs) apikey = request.headers.get(HEADER_API_KEY) if apikey: try: user = User.objects.get(apikey=apikey) except User.DoesNotExist: self.abort(401, 'Invalid API Key') if not login_user(user, False): self.abort(401, 'Inactive user') else: oauth2.check_credentials() return func(*args, **kwargs)
def pre_validate(self, form): if self.data: if not current_user.is_authenticated(): raise validators.ValidationError( _('You must be authenticated')) elif not OrganizationPrivatePermission(self.data).can(): raise validators.ValidationError( _("Permission denied for this organization")) # Ensure either owner field or this field value is unset owner_field = form._fields[self.owner_field] if self.raw_data: owner_field.data = None elif getattr(form._obj, self.short_name) and not owner_field.data: pass else: self.data = None return True
def test_fetch_token_and_create_user_on_authorize_callback(self): """Should create the user on authorize callback""" with self.mock_authorize() as (profile, client): response = self.get(url_for("youckan.authorized", code="code"), client=client) self.assertRedirects(response, url_for("site.home")) self.assertIn("youckan.token", session) self.assertTrue(current_user.is_authenticated()) self.assertTrue(current_user.is_active()) self.assertEqual(current_user.slug, profile["slug"]) self.assertEqual(current_user.first_name, profile["first_name"]) self.assertEqual(current_user.last_name, profile["last_name"]) self.assertEqual(current_user.email, profile["email"]) self.assertEqual(current_user.has_role("admin"), profile["is_superuser"]) self.assertEqual(current_user.avatar_url, profile["profile"]["avatar"]) self.assertEqual(len(User.objects), 1)
def pre_validate(self, form): if self.data: if not current_user.is_authenticated(): raise validators.ValidationError( _('You must be authenticated')) elif not OrganizationPrivatePermission(self.data).can(): raise validators.ValidationError( _("Permission denied for this organization")) # Ensure either owner field or this field value is unset owner_field = form._fields[self.owner_field] if self.raw_data: owner_field.data = None elif getattr(form._obj, self.short_name) and not owner_field.data: pass else: self.data = None return True
def test_trigger_oauth_login_on_cookie(self): """Should trigger a OAuth handshake if YouCKAN cookie is present""" with self.app.test_client() as client: self.assertFalse(current_user.is_authenticated()) client.set_cookie("udata.dev", YouckanSettings.YOUCKAN_SESSION_COOKIE, "session_id") client.set_cookie("udata.dev", YouckanSettings.YOUCKAN_AUTH_COOKIE, "whatever") client.set_cookie("udata.dev", YouckanSettings.YOUCKAN_AUTH_COOKIE + ".logged", "whatever") response = self.get("/somewhere", client=client) self.assertStatus(response, 302) response_url = urlparse(response.location) expected_url = urlparse(self.app.config["YOUCKAN_AUTHORIZE_URL"]) self.assertEqual(response_url.hostname, expected_url.hostname) self.assertEqual(response_url.path, expected_url.path) qs = parse_qs(response_url.query) self.assertIn("state", qs) state = decode_state(qs["state"][0]) self.assertEqual(state["next_url"], "https://localhost/somewhere")
def test_update_user_on_authorize_callback(self): """Should only update specific field on authorize callback""" user = UserFactory() old_slug = user.slug with self.mock_authorize(slug=user.slug, is_superuser=True) as (profile, client): response = self.get(url_for("youckan.authorized", code="code"), client=client) self.assertRedirects(response, url_for("site.home")) self.assertIn("youckan.token", session) self.assertTrue(current_user.is_authenticated()) user.reload() self.assertEqual(user.slug, old_slug) self.assertEqual(user.first_name, profile["first_name"]) self.assertEqual(user.last_name, profile["last_name"]) self.assertEqual(user.email, profile["email"]) self.assertEqual(user.avatar_url, profile["profile"]["avatar"]) self.assertEqual(len(User.objects), 1)
def add_badge(self, kind): '''Perform an atomic prepend for a new badge''' badge = self.get_badge(kind) if badge: return badge if kind not in getattr(self, '__badges__', {}): msg = 'Unknown badge type for {model}: {kind}' raise db.ValidationError(msg.format(model=self.__class__.__name__, kind=kind)) badge = Badge(kind=kind) if current_user.is_authenticated(): badge.created_by = current_user.id self.update(__raw__={ '$push': { 'badges': { '$each': [badge.to_mongo()], '$position': 0 } } }) self.reload() post_save.send(self.__class__, document=self) return self.get_badge(kind)
def add_badge(self, kind): '''Perform an atomic prepend for a new badge''' badge = self.get_badge(kind) if badge: return badge if kind not in getattr(self, '__badges__', {}): msg = 'Unknown badge type for {model}: {kind}' raise db.ValidationError( msg.format(model=self.__class__.__name__, kind=kind)) badge = Badge(kind=kind) if current_user.is_authenticated(): badge.created_by = current_user.id self.update(__raw__={ '$push': { 'badges': { '$each': [badge.to_mongo()], '$position': 0 } } }) self.reload() post_save.send(self.__class__, document=self) return self.get_badge(kind)
def set_dataset_identity(identity, dataset): if not current_user.is_authenticated(): return if dataset.owner and current_user.id == dataset.owner.id: identity.provides.add(DatasetOwnerNeed(str(dataset.id)))
def is_following(obj): return current_user.is_authenticated() and Follow.objects.is_following(current_user._get_current_object(), obj)
def default_owner(): '''Default to current_user if authenticated''' if current_user.is_authenticated(): return current_user._get_current_object()
def inject_organization_needs(sender, identity): if current_user.is_authenticated(): for org in Organization.objects(members__user=current_user.id): membership = get_by(org.members, 'user', current_user._get_current_object()) identity.provides.add(OrganizationNeed(membership.role, org.id))
def default_owner(): '''Default to current_user if authenticated''' if current_user.is_authenticated(): return current_user._get_current_object()
def on_user_deleted_dataset(dataset): if (not dataset.private and current_user and current_user.is_authenticated()): user = current_user._get_current_object() organization = dataset.organization write_activity.delay(UserDeletedDataset, user, dataset, organization)
def on_user_deleted_dataset(dataset): if (not dataset.private and current_user and current_user.is_authenticated()): user = current_user._get_current_object() organization = dataset.organization write_activity.delay(UserDeletedDataset, user, dataset, organization)
def inject_organization_needs(sender, identity): if current_user.is_authenticated(): for org in Organization.objects(members__user=current_user.id): membership = get_by(org.members, 'user', current_user._get_current_object()) identity.provides.add(OrganizationNeed(membership.role, org.id))
def is_following(obj): return (current_user.is_authenticated() and Follow.objects.is_following(current_user._get_current_object(), obj))
def set_reuse_identity(identity, reuse): if not current_user.is_authenticated(): return if reuse.owner and current_user.id == reuse.owner.id: identity.provides.add(ReuseOwnerNeed(str(reuse.id)))