def activate(request, username="", user="******", token=""): user = int(user) try: user = User.objects.get(pk=user) current_activation = user.activation # Run checks user_ban = Ban.objects.check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) if user.activation == User.ACTIVATION_NONE: return redirect_message(request, Message(_("%(username)s, your account is already active.") % {'username': user.username}), 'info') if user.activation == User.ACTIVATION_ADMIN: return redirect_message(request, Message(_("%(username)s, only board administrator can activate your account.") % {'username': user.username}), 'info') if not token or not user.token or user.token != token: return redirect_message(request, Message(_("%(username)s, your activation link is invalid. Try again or request new activation e-mail.") % {'username': user.username}), 'error') # Activate and sign in our member user.activation = User.ACTIVATION_NONE sign_user_in(request, user) # Update monitor User.objects.resync_monitor(request.monitor) if current_activation == User.ACTIVATION_CREDENTIALS: return redirect_message(request, Message(_("%(username)s, your account has been successfully reactivated after change of sign-in credentials.") % {'username': user.username}), 'success') else: return redirect_message(request, Message(_("%(username)s, your account has been successfully activated. Welcome aboard!") % {'username': user.username}), 'success') except User.DoesNotExist: return error404(request)
def __call__(self, request, target=None, slug=None): # Default message message = request.messages.get_message(self.admin.id) # Fetch target? model = None if target: model = self.get_and_validate_target(request, target) self.original_name = self.get_target_name(model) if not model: return redirect(self.get_fallback_url(request)) original_model = model # Get form type to instantiate FormType = self.get_form(request, target) #Submit form if request.method == 'POST': form = self.get_form_instance(FormType, request, model, self.get_initial_data(request, model), True) if form.is_valid(): model, message = self.submit_form(request, form, model) if message.type != 'error': request.messages.set_flash(message, message.type, self.admin.id) # Redirect back to right page try: if 'save_new' in request.POST and self.get_new_url: return redirect(self.get_new_url(request, model)) except AttributeError: pass try: if 'save_edit' in request.POST and self.get_edit_url: return redirect(self.get_edit_url(request, model)) except AttributeError: pass try: if self.get_submit_url: return redirect(self.get_submit_url(request, model)) except AttributeError: pass return redirect(self.get_fallback_url(request)) else: message = Message(request, form.non_field_errors()[0]) message.type = 'error' else: form = self.get_form_instance(FormType, request, model, self.get_initial_data(request, model)) # Render form return request.theme.render_to_response(self.get_templates(self.template), { 'admin': self.admin, 'action': self, 'request': request, 'url': self.get_url(request, model), 'fallback': self.get_fallback_url(request), 'message': message, 'target': self.get_target_name(original_model), 'target_model': original_model, 'form': FormLayout(form, self.get_layout(request, form, target)), }, context_instance=RequestContext(request));
def activate(request, token): new_credentials = request.session.get('new_credentials') if not new_credentials or new_credentials['token'] != token: return error404(request) if new_credentials['new_email']: request.user.set_email(new_credentials['new_email']) if new_credentials['new_password']: request.user.set_password(new_credentials['new_password']) try: request.user.full_clean() request.user.save(force_update=True) request.user.sessions.exclude(id=request.session.id).delete() request.user.signin_tokens.all().delete() request.messages.set_flash( Message( _("%(username)s, your Sign-In credentials have been changed.") % {'username': request.user.username}), 'success', 'security') request.session.sign_out(request) del request.session['new_credentials'] return redirect(reverse('sign_in')) except ValidationError: request.messages.set_flash( Message( _("Your new credentials have been invalidated. Please try again." )), 'error', 'usercp_credentials') return redirect(reverse('usercp_credentials'))
def form(request): message = None if request.method == 'POST': form = UserSendActivationMailForm(request.POST, request=request) if form.is_valid(): user = form.found_user user_ban = Ban.objects.check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) if user.activation == User.ACTIVATION_NONE: return redirect_message(request, Message(_("%(username)s, your account is already active.") % {'username': user.username}), 'info') if user.activation == User.ACTIVATION_ADMIN: return redirect_message(request, Message(_("%(username)s, only board administrator can activate your account.") % {'username': user.username}), 'info') user.email_user( request, 'users/activation/resend', _("Account Activation"), ) return redirect_message(request, Message(_("%(username)s, e-mail containing new activation link has been sent to %(email)s.") % {'username': user.username, 'email': user.email}), 'success') else: message = Message(form.non_field_errors()[0], 'error') else: form = UserSendActivationMailForm(request=request) return request.theme.render_to_response('resend_activation.html', { 'message': message, 'form': FormLayout(form), }, context_instance=RequestContext(request));
def handle_posts_form(self): if self.request.method == 'POST' and self.request.POST.get('origin') == 'posts_form': self.posts_form = self.posts_form(self.request.POST, request=self.request) if self.posts_form.is_valid(): checked_items = [] for post in self.posts: if str(post.pk) in self.posts_form.cleaned_data['list_items']: checked_items.append(post.pk) if checked_items: form_action = getattr(self, 'post_action_' + self.posts_form.cleaned_data['list_action']) try: response = form_action(checked_items) if response: return response return redirect(self.request.path) except forms.ValidationError as e: self.message = Message(e.messages[0], messages.ERROR) else: self.message = Message(_("You have to select at least one post."), messages.ERROR) else: if 'list_action' in self.posts_form.errors: self.message = Message(_("Requested action is incorrect."), messages.ERROR) else: self.message = Message(posts_form.non_field_errors()[0], messages.ERROR) else: self.posts_form = self.posts_form(request=self.request)
def crop(request, upload=False): if upload and (not request.user.avatar_temp or not 'upload' in settings.avatars_types): return error404(request) if not upload and request.user.avatar_type != 'upload': messages.error(request, _("Crop Avatar option is avaiable only when you use uploaded image as your avatar."), 'usercp_avatar') return redirect(reverse('usercp_avatar')) message = request.messages.get_message('usercp_avatar') if request.method == 'POST': if request.csrf.request_secure(request): try: image_path = settings.MEDIA_ROOT + 'avatars/' if upload: source = Image.open(image_path + request.user.avatar_temp) else: source = Image.open(image_path + request.user.avatar_original) width, height = source.size aspect = float(width) / float(request.POST['crop_b']) crop_x = int(aspect * float(request.POST['crop_x'])) crop_y = int(aspect * float(request.POST['crop_y'])) crop_w = int(aspect * float(request.POST['crop_w'])) crop = source.crop((crop_x, crop_y, crop_x + crop_w, crop_y + crop_w)) if upload: image_name, image_extension = path(request.user.avatar_temp).splitext() else: image_name, image_extension = path(request.user.avatar_original).splitext() image_name = '%s_%s%s' % (request.user.pk, random_string(8), image_extension) resizeimage(crop, settings.AVATAR_SIZES[0], image_path + image_name, info=source.info, format=source.format) for size in settings.AVATAR_SIZES[1:]: resizeimage(crop, size, image_path + str(size) + '_' + image_name, info=source.info, format=source.format) request.user.delete_avatar_image() if upload: request.user.delete_avatar_original() request.user.avatar_type = 'upload' request.user.avatar_original = '%s_org_%s%s' % (request.user.pk, random_string(8), image_extension) source.save(image_path + request.user.avatar_original) request.user.delete_avatar_temp() request.user.avatar_image = image_name request.user.avatar_crop = [str(float(request.POST[x])) for x in ('crop_x', 'crop_y', 'crop_w')] request.user.save(force_update=True) messages.success(request, _("Your avatar has been cropped."), 'usercp_avatar') return redirect(reverse('usercp_avatar')) except Exception: message = Message(_("Form contains errors."), messages.ERROR) else: message = Message(_("Request authorisation is invalid."), messages.ERROR) return render_to_response('usercp/avatar_crop.html', context_instance=RequestContext(request, { 'message': message, 'after_upload': upload, 'avatar_size': settings.AVATAR_SIZES[0], 'avatar_crop': request.user.avatar_crop if not upload else None, 'source': 'avatars/%s' % (request.user.avatar_temp if upload else request.user.avatar_original), 'tab': 'avatar'}));
def reset(request, username="", user="******", token=""): user = int(user) try: user = User.objects.get(pk=user) user_ban = check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) if user.activation != User.ACTIVATION_NONE: return error403( request, Message(request, 'users/activation/required', {'user': user})) if not token or not user.token or user.token != token: return error403( request, Message(request, 'users/invalid_confirmation_link', {'user': user})) new_password = get_random_string(6) user.token = None user.set_password(new_password) user.save(force_update=True) # Logout signed in and kill remember me tokens Session.objects.filter(user=user).update(user=None) Token.objects.filter(user=user).delete() # Set flash and mail new password request.messages.set_flash( Message(request, 'users/password/reset_done', extra={'user': user}), 'success') user.email_user(request, 'users/password/new', _("Your New Password"), {'password': new_password}) return redirect(reverse('sign_in')) except User.DoesNotExist: return error404(request)
def form(request): message = None if request.method == 'POST': form = UserSendSpecialMailForm(request.POST, request=request) if form.is_valid(): user = form.found_user user_ban = check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) elif user.activation != User.ACTIVATION_NONE: return error403( request, Message(request, 'users/activation/required', {'user': user})) user.token = get_random_string(12) user.save(force_update=True) request.messages.set_flash( Message(request, 'users/password/reset_confirm', extra={'user': user}), 'success') user.email_user(request, 'users/password/confirm', _("Confirm New Password Request")) return redirect(reverse('index')) else: message = Message(request, form.non_field_errors()[0]) else: form = UserSendSpecialMailForm(request=request) return request.theme.render_to_response( 'users/forgot_password.html', { 'message': message, 'form': FormLayout(form), }, context_instance=RequestContext(request))
def signature(request): # Intercept all requests if we can't use signature if not request.acl.usercp.can_use_signature(): return error403(request) if request.user.signature_ban: return request.theme.render_to_response('usercp/signature_banned.html', context_instance=RequestContext(request, { 'tab': 'signature', })); siggy_text = '' message = request.messages.get_message('usercp_signature') if request.method == 'POST': form = SignatureForm(request.POST, request=request, initial={'signature': request.user.signature}) if form.is_valid(): request.user.signature = form.cleaned_data['signature'] if request.user.signature: request.user.signature_preparsed = signature_markdown(request.acl, request.user.signature) else: request.user.signature_preparsed = None request.user.save(force_update=True) request.messages.set_flash(Message(_("Your signature has been changed.")), 'success', 'usercp_signature') return redirect(reverse('usercp_signature')) else: message = Message(form.non_field_errors()[0], 'error') else: form = SignatureForm(request=request, initial={'signature': request.user.signature}) return request.theme.render_to_response('usercp/signature.html', context_instance=RequestContext(request, { 'message': message, 'tab': 'signature', 'form': FormLayout(form), }));
def thread_action_move(self): message = None if self.request.POST.get('do') == 'move': form = MoveThreadsForm(self.request.POST, request=self.request, forum=self.forum) if form.is_valid(): new_forum = form.cleaned_data['new_forum'] self.thread.move_to(new_forum) self.thread.save(force_update=True) self.thread.set_checkpoint(self.request, 'moved', forum=self.forum) self.forum.sync() self.forum.save(force_update=True) new_forum.sync() new_forum.save(force_update=True) self.request.messages.set_flash( Message( _('Thread has been moved to "%(forum)s".') % {'forum': new_forum.name}), 'success', 'threads') return None message = Message(form.non_field_errors()[0], 'error') else: form = MoveThreadsForm(request=self.request, forum=self.forum) return self.request.theme.render_to_response( '%ss/move_thread.html' % self.type_prefix, { 'type_prefix': self.type_prefix, 'message': message, 'forum': self.forum, 'parents': self.parents, 'thread': self.thread, 'form': FormLayout(form), }, context_instance=RequestContext(self.request))
def settings(request, group_id=None, group_slug=None): # Load groups and find selected group settings_groups = Group.objects.all().order_by('key') if not group_id: active_group = settings_groups[0] group_id = active_group.pk else: group_id = int(group_id) for group in settings_groups: if group.pk == group_id: active_group = group break else: return error404(request, BasicMessage(_('The requested settings group could not be found.'))) # Load selected group settings and turn them into form group_settings = Setting.objects.filter(group=active_group).order_by('position') last_fieldset = (None, []) group_form = {'layout': []} for setting in group_settings: # New field subgroup? if setting.separator and last_fieldset[0] != setting.separator: if last_fieldset[0]: group_form['layout'].append(last_fieldset) last_fieldset = (_(setting.separator), []) last_fieldset[1].append(setting.pk) group_form[setting.pk] = setting.get_field() group_form['layout'].append(last_fieldset) SettingsGroupForm = type('SettingsGroupForm', (Form,), group_form) #Submit form message = request.messages.get_message('admin_settings') if request.method == 'POST': form = SettingsGroupForm(request.POST, request=request) if form.is_valid(): for setting in form.cleaned_data.keys(): request.settings[setting] = form.cleaned_data[setting] request.messages.set_flash(BasicMessage(_('Configuration has been saved.')), 'success', 'admin_settings') return redirect(reverse('admin_settings', kwargs={ 'group_id': active_group.pk, 'group_slug': active_group.key, })) else: message = Message(request, form.non_field_errors()[0]) message.type = 'error' else: form = SettingsGroupForm(request=request) # Display settings group form return request.theme.render_to_response('settings/settings.html', { 'message': message, 'groups': settings_groups, 'active_group': active_group, 'search_form': FormFields(SearchForm(request=request)), 'form': FormLayout(form), 'raw_form': form, }, context_instance=RequestContext(request));
def settings(request, group_id=None, group_slug=None): # Load groups and find selected group settings_groups = SettingsGroup.objects.all().order_by('key') if not group_id: active_group = settings_groups[0] group_id = active_group.pk else: group_id = int(group_id) for group in settings_groups: if group.pk == group_id: active_group = group break else: return error404(request, _('Requested settings group could not be found.')) # Load selected group settings and turn them into form group_settings = Setting.objects.filter(group=active_group).order_by('position') last_fieldset = (None, []) group_form = {'layout': []} for setting in group_settings: # New field subgroup? if setting.separator and last_fieldset[0] != setting.separator: if last_fieldset[0]: group_form['layout'].append(last_fieldset) last_fieldset = (_(setting.separator), []) last_fieldset[1].append(setting.pk) group_form[setting.pk] = setting.get_field() group_form['layout'].append(last_fieldset) SettingsGroupForm = type('SettingsGroupForm', (Form,), group_form) #Submit form message = request.messages.get_message('admin_settings') if request.method == 'POST': form = SettingsGroupForm(request.POST, request=request) if form.is_valid(): for setting in form.cleaned_data.keys(): request.settings[setting] = form.cleaned_data[setting] cache.delete('settings') request.messages.set_flash(Message(_('Configuration has been changed.')), 'success', 'admin_settings') return redirect(reverse('admin_settings', kwargs={ 'group_id': active_group.pk, 'group_slug': active_group.key, })) else: message = Message(form.non_field_errors()[0], 'error') else: form = SettingsGroupForm(request=request) # Display settings group form return request.theme.render_to_response('settings/settings.html', { 'message': message, 'groups': settings_groups, 'active_group': active_group, 'search_form': FormFields(SearchForm(request=request)), 'form': FormLayout(form), 'raw_form': form, }, context_instance=RequestContext(request));
def action_undelete(self, ids): if self._action_undelete(ids): self.request.messages.set_flash( Message(_('Selected reports have been restored.')), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No reports were restored.')), 'info', 'threads')
def action_soft(self, ids): if self._action_soft(ids): self.request.messages.set_flash( Message(_('Selected threads have been hidden.')), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No threads were hidden.')), 'info', 'threads')
def action_hard(self, ids): if self._action_hard(ids): self.request.messages.set_flash( Message(_('Selected threads have been deleted.')), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No threads were deleted.')), 'info', 'threads')
def action_normal(self, ids): if self._action_normal(ids): self.mass_resolve(ids) self.request.messages.set_flash( Message(_('Selected reports were set as bogus.')), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No reports were set as bogus.')), 'info', 'threads')
def action_normal(self, ids): if self._action_normal(ids): self.request.messages.set_flash( Message(_('Selected threads weight has been removed.')), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No threads have had their weight removed.')), 'info', 'threads')
def handle_form(self): if self.request.method == 'POST': self.form = self.form(self.request.POST, request=self.request) if self.form.is_valid(): checked_items = [] posts = [] for thread in self.threads: if str(thread.pk) in self.form.cleaned_data[ 'list_items'] and thread.forum_id == self.forum.pk: posts.append(thread.start_post_id) if thread.start_post_id != thread.last_post_id: posts.append(thread.last_post_id) checked_items.append(thread.pk) if checked_items: if posts: for post in Post.objects.filter( id__in=posts).prefetch_related('user'): for thread in self.threads: if thread.start_post_id == post.pk: thread.start_post = post if thread.last_post_id == post.pk: thread.last_post = post if thread.start_post_id == post.pk or thread.last_post_id == post.pk: break action_call = 'action_' + self.form.cleaned_data[ 'list_action'] action_extra_args = [] if ':' in action_call: action_extra_args = action_call[action_call.index(':' ) + 1:].split(',') action_call = action_call[:action_call.index(':')] form_action = getattr(self, action_call) try: response = form_action(checked_items, *action_extra_args) if response: return response return redirect(self.request.path) except forms.ValidationError as e: self.message = Message(e.messages[0], messages.ERROR) else: self.message = Message( _("You have to select at least one thread."), messages.ERROR) else: if 'list_action' in self.form.errors: self.message = Message(_("Requested action is incorrect."), messages.ERROR) else: self.message = Message(self.form.non_field_errors()[0], messages.ERROR) else: self.form = self.form(request=self.request)
def action_sticky(self, ids): if self._action_sticky(ids): self.request.messages.set_flash( Message( _('Selected threads have been sticked to the top of list.') ), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No threads were turned into stickies.')), 'info', 'threads')
def action_accept(self, ids): if self._action_accept(ids): self.request.messages.set_flash( Message( _('Selected threads have been marked as reviewed and made visible to other members.' )), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No threads were marked as reviewed.')), 'info', 'threads')
def action_annouce(self, ids): if self._action_annouce(ids): self.request.messages.set_flash( Message( _('Selected threads have been turned into announcements.') ), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No threads were turned into announcements.')), 'info', 'threads')
def username(request): if not request.acl.usercp.show_username_change(): return error404(request) changes_left = request.acl.usercp.changes_left(request.user) next_change = None if request.acl.usercp.changes_expire() and not changes_left: next_change = request.user.namechanges.filter( date__gte=timezone.now() - timedelta(days=request.acl.usercp.acl['changes_expire']), ).order_by('-date')[0] next_change = next_change.date + timedelta(days=request.acl.usercp.acl['changes_expire']) message = request.messages.get_message('usercp_username') if request.method == 'POST': if not changes_left: message = Message(_("You have exceeded the maximum number of name changes."), messages.ERROR) form = UsernameChangeForm(request=request) else: org_username = request.user.username form = UsernameChangeForm(request.POST, request=request) if form.is_valid(): request.user.set_username(form.cleaned_data['username']) request.user.save(force_update=True) request.user.sync_username() request.user.namechanges.create(date=timezone.now(), old_username=org_username) messages.success(request, _("Your username has been changed."), 'usercp_username') # Alert followers of namechange alert_time = timezone.now() bulk_alerts = [] alerted_users = [] for follower in request.user.follows_set.iterator(): alerted_users.append(follower.pk) alert = Alert(user=follower, message=ugettext_lazy("User that you are following, %(username)s, has changed his name to %(newname)s").message, date=alert_time) alert.strong('username', org_username) alert.profile('newname', request.user) alert.hydrate() bulk_alerts.append(alert) if bulk_alerts: Alert.objects.bulk_create(bulk_alerts) User.objects.filter(id__in=alerted_users).update(alerts=F('alerts') + 1) # Hop back return redirect(reverse('usercp_username')) message = Message(form.non_field_errors()[0], messages.ERROR) else: form = UsernameChangeForm(request=request) return render_to_response('usercp/username.html', context_instance=RequestContext(request, { 'message': message, 'changes_left': changes_left, 'form': form, 'next_change': next_change, 'changes_history': request.user.namechanges.order_by('-date')[:10], 'tab': 'username'}));
def response(self): if self.post.moderated: self.request.messages.set_flash( Message( _("Your reply has been posted. It will be hidden from other members until moderator reviews it." )), 'success', 'threads_%s' % self.post.pk) else: self.request.messages.set_flash( Message(_("Your reply has been posted.")), 'success', 'threads_%s' % self.post.pk) return self.redirect_to_post(self.post)
def get_and_validate_target(self, target): try: model = self.admin.model.objects.select_related().get(pk=target) self.get_target(model) return model except self.admin.model.DoesNotExist: self.request.messages.set_flash(Message(self.notfound_message), 'error', self.admin.id) except ValueError as e: self.request.messages.set_flash(Message(e.args[0]), 'error', self.admin.id) return None
def action(self, target): target.delete() with UpdatingMonitor() as cm: monitor.increase('bans_version') if target.test == 0: return Message(_('E-mail and username Ban "%(ban)s" has been lifted.') % {'ban': target.ban}, messages.SUCCESS), False if target.test == 1: return Message(_('Username Ban "%(ban)s" has been lifted.') % {'ban': target.ban}, messages.SUCCESS), False if target.test == 2: return Message(_('E-mail Ban "%(ban)s" has been lifted.') % {'ban': target.ban}, messages.SUCCESS), False if target.test == 3: return Message(_('IP Ban "%(ban)s" has been lifted.') % {'ban': target.ban}, messages.SUCCESS), False
def gravatar(request): if not 'gravatar' in request.settings.avatars_types: return error404(request) if request.user.avatar_type != 'gravatar': if request.csrf.request_secure(request): request.user.delete_avatar() request.user.avatar_type = 'gravatar' request.user.save(force_update=True) request.messages.set_flash(Message(_("Your avatar has been changed to Gravatar.")), 'success', 'usercp_avatar') else: request.messages.set_flash(Message(_("Request authorisation is invalid.")), 'error', 'usercp_avatar') return redirect(reverse('usercp_avatar'))
def update_watcher(self, request, watcher): watcher.email = True if watcher.pk: request.messages.set_flash( Message( _('You will now receive e-mail with notification when somebody replies to this thread.' )), 'success', 'threads') else: request.messages.set_flash( Message( _('This thread has been added to your watched threads list. You will also receive e-mail with notification when somebody replies to it.' )), 'success', 'threads')
def gallery(request): if not 'gallery' in settings.avatars_types: return error404(request) allowed_avatars = [] galleries = [] for directory in path( settings.STATICFILES_DIRS[0]).joinpath('avatars').dirs(): if directory[-7:] != '_locked' and directory[-8:] != '_default': gallery = {'name': directory[-7:], 'avatars': []} avatars = directory.files('*.gif') avatars += directory.files('*.jpg') avatars += directory.files('*.jpeg') avatars += directory.files('*.png') for item in avatars: gallery['avatars'].append('/'.join(path(item).splitall()[-2:])) galleries.append(gallery) allowed_avatars += gallery['avatars'] if not allowed_avatars: messages.info(request, _("No avatar galleries are available at the moment."), 'usercp_avatar') return redirect(reverse('usercp_avatar')) message = request.messages.get_message('usercp_avatar') if request.method == 'POST': if request.csrf.request_secure(request): new_avatar = request.POST.get('avatar_image') if new_avatar in allowed_avatars: request.user.delete_avatar() request.user.avatar_type = 'gallery' request.user.avatar_image = new_avatar request.user.save(force_update=True) messages.success( request, _("Your avatar has been changed to one from gallery."), 'usercp_avatar') return redirect(reverse('usercp_avatar')) message = Message(_("Selected Avatar is incorrect."), messages.ERROR) else: message = Message(_("Request authorisation is invalid."), messages.ERROR) return render_to_response('usercp/avatar_gallery.html', context_instance=RequestContext( request, { 'message': message, 'galleries': galleries, 'tab': 'avatar' }))
def update_watcher(self, request, watcher): watcher.deleted = True watcher.delete() if watcher.email: request.messages.set_flash( Message( _('This thread has been removed from your watched threads list. You will no longer receive e-mails with notifications when somebody replies to it.' )), 'success', 'threads') else: request.messages.set_flash( Message( _('This thread has been removed from your watched threads list.' )), 'success', 'threads')
def post_action_protect(self, ids): protected = 0 for post in self.posts: if post.pk in ids and not post.protected: protected += 1 if protected: self.thread.post_set.filter(id__in=ids).update(protected=True) self.request.messages.set_flash( Message(_('Selected posts have been protected from edition.')), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No posts were protected.')), 'info', 'threads')
def post_action_unprotect(self, ids): unprotected = 0 for post in self.posts: if post.pk in ids and post.protected: unprotected += 1 if unprotected: self.thread.post_set.filter(id__in=ids).update(protected=False) self.request.messages.set_flash( Message( _('Protection from editions has been removed from selected posts.' )), 'success', 'threads') else: self.request.messages.set_flash( Message(_('No posts were unprotected.')), 'info', 'threads')
def __call__(self, request, page=0): """ Use widget as view """ self.request = request # Get basic list items items_total = self.get_items() # Set extra filters? try: items_total = self.select_items(items_total).count() except AttributeError: items_total = items_total.count() # Set sorting and paginating sorting_method = self.get_sorting() paginating_method = self.get_pagination(items_total, page) # List items items = self.get_items() if not request.session.get(self.get_token('filter')): items = items.all() # Set extra filters? try: items = self.select_items(items) except AttributeError: pass # Sort them items = self.sort_items(items, sorting_method); # Set pagination if self.pagination: items = items[paginating_method['start']:paginating_method['stop']] # Prefetch related? try: items = self.prefetch_related(items) except AttributeError: pass # Default message message = None # See if we should make and handle search form search_form = None SearchForm = self.get_search_form() if SearchForm: if request.method == 'POST': # New search if request.POST.get('origin') == 'search': search_form = SearchForm(request.POST, request=request) if search_form.is_valid(): search_criteria = {} for field, criteria in search_form.cleaned_data.items(): if len(criteria) > 0: search_criteria[field] = criteria if not search_criteria: message = Message(_("No search criteria have been defined.")) else: request.session[self.get_token('filter')] = search_criteria return redirect(self.get_url()) else: message = Message(_("Search form contains errors.")) message.type = 'error' else: search_form = SearchForm(request=request) # Kill search if request.POST.get('origin') == 'clear' and self.is_filtering and request.csrf.request_secure(request): request.session[self.get_token('filter')] = None request.messages.set_flash(Message(_("Search criteria have been cleared.")), 'info', self.admin.id) return redirect(self.get_url()) else: if self.is_filtering: search_form = SearchForm(request=request, initial=request.session.get(self.get_token('filter'))) else: search_form = SearchForm(request=request) # See if we sould make and handle tab form table_form = None TableForm = self.get_table_form(items) if TableForm: if request.method == 'POST' and request.POST.get('origin') == 'table': table_form = TableForm(request.POST, request=request) if table_form.is_valid(): message, redirect_url = self.table_action(items, table_form.cleaned_data) if redirect_url: request.messages.set_flash(message, message.type, self.admin.id) return redirect(redirect_url) else: message = Message(table_form.non_field_errors()[0], 'error') else: table_form = TableForm(request=request) # See if we should make and handle list form list_form = None ListForm = self.get_actions_form(items) if ListForm: if request.method == 'POST' and request.POST.get('origin') == 'list': list_form = ListForm(request.POST, request=request) if list_form.is_valid(): try: form_action = getattr(self, 'action_' + list_form.cleaned_data['list_action']) message, redirect_url = form_action(items, list_form.cleaned_data['list_items']) if redirect_url: request.messages.set_flash(message, message.type, self.admin.id) return redirect(redirect_url) except AttributeError: message = Message(_("Action requested is incorrect.")) else: if 'list_items' in list_form.errors: message = Message(self.nothing_checked_message) elif 'list_action' in list_form.errors: message = Message(_("Action requested is incorrect.")) else: message = Message(list_form.non_field_errors()[0]) message.type = 'error' else: list_form = ListForm(request=request) # Little hax to keep counters correct items_shown = len(items) if items_total < items_shown: items_total = items_shown # Render list return request.theme.render_to_response(self.get_template(), self.add_template_variables({ 'admin': self.admin, 'action': self, 'request': request, 'url': self.get_url(), 'messages_log': request.messages.get_messages(self.admin.id), 'message': message, 'sorting': self.sortables, 'sorting_method': sorting_method, 'pagination': paginating_method, 'list_form': FormLayout(list_form) if list_form else None, 'search_form': FormLayout(search_form) if search_form else None, 'table_form': FormFields(table_form).fields if table_form else None, 'items': items, 'items_total': items_total, 'items_shown': items_shown, }), context_instance=RequestContext(request));
def __call__(self, request, page=0): """ Use widget as view """ self.request = request # Get basic list items items_total = self.get_items() # Set extra filters? try: items_total = self.select_items(items_total).count() except AttributeError: items_total = items_total.count() # Set sorting and paginating sorting_method = self.get_sorting() try: paginating_method = self.get_pagination(items_total, page) except Http404: return redirect(self.get_url()) # List items items = self.get_items() if not request.session.get(self.get_token("filter")): items = items.all() # Set extra filters? try: items = self.select_items(items) except AttributeError: pass # Sort them items = self.sort_items(items, sorting_method) # Set pagination if self.pagination: items = items[paginating_method["start"] : paginating_method["stop"]] # Prefetch related? try: items = self.prefetch_related(items) except AttributeError: pass # Default message message = None # See if we should make and handle search form search_form = None SearchForm = self.get_search_form() if SearchForm: if request.method == "POST": # New search if request.POST.get("origin") == "search": search_form = SearchForm(request.POST, request=request) if search_form.is_valid(): search_criteria = {} for field, criteria in search_form.cleaned_data.items(): if len(criteria) > 0: search_criteria[field] = criteria if not search_criteria: message = Message(_("No search criteria have been defined.")) else: request.session[self.get_token("filter")] = search_criteria return redirect(self.get_url()) else: message = Message(_("Search form contains errors.")) message.type = "error" else: search_form = SearchForm(request=request) # Kill search if request.POST.get("origin") == "clear" and self.is_filtering and request.csrf.request_secure(request): request.session[self.get_token("filter")] = None request.messages.set_flash(Message(_("Search criteria have been cleared.")), "info", self.admin.id) return redirect(self.get_url()) else: if self.is_filtering: search_form = SearchForm(request=request, initial=request.session.get(self.get_token("filter"))) else: search_form = SearchForm(request=request) # See if we sould make and handle tab form table_form = None TableForm = self.get_table_form(items) if TableForm: if request.method == "POST" and request.POST.get("origin") == "table": table_form = TableForm(request.POST, request=request) if table_form.is_valid(): message, redirect_url = self.table_action(items, table_form.cleaned_data) if redirect_url: request.messages.set_flash(message, message.type, self.admin.id) return redirect(redirect_url) else: message = Message(table_form.non_field_errors()[0], "error") else: table_form = TableForm(request=request) # See if we should make and handle list form list_form = None ListForm = self.get_actions_form(items) if ListForm: if request.method == "POST" and request.POST.get("origin") == "list": list_form = ListForm(request.POST, request=request) if list_form.is_valid(): try: form_action = getattr(self, "action_" + list_form.cleaned_data["list_action"]) message, redirect_url = form_action( items, [int(x) for x in list_form.cleaned_data["list_items"]] ) if redirect_url: request.messages.set_flash(message, message.type, self.admin.id) return redirect(redirect_url) except AttributeError: message = Message(_("Action requested is incorrect.")) else: if "list_items" in list_form.errors: message = Message(self.nothing_checked_message) elif "list_action" in list_form.errors: message = Message(_("Action requested is incorrect.")) else: message = Message(list_form.non_field_errors()[0]) message.type = "error" else: list_form = ListForm(request=request) # Little hax to keep counters correct items_shown = len(items) if items_total < items_shown: items_total = items_shown # Render list return request.theme.render_to_response( self.get_template(), self.add_template_variables( { "admin": self.admin, "action": self, "request": request, "url": self.get_url(), "messages_log": request.messages.get_messages(self.admin.id), "message": message, "sorting": self.sortables, "sorting_method": sorting_method, "pagination": paginating_method, "list_form": FormLayout(list_form) if list_form else None, "search_form": FormLayout(search_form) if search_form else None, "table_form": FormFields(table_form).fields if table_form else None, "items": items, "items_total": items_total, "items_shown": items_shown, } ), context_instance=RequestContext(request), )
def signin(request): message = request.messages.get_message('security') if request.method == 'POST': form = SignInForm( request.POST, show_remember_me=not request.firewall.admin and request.settings['remember_me_allow'], show_stay_hidden=not request.firewall.admin and request.settings['sessions_hidden'], request=request ) if form.is_valid(): try: # Configure correct auth and redirect links if request.firewall.admin: auth_method = auth_admin success_redirect = reverse(site.get_admin_index()) else: auth_method = auth_forum success_redirect = reverse('index') # Authenticate user user = auth_method( request, form.cleaned_data['user_email'], form.cleaned_data['user_password'], ) if not request.firewall.admin and request.settings['sessions_hidden'] and form.cleaned_data['user_stay_hidden']: request.session.hidden = True sign_user_in(request, user, request.session.hidden) remember_me_token = False if not request.firewall.admin and request.settings['remember_me_allow'] and form.cleaned_data['user_remember_me']: remember_me_token = get_random_string(42) remember_me = Token( id=remember_me_token, user=user, created=timezone.now(), accessed=timezone.now(), hidden=request.session.hidden ) remember_me.save() if remember_me_token: request.cookie_jar.set('TOKEN', remember_me_token, True) request.messages.set_flash(Message(request, 'security/signed_in', extra={'user': user}), 'success', 'security') return redirect(success_redirect) except AuthException as e: message = Message(request, e.type, extra={'user':e.user, 'ban':e.ban}) message.type = 'error' # If not in Admin, register failed attempt if not request.firewall.admin and e.type == auth.CREDENTIALS: SignInAttempt.objects.register_attempt(request.session.get_ip(request)) # Have we jammed our account? if SignInAttempt.objects.is_jammed(request.settings, request.session.get_ip(request)): request.jam.expires = timezone.now() return redirect(reverse('sign_in')) else: message = Message(request, form.non_field_errors()[0]) message.type = 'error' else: form = SignInForm( show_remember_me=not request.firewall.admin and request.settings['remember_me_allow'], show_stay_hidden=not request.firewall.admin and request.settings['sessions_hidden'], request=request ) return request.theme.render_to_response('signin.html', { 'message': message, 'form': FormLayout(form, [ ( None, [('user_email', {'attrs': {'placeholder': _("Enter your e-mail")}}), ('user_password', {'has_value': False, 'placeholder': _("Enter your password")})] ), ( None, ['user_remember_me', 'user_stay_hidden'], ), ]), 'hide_signin': True, }, context_instance=RequestContext(request));