def get_pybb_profile_model(): from pybb import defaults if defaults.PYBB_PROFILE_RELATED_NAME: return compat.get_related_model_class(get_user_model(), defaults.PYBB_PROFILE_RELATED_NAME) else: return get_user_model()
def get_pybb_profile_model(): from pybb import defaults if defaults.PYBB_PROFILE_RELATED_NAME: return getattr(get_user_model(), defaults.PYBB_PROFILE_RELATED_NAME).related.field.model else: return get_user_model()
def get_pybb_profile_model(): from pybb import defaults if defaults.PYBB_PROFILE_RELATED_NAME: return getattr(get_user_model(), defaults.PYBB_PROFILE_RELATED_NAME).related.model else: return get_user_model()
def test_post_in_category_hidden_is_accessible_by_unauthenticated_user(self): self.parent_forum.hidden = True self.parent_forum.save() with patch.object(get_user_model(), 'is_authenticated', new_callable=PropertyMock, return_value=False): self.assertFalse(self.post.is_accessible_by(self.newbie)) with patch.object(get_user_model(), 'is_authenticated', new_callable=PropertyMock, return_value=True): self.assertTrue(self.post.is_accessible_by(self.user)) self.assertTrue(self.post.is_accessible_by(self.staff)) self.assertTrue(self.post.is_accessible_by(self.superuser))
def superuser(self): superuser = get_user_model().objects.create_user('oleiade', 'oleiade@localhost', '$ecret') superuser.is_superuser = True superuser.is_staff = True superuser.save() return superuser
def handle_user_logged_in(sender, request, user, **kwargs): from pybb.compat import get_user_model User = get_user_model() try: BannedUser.objects.get(user=user) except BannedUser.DoesNotExist: value = request.COOKIES.get(settings.PYBB_BAN_COOKIE_NAME, None) banned_user = None if value: try: existing_user = User.objects.get(pk=int(value)) except (User.DoesNotExist, ValueError): banned_user = BannedUser(user=user, reason=_('Cookie exists: user already banned from anonymous account')) else: banned_user = BannedUser(user=user, reason=_('Cookie exists: user already banned for the account %s') % existing_user) ip_address = get_ip(request) exists = IPAddress.objects.filter(ip_address=ip_address, banned=True).exists() if exists: banned_user = BannedUser(user=user, reason=_('IP Address %s is banned') % ip_address) if banned_user: banned_user.save()
def lookup_users(qs): user_ids = queryset_to_dict(qs, key='user_id', singular=False) users = queryset_to_dict(get_user_model().objects.filter(id__in=user_ids.keys())) try: Profile = get_profile_model() profiles = queryset_to_dict(Profile.objects.filter(user__in=users.keys()), key='user_id') except SiteProfileNotAvailable: profiles = {} for user_id, objs in user_ids.iteritems(): if user_id in users: user = users[user_id] for obj in objs: obj.user = user if user_id in profiles: obj.user._profile_cache = profiles[user_id] obj.user._profile_cache.user = obj.user else: for obj in objs: obj.user_id = None
def test_ban_middelware(self): from pybb.compat import get_user_model with patch.object(get_user_model(), 'is_authenticated') as is_authenticated: is_authenticated.return_value = True factory = RequestFactory(REMOTE_ADDR='199.59.149.230') request = factory.get('/post/1') request.user = self.user request.session = {} middleware = PybbBanMiddleware() middleware.process_request(request) self.assertEqual(IPAddress.objects.filter(user=self.user, ip_address='199.59.149.230').count(), 1) ip_address = IPAddress.objects.get(user=self.user, ip_address='199.59.149.230') ip_address.banned = True ip_address.save() middleware = PybbBanMiddleware() response = middleware.process_request(request) self.assertEqual(int(response.cookies[settings.PYBB_BAN_COOKIE_NAME].value), self.user.pk)
def test_subscription(self): user = get_user_model().objects.create_user(username='******', password='******', email='*****@*****.**') client = Client() client.login(username='******', password='******') response = client.post(reverse('pybb:subscription_create'), data={ 'topic_id': self.topic.pk, 'type': Subscription.TYPE_INSTANT_ALERT }) self.assertEqual(response.status_code, 302) self.assertRedirects(response, self.topic.get_absolute_url()) self.assertTrue(user in list(self.topic.subscribers.all())) new_post = Post(topic=self.topic, user=self.user, body='test subscribtion юникод') new_post.save() self.assertTrue([ msg for msg in mail.outbox if new_post.get_absolute_url() in msg.body ]) response = client.post(reverse('pybb:subscription_delete'), data={'topic_id': self.topic.pk}) self.assertEqual(response.status_code, 302) self.assertRedirects(response, self.topic.get_absolute_url()) self.assertTrue(user not in list(self.topic.subscribers.all()))
def setup(): pre_save.connect(pre_save_category_slug, sender=Category) pre_save.connect(pre_save_forum_slug, sender=Forum) pre_save.connect(pre_save_topic_slug, sender=Topic) post_save.connect(post_saved, sender=Post) post_delete.connect(post_deleted, sender=Post) if defaults.PYBB_AUTO_USER_PERMISSIONS: post_save.connect(user_saved, sender=compat.get_user_model())
def clean_username(self): username = self.cleaned_data['username'] try: self.get_user(username) except get_user_model().DoesNotExist: raise forms.ValidationError(self.error_messages['unknown_username']) else: return username
def clean_username(self): username = self.cleaned_data['username'] try: self.get_user(username) except get_user_model().DoesNotExist: raise forms.ValidationError( self.error_messages['unknown_username']) else: return username
def test_post_in_category_hidden_is_accessible_by_unauthenticated_user( self): self.parent_forum.hidden = True self.parent_forum.save() with patch.object(get_user_model(), 'is_authenticated', new_callable=PropertyMock, return_value=False): self.assertFalse(self.post.is_accessible_by(self.newbie)) with patch.object(get_user_model(), 'is_authenticated', new_callable=PropertyMock, return_value=True): self.assertTrue(self.post.is_accessible_by(self.user)) self.assertTrue(self.post.is_accessible_by(self.staff)) self.assertTrue(self.post.is_accessible_by(self.superuser))
def handle(self, *args, **kwargs): if len(args) != 2: raise CommandError("Enter action {add|del} and username") action, username = args assert action in ('add', 'del') user = compat.get_user_model().objects.get(**{compat.get_username_field(): username}) forums = Forum.objects.all() for forum in forums: forum.moderators.remove(user) if action == 'add': forum.moderators.add(user)
def post_deleted(instance, **kwargs): Profile = util.get_pybb_profile_model() User = compat.get_user_model() try: profile = util.get_pybb_profile(instance.user) except (Profile.DoesNotExist, User.DoesNotExist) as e: #When we cascade delete an user, profile and posts are also deleted pass else: profile.post_count = instance.user.posts.count() profile.save()
def test_post_in_forum_hidden_is_accessible_by_unauthenticated_user(self): self.forum.hidden = True self.forum.save() with patch.object(get_user_model(), 'is_authenticated') as is_authenticated: is_authenticated.return_value = False self.assertFalse(self.post.is_accessible_by(self.newbie)) self.assertTrue(self.post.is_accessible_by(self.user)) self.assertTrue(self.post.is_accessible_by(self.staff)) self.assertTrue(self.post.is_accessible_by(self.superuser))
def handle(self, *args, **kwargs): if len(args) != 2: raise CommandError("Enter action {add|del} and username") action, username = args assert action in ('add', 'del') user = compat.get_user_model().objects.get( **{compat.get_username_field(): username}) forums = Forum.objects.all() for forum in forums: forum.moderators.remove(user) if action == 'add': forum.moderators.add(user)
def test_post_editable_by_moderator_with_permission(self): self.assertFalse(self.post.is_editable_by(self.newbie)) Moderator.objects.create(forum=self.post.topic.forum, user=self.newbie) self.assertFalse(self.post.is_editable_by(self.newbie, 'can_change_post')) UserObjectPermission.objects.assign_perm('can_change_post', self.newbie, obj=self.post.topic.forum) self.post = Post.objects.get(pk=self.post.pk) with patch.object(get_user_model(), 'is_authenticated', new_callable=PropertyMock, return_value=True): self.assertTrue(self.post.is_editable_by(self.newbie))
def setUp(self): self.ORIG_PYBB_ENABLE_ANONYMOUS_POST = defaults.PYBB_ENABLE_ANONYMOUS_POST self.ORIG_PYBB_ANONYMOUS_USERNAME = defaults.PYBB_ANONYMOUS_USERNAME defaults.PYBB_ENABLE_ANONYMOUS_POST = True defaults.PYBB_ANONYMOUS_USERNAME = '******' self.user = get_user_model().objects.create_user('Anonymous', 'Anonymous@localhost', 'Anonymous') self.parent_forum = Forum.objects.create(name='foo') self.forum = Forum.objects.create(name='xfoo', description='bar', forum=self.parent_forum) self.topic = Topic.objects.create(name='etopic', forum=self.forum, user=self.user) add_post_permission = Permission.objects.get_by_natural_key('add_post', 'pybb', 'post') self.user.user_permissions.add(add_post_permission)
def get_pybb_profile(user): from pybb import defaults if not user.is_authenticated(): if defaults.PYBB_ENABLE_ANONYMOUS_POST: user = get_user_model().objects.get(**{get_username_field(): defaults.PYBB_ANONYMOUS_USERNAME}) else: raise ValueError(_('Can\'t get profile for anonymous user')) if defaults.PYBB_PROFILE_RELATED_NAME: return getattr(user, defaults.PYBB_PROFILE_RELATED_NAME) else: return user
def test_topic_on_moderation(self): self.post self.topic.on_moderation = True self.topic.save() with patch.object(get_user_model(), 'is_authenticated', new_callable=PropertyMock, return_value=True): self.assertTrue(self.post.is_accessible_by(self.user)) self.assertTrue(self.post.is_accessible_by(self.staff)) self.assertTrue(self.post.is_accessible_by(self.superuser)) self.assertFalse(self.post.is_accessible_by(self.newbie)) Moderator.objects.create(forum=self.post.topic.forum, user=self.newbie) self.assertTrue(self.post.is_accessible_by(self.newbie))
def quote(tag_name, value, options, parent, context): if 'quote' not in options: return value splits = options['quote'].split(';') try: username, post_id = splits post_id = int(post_id) except ValueError: if len(splits) == 1: return settings.PYBB_QUOTES_QUOTE_MINIMAL_FORMAT % { 'message': value, 'username': splits[0], } return settings.PYBB_QUOTES_QUOTE_BASIC_FORMAT % { 'message': value, } try: post = Post.objects.get(pk=post_id) user = post.user except (Post.DoesNotExist, get_user_model().DoesNotExist): return settings.PYBB_QUOTES_QUOTE_MINIMAL_FORMAT % { 'message': value, 'username': splits[0], } if 'obj' in context and context['obj']: current_post = context['obj'] if current_post.user: quoted.send(sender=current_post.__class__, user=current_post.user, from_post=current_post, to_post=post) return settings.PYBB_QUOTES_QUOTE_VALID_FORMAT % { 'user_url': settings.PYBB_QUOTES_USER_URL(user), 'message': value, 'username': username, 'post_url': settings.PYBB_QUOTES_POST_URL(post) # anonymous anchor url }
def test_post_editable_by_moderator_with_permission(self): self.assertFalse(self.post.is_editable_by(self.newbie)) Moderator.objects.create(forum=self.post.topic.forum, user=self.newbie) self.assertFalse( self.post.is_editable_by(self.newbie, 'can_change_post')) UserObjectPermission.objects.assign_perm('can_change_post', self.newbie, obj=self.post.topic.forum) self.post = Post.objects.get(pk=self.post.pk) with patch.object(get_user_model(), 'is_authenticated', new_callable=PropertyMock, return_value=True): self.assertTrue(self.post.is_editable_by(self.newbie))
def setUp(self): self.ORIG_PYBB_ENABLE_ANONYMOUS_POST = defaults.PYBB_ENABLE_ANONYMOUS_POST self.ORIG_PYBB_ANONYMOUS_USERNAME = defaults.PYBB_ANONYMOUS_USERNAME defaults.PYBB_ENABLE_ANONYMOUS_POST = True defaults.PYBB_ANONYMOUS_USERNAME = '******' self.user = get_user_model().objects.create_user( 'Anonymous', 'Anonymous@localhost', 'Anonymous') self.parent_forum = Forum.objects.create(name='foo') self.forum = Forum.objects.create(name='xfoo', description='bar', forum=self.parent_forum) self.topic = Topic.objects.create(name='etopic', forum=self.forum, user=self.user) add_post_permission = Permission.objects.get_by_natural_key( 'add_post', 'pybb', 'post') self.user.user_permissions.add(add_post_permission)
def test_subscription(self): user = get_user_model().objects.create_user(username='******', password='******', email='*****@*****.**') client = Client() client.login(username='******', password='******') response = client.post(reverse('pybb:subscription_create'), data={ 'topic_id': self.topic.pk, 'type': Subscription.TYPE_INSTANT_ALERT }) self.assertEqual(response.status_code, 302) self.assertRedirects(response, self.topic.get_absolute_url()) self.assertTrue(user in list(self.topic.subscribers.all())) new_post = Post(topic=self.topic, user=self.user, body='test subscribtion юникод') new_post.save() self.assertTrue([msg for msg in mail.outbox if new_post.get_absolute_url() in msg.body]) response = client.post(reverse('pybb:subscription_delete'), data={ 'topic_id': self.topic.pk }) self.assertEqual(response.status_code, 302) self.assertRedirects(response, self.topic.get_absolute_url()) self.assertTrue(user not in list(self.topic.subscribers.all()))
class MentionProcessor(BaseProcessor): username_re = r'@([\w\-]+)' format = '@%(username)s' tag = '[mention=%(user_id)s]%(username)s[/mention]' model = get_user_model() def get_user_url(self, user): return settings.PYBB_MENTIONS_USER_URL(user) def get_users(self, username_list): return self.model.objects.filter( username__in=username_list).values_list('username', 'id') def _format(self, user, body): username, user_id = user format = self.format % {'username': username} body = body.replace( format, self.tag % { 'user_id': user_id, 'username': username }) return body def render(self): body = self.body username_list = [ m.group(1) for m in re.finditer(self.username_re, body, re.MULTILINE) ] users = self.get_users(username_list) for user in users: body = self._format(user, body) return body
class AdminPostForm(PostForm): """ Superusers can post messages from any user and from any time If no user with specified name - new user will be created """ login = forms.ModelChoiceField(label=_('User'), queryset=get_user_model().objects.all()) def __init__(self, *args, **kwargs): if args: kwargs.update( dict( zip( inspect.getargspec(forms.ModelForm.__init__)[0][1:], args))) super(AdminPostForm, self).__init__(**kwargs) def save(self, *args, **kwargs): self.user = self.cleaned_data['login'] return super(AdminPostForm, self).save(*args, **kwargs)
def mention(tag_name, value, options, parent, context): User = get_user_model() if 'mention' not in options: return settings.PYBB_MENTIONS_MENTION_FORMAT_WITHOUT_USER % { 'username': value } user_id = options['mention'] try: user = User.objects.get(pk=user_id) except (User.DoesNotExist, ValueError): return settings.PYBB_MENTIONS_MENTION_FORMAT_WITHOUT_USER % { 'username': value } else: if 'obj' in context and context['obj'] and context['obj'].user: mentioned.send(sender=User, user=user, post=context['obj']) return settings.PYBB_MENTIONS_MENTION_FORMAT_WITH_USER % { 'user_url': settings.PYBB_MENTIONS_USER_URL(user), 'username': value }
def get_user(self, username): return get_user_model().objects.get(username=username)
def get_queryset(self): return get_user_model().objects.all()
from __future__ import unicode_literals import re import inspect from django import forms from django.core.exceptions import FieldError from django.forms.models import inlineformset_factory, BaseInlineFormSet from django.utils.translation import ugettext, ugettext_lazy from django.utils.timezone import now as tznow from pybb import compat, defaults, util from pybb.models import Topic, Post, Attachment, PollAnswer User = compat.get_user_model() username_field = compat.get_username_field() class AttachmentForm(forms.ModelForm): class Meta(object): model = Attachment fields = ('file', ) def clean_file(self): if self.cleaned_data['file'].size > defaults.PYBB_ATTACHMENT_SIZE_LIMIT: raise forms.ValidationError(ugettext('Attachment is too big')) return self.cleaned_data['file'] AttachmentFormSet = inlineformset_factory(Post, Attachment, extra=1, form=AttachmentForm)
try: add_post_permission = Permission.objects.get_by_natural_key('add_post', 'pybb', 'post') add_topic_permission = Permission.objects.get_by_natural_key('add_topic', 'pybb', 'topic') except ObjectDoesNotExist: return instance.user_permissions.add(add_post_permission, add_topic_permission) instance.save() get_profile(instance) def get_profile(user): try: return user.pybb_profile except ObjectDoesNotExist: return Profile(user=user).save() if django.VERSION < (1, 7): from pybb.compat import get_user_model post_save.connect(user_saved, sender=get_user_model()) else: from django.apps import apps if apps.ready: from pybb.compat import get_user_model post_save.connect(user_saved, sender=get_user_model())
def test_read_tracking_multi_user(self): self.post topic_1 = self.topic topic_2 = Topic(name='topic_2', forum=self.forum, user=self.user) topic_2.save() Post(topic=topic_2, user=self.user, body='one').save() user_ann = get_user_model().objects.create_user('ann', 'ann@localhost', 'ann') client_ann = Client() client_ann.login(username='******', password='******') user_bob = get_user_model().objects.create_user('bob', 'bob@localhost', 'bob') client_bob = Client() client_bob.login(username='******', password='******') # Two topics, each with one post. everything is unread, so the db should reflect that: self.assertEqual(TopicReadTracker.objects.all().count(), 0) self.assertEqual(ForumReadTracker.objects.all().count(), 0) # user_ann reads topic_1, she should get one topic read tracker, there should be no forum read trackers client_ann.get(topic_1.get_absolute_url()) self.assertEqual(TopicReadTracker.objects.all().count(), 1) self.assertEqual(TopicReadTracker.objects.filter(user=user_ann).count(), 1) self.assertEqual(TopicReadTracker.objects.filter(user=user_ann, topic=topic_1).count(), 1) self.assertEqual(ForumReadTracker.objects.all().count(), 0) # user_bob reads topic_1, he should get one topic read tracker, there should be no forum read trackers client_bob.get(topic_1.get_absolute_url()) self.assertEqual(TopicReadTracker.objects.all().count(), 2) self.assertEqual(TopicReadTracker.objects.filter(user=user_bob).count(), 1) self.assertEqual(TopicReadTracker.objects.filter(user=user_bob, topic=topic_1).count(), 1) self.assertEqual(ForumReadTracker.objects.all().count(), 0) # user_bob reads topic_2, he should get a forum read tracker, # there should be no topic read trackers for user_bob client_bob.get(topic_2.get_absolute_url()) self.assertEqual(TopicReadTracker.objects.all().count(), 1) self.assertEqual(ForumReadTracker.objects.all().count(), 1) self.assertEqual(ForumReadTracker.objects.filter(user=user_bob).count(), 1) self.assertEqual(ForumReadTracker.objects.filter(user=user_bob, forum=self.forum).count(), 1) # user_ann creates topic_3, there should be a new topic read tracker in the db topic_create_url = reverse('pybb:topic_create', kwargs={'forum_id': self.forum.id}) response = client_ann.get(topic_create_url) values = self.get_form_values(response) values['body'] = 'topic_3' values['name'] = 'topic_3' values['poll_type'] = 0 response = client_ann.post(topic_create_url, data=values, follow=True) self.assertEqual(TopicReadTracker.objects.all().count(), 2) self.assertEqual(TopicReadTracker.objects.filter(user=user_ann).count(), 2) self.assertEqual(ForumReadTracker.objects.all().count(), 1) topic_3 = Topic.objects.order_by('-updated')[0] self.assertEqual(topic_3.name, 'topic_3') # user_ann posts to topic_1, a topic they've already read, no new trackers should be created (existing one is updated) post_create_url = reverse('pybb:post_create', kwargs={'topic_id': topic_1.id}) response = client_ann.get(post_create_url) values = self.get_form_values(response) values['body'] = 'test tracking' response = client_ann.post(post_create_url, values, follow=True) self.assertEqual(TopicReadTracker.objects.all().count(), 2) self.assertEqual(TopicReadTracker.objects.filter(user=user_ann).count(), 2) self.assertEqual(ForumReadTracker.objects.all().count(), 1) self.assertEqual(ForumReadTracker.objects.all().count(), 1) previous_time = ForumReadTracker.objects.all()[0].time_stamp # user bob reads topic 1 which he already read, topic tracker recreated, forum tracker untouched (topic 3 still unread) client_bob.get(topic_1.get_absolute_url()) self.assertEqual(ForumReadTracker.objects.all().count(), 1) self.assertEqual(ForumReadTracker.objects.all()[0].time_stamp, previous_time) self.assertEqual(TopicReadTracker.objects.all().count(), 3) self.assertEqual(TopicReadTracker.objects.filter(user=user_bob).count(), 1) self.assertEqual(ForumReadTracker.objects.all().count(), 1) previous_time = ForumReadTracker.objects.all()[0].time_stamp # user bob reads topic 3, topic tracker purged, forum tracker updated client_bob.get(topic_3.get_absolute_url()) self.assertEqual(ForumReadTracker.objects.all().count(), 1) self.assertGreater(ForumReadTracker.objects.all()[0].time_stamp, previous_time) self.assertEqual(TopicReadTracker.objects.all().count(), 2) self.assertEqual(TopicReadTracker.objects.filter(user=user_bob).count(), 0)
def newbie(self): return get_user_model().objects.create_user('newbie', 'newbie@localhost', 'newbie')
def staff(self): staff = get_user_model().objects.create_user('thoas', 'thoas@localhost', '$ecret') staff.is_staff = True staff.save() return staff
def user(self): return get_user_model().objects.create_user('zeus', 'zeus@localhost', 'zeus')
def setup(): post_save.connect(post_saved, sender=Post) post_delete.connect(post_deleted, sender=Post) if defaults.PYBB_AUTO_USER_PERMISSIONS: post_save.connect(user_saved, sender=compat.get_user_model())