def search_replace(request, project, subproject, lang): translation = get_translation(request, project, subproject, lang) if not can_translate(request.user, translation): raise PermissionDenied() form = ReplaceForm(request.POST) if translation.subproject.locked or not form.is_valid(): messages.error(request, _('Failed to process form!')) return redirect(translation) search_text = form.cleaned_data['search'] replacement = form.cleaned_data['replacement'] matching = translation.unit_set.filter(target__contains=search_text) updated = matching.count() for unit in matching.iterator(): unit.target = unit.target.replace(search_text, replacement) unit.save_backend(request, change_action=Change.ACTION_REPLACE) import_message( request, updated, _('Search and replace completed, no strings were updated.'), ungettext( 'Search and replace completed, %d string was updated.', 'Search and replace completed, %d strings were updated.', updated ) ) return redirect(translation)
def upload_dictionary(request, project, lang): prj = get_project(request, project) lang = get_object_or_404(Language, code=lang) form = DictUploadForm(request.POST, request.FILES) if form.is_valid(): try: count = Dictionary.objects.upload( request, prj, lang, request.FILES['file'], form.cleaned_data['method'] ) import_message( request, count, _('No words to import found in file.'), ungettext( 'Imported %d word from the uploaded file.', 'Imported %d words from the uploaded file.', count ) ) except Exception as error: report_error(error, sys.exc_info(), request) messages.error( request, _('File upload has failed: %s') % force_text(error) ) else: messages.error(request, _('Failed to process form!')) return redirect( 'show_dictionary', project=prj.slug, lang=lang.code )
def post_login_handler(sender, request, user, **kwargs): ''' Signal handler for setting user language and migrating profile if needed. ''' # Warning about setting password if (getattr(user, 'backend', '').endswith('.EmailAuth') and not user.has_usable_password()): request.session['show_set_password'] = True # Ensure user has a profile profile = Profile.objects.get_or_create(user=user)[0] # Migrate django-registration based verification to python-social-auth if (user.has_usable_password() and user.email and not user.social_auth.filter(provider='email').exists()): social = user.social_auth.create( provider='email', uid=user.email, ) VerifiedEmail.objects.create( social=social, email=user.email, ) # Set language for session based on preferences set_lang(request, profile) # Warn about not set email if not user.email: messages.error( request, _('You can not submit translations as ' 'you do not have assigned any email address.'))
def reset_password(request): """ Password reset handling. """ if "email" not in load_backends(BACKENDS).keys(): messages.error(request, _("Can not reset password, email authentication is disabled!")) return redirect("login") if request.method == "POST": form = ResetForm(request.POST) if form.is_valid(): user = form.cleaned_data["email"] user.set_unusable_password() user.save() # Force creating new session request.session.create() if request.user.is_authenticated(): logout(request) request.session["password_reset"] = True return complete(request, "email") else: form = ResetForm() return render(request, "accounts/reset.html", {"title": _("Password reset"), "form": form})
def reset_password(request): ''' Password reset handling. ''' if 'email' not in load_backends(BACKENDS).keys(): messages.error( request, _('Can not reset password, email authentication is disabled!')) return redirect('login') if request.method == 'POST': form = ResetForm(request.POST) if form.is_valid(): # Force creating new session request.session.create() if request.user.is_authenticated(): logout(request) request.session['password_reset'] = True return complete(request, 'email') else: form = ResetForm() return render(request, 'accounts/reset.html', { 'title': _('Password reset'), 'form': form, })
def save_zen(request, project, subproject, lang): ''' Save handler for zen mode. ''' translation = get_translation(request, project, subproject, lang) user_locked = translation.is_user_locked(request.user) form = TranslationForm(translation, None, request.POST) if not can_translate(request.user, translation): messages.error( request, _('You don\'t have privileges to save translations!') ) elif not form.is_valid(): messages.error(request, _('Failed to save translation!')) elif not user_locked: unit = form.cleaned_data['unit'] perform_translation(unit, form, request) return render( request, 'zen-response.html', {}, )
def auto_translation(request, project, subproject, lang): translation = get_translation(request, project, subproject, lang) project = translation.subproject.project if not can_automatic_translation(request.user, project): raise PermissionDenied() autoform = AutoForm(translation, request.user, request.POST) if translation.subproject.locked or not autoform.is_valid(): messages.error(request, _('Failed to process form!')) return redirect(translation) updated = auto_translate(request.user, translation, autoform.cleaned_data['subproject'], autoform.cleaned_data['inconsistent'], autoform.cleaned_data['overwrite']) import_message( request, updated, _('Automatic translation completed, no strings were updated.'), ungettext('Automatic translation completed, %d string was updated.', 'Automatic translation completed, %d strings were updated.', updated)) return redirect(translation)
def new_language(request, project, subproject): obj = get_subproject(request, project, subproject) if not can_add_translation(request.user, obj.project): raise PermissionDenied() form = get_new_language_form(request, obj)(obj, request.POST) if form.is_valid(): langs = form.cleaned_data['lang'] if isinstance(langs, string_types): langs = [langs] for language in Language.objects.filter(code__in=langs): if obj.new_lang == 'contact': notify_new_language(obj, language, request.user) messages.success( request, _("A request for a new translation has been " "sent to the project's maintainers.")) elif obj.new_lang == 'add': obj.add_new_language(language, request) else: messages.error(request, _('Invalid language chosen!')) return redirect(obj)
def perform_suggestion(unit, form, request): ''' Handle suggesion saving. ''' if form.cleaned_data['target'][0] == '': messages.error(request, _('Your suggestion is empty!')) # Stay on same entry return False elif not can_suggest(request.user, unit.translation): # Need privilege to add messages.error(request, _('You don\'t have privileges to add suggestions!')) # Stay on same entry return False # Invite user to become translator if there is nobody else recent_changes = Change.objects.content(True).filter( translation=unit.translation, ).exclude(user=None) if not recent_changes.exists(): messages.info( request, _('There is currently no active translator for this ' 'translation, please consider becoming a translator ' 'as your suggestion might otherwise remain unreviewed.')) # Create the suggestion Suggestion.objects.add( unit, join_plural(form.cleaned_data['target']), request, ) return True
def password(request): ''' Password change / set form. ''' if appsettings.DEMO_SERVER and request.user.username == 'demo': return deny_demo(request) do_change = False if not request.user.has_usable_password(): do_change = True change_form = None elif request.method == 'POST': change_form = PasswordChangeForm(request.POST) if change_form.is_valid(): cur_password = change_form.cleaned_data['password'] do_change = request.user.check_password(cur_password) if not do_change: messages.error( request, _('You have entered an invalid password.') ) else: change_form = PasswordChangeForm() if request.method == 'POST': form = PasswordForm(request.POST) if form.is_valid() and do_change: # Clear flag forcing user to set password redirect_page = '#auth' if 'show_set_password' in request.session: del request.session['show_set_password'] redirect_page = '' request.user.set_password( form.cleaned_data['password1'] ) request.user.save() # Update session hash update_session_auth_hash(request, request.user) messages.success( request, _('Your password has been changed.') ) return redirect_profile(redirect_page) else: form = PasswordForm() return render( request, 'accounts/password.html', { 'title': _('Change password'), 'change_form': change_form, 'form': form, } )
def check_acl(self, request): """Raises an error if user is not allowed to access this project.""" if not self.has_acl(request.user): messages.error( request, _('You are not allowed to access project %s.') % self.name) raise PermissionDenied
def mail_admins_contact(request, subject, message, context, sender): ''' Sends a message to the admins, as defined by the ADMINS setting. ''' LOGGER.info( 'contact form from %s', sender, ) if not settings.ADMINS: messages.error( request, _('Message could not be sent to administrator!') ) LOGGER.error( 'ADMINS not configured, can not send message!' ) return mail = EmailMultiAlternatives( '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject % context), message % context, to=[a[1] for a in settings.ADMINS], headers={'Reply-To': sender}, ) mail.send(fail_silently=False) messages.success( request, _('Message has been sent to administrator.') )
def auto_translation(request, project, subproject, lang): translation = get_translation(request, project, subproject, lang) project = translation.subproject.project if not can_automatic_translation(request.user, project): raise PermissionDenied() autoform = AutoForm(translation, request.user, request.POST) if translation.subproject.locked or not autoform.is_valid(): messages.error(request, _('Failed to process form!')) return redirect(translation) updated = auto_translate( request.user, translation, autoform.cleaned_data['subproject'], autoform.cleaned_data['inconsistent'], autoform.cleaned_data['overwrite'] ) import_message( request, updated, _('Automatic translation completed, no strings were updated.'), ungettext( 'Automatic translation completed, %d string was updated.', 'Automatic translation completed, %d strings were updated.', updated ) ) return redirect(translation)
def comment(request, pk): ''' Adds new comment. ''' translation = get_object_or_404(Unit, pk=pk) translation.check_acl(request) form = CommentForm(request.POST) if form.is_valid(): if form.cleaned_data['scope'] == 'global': lang = None else: lang = translation.translation.language Comment.objects.add( translation, request.user, lang, form.cleaned_data['comment'] ) messages.success(request, _('Posted new comment')) else: messages.error(request, _('Failed to add comment!')) return redirect(request.POST.get('next', translation))
def new_language(request, project, subproject): obj = get_subproject(request, project, subproject) if not can_add_translation(request.user, obj.project): raise PermissionDenied() form = get_new_language_form(request, obj)(obj, request.POST) if form.is_valid(): langs = form.cleaned_data['lang'] if isinstance(langs, string_types): langs = [langs] for language in Language.objects.filter(code__in=langs): if obj.new_lang == 'contact': notify_new_language(obj, language, request.user) messages.success( request, _( "A request for a new translation has been " "sent to the project's maintainers." ) ) elif obj.new_lang == 'add': obj.add_new_language(language, request) else: messages.error( request, _('Invalid language chosen!') ) return redirect(obj)
def reset_password(request): ''' Password reset handling. ''' if 'email' not in load_backends(BACKENDS).keys(): messages.error( request, _('Can not reset password, email authentication is disabled!') ) return redirect('login') if request.method == 'POST': form = ResetForm(request.POST) if form.is_valid(): # Force creating new session request.session.create() if request.user.is_authenticated(): logout(request) request.session['password_reset'] = True return complete(request, 'email') else: form = ResetForm() return render( request, 'accounts/reset.html', { 'title': _('Password reset'), 'form': form, } )
def search_replace(request, project, subproject, lang): translation = get_translation(request, project, subproject, lang) if not can_translate(request.user, translation): raise PermissionDenied() form = ReplaceForm(request.POST) if translation.subproject.locked or not form.is_valid(): messages.error(request, _('Failed to process form!')) return redirect(translation) search_text = form.cleaned_data['search'] replacement = form.cleaned_data['replacement'] matching = translation.unit_set.filter(target__contains=search_text) updated = matching.count() for unit in matching.iterator(): unit.target = unit.target.replace(search_text, replacement) unit.save_backend(request, change_action=Change.ACTION_REPLACE) import_message( request, updated, _('Search and replace completed, no strings were updated.'), ungettext('Search and replace completed, %d string was updated.', 'Search and replace completed, %d strings were updated.', updated)) return redirect(translation)
def perform_suggestion(unit, form, request): ''' Handle suggesion saving. ''' if form.cleaned_data['target'][0] == '': messages.error(request, _('Your suggestion is empty!')) # Stay on same entry return False elif not can_suggest(request.user, unit.translation): # Need privilege to add messages.error( request, _('You don\'t have privileges to add suggestions!') ) # Stay on same entry return False # Invite user to become translator if there is nobody else recent_changes = Change.objects.content(True).filter( translation=unit.translation, ).exclude( user=None ) if not recent_changes.exists(): messages.info(request, _( 'There is currently no active translator for this ' 'translation, please consider becoming a translator ' 'as your suggestion might otherwise remain unreviewed.' )) # Create the suggestion Suggestion.objects.add( unit, join_plural(form.cleaned_data['target']), request, ) return True
def check_acl(self, request): """Raises an error if user is not allowed to access this project.""" if not self.has_acl(request.user): messages.error( request, _('You are not allowed to access project %s.') % self.name ) raise PermissionDenied
def _get_queryset_user(self): """ Filtering by user """ if "user" in self.request.GET: try: self.user = User.objects.get(username=self.request.GET["user"]) except User.DoesNotExist: messages.error(self.request, _("Failed to find matching user!"))
def _get_queryset_language(self): """ Filtering by language """ if self.translation is None and "lang" in self.request.GET: try: self.language = Language.objects.get(code=self.request.GET["lang"]) except Language.DoesNotExist: messages.error(self.request, _("Failed to find matching language!"))
def _get_queryset_user(self): """ Filtering by user """ if 'user' in self.request.GET: try: self.user = User.objects.get(username=self.request.GET['user']) except User.DoesNotExist: messages.error(self.request, _('Failed to find matching user!'))
def _get_queryset_language(self): """ Filtering by language """ if self.translation is None and 'lang' in self.request.GET: try: self.language = Language.objects.get( code=self.request.GET['lang']) except Language.DoesNotExist: messages.error(self.request, _('Failed to find matching language!'))
def perform_translation(unit, form, request): ''' Handles translation and stores it to a backend. ''' # Remember old checks oldchecks = set( unit.active_checks().values_list('check', flat=True) ) # Run AutoFixes on user input if not unit.translation.is_template(): new_target, fixups = fix_target(form.cleaned_data['target'], unit) else: new_target = form.cleaned_data['target'] fixups = [] # Save saved = unit.translate( request, new_target, form.cleaned_data['fuzzy'] ) # Warn about applied fixups if len(fixups) > 0: messages.info( request, _('Following fixups were applied to translation: %s') % ', '.join([force_text(f) for f in fixups]) ) # Get new set of checks newchecks = set( unit.active_checks().values_list('check', flat=True) ) # Did we introduce any new failures? if saved and newchecks > oldchecks: # Show message to user messages.error( request, _( 'Some checks have failed on your translation: {0}' ).format( ', '.join( [force_text(CHECKS[check].name) for check in newchecks] ) ) ) # Stay on same entry return False return True
def auth_complete(self, *args, **kwargs): try: return super(EmailAuth, self).auth_complete(*args, **kwargs) except AuthMissingParameter as error: if error.parameter == 'email': messages.error( self.strategy.request, _('Failed to verify your registration! ' 'Probably the verification token has expired. ' 'Please try the registration again.')) report_error(error, sys.exc_info(), extra_data=self.data) return redirect(reverse('login')) raise
def search(request): """ Performs site-wide search on units. """ search_form = SiteSearchForm(request.GET) context = { 'search_form': search_form, } if search_form.is_valid(): # Filter results by ACL acl_projects = Project.objects.get_acl_ids(request.user) units = Unit.objects.search( None, search_form.cleaned_data, ).filter( translation__subproject__project_id__in=acl_projects ).select_related( 'translation', ) limit = request.GET.get('limit', 50) page = request.GET.get('page', 1) paginator = Paginator(units, limit) try: units = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. units = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of # results. units = paginator.page(paginator.num_pages) context['page_obj'] = units context['title'] = _('Search for %s') % ( search_form.cleaned_data['q'] ) context['query_string'] = search_form.urlencode() context['search_query'] = search_form.cleaned_data['q'] else: messages.error(request, _('Invalid search query!')) return render( request, 'search.html', context )
def show_form_errors(request, form): ''' Shows all form errors as a message. ''' for error in form.non_field_errors(): messages.error(request, error) for field in form: for error in field.errors: messages.error( request, _('Error in parameter %(field)s: %(error)s') % { 'field': field.name, 'error': error })
def _get_queryset_project(self): """ Filtering by translation/project. """ if "project" in self.request.GET: try: self.project, self.subproject, self.translation = get_project_translation( self.request, self.request.GET.get("project", None), self.request.GET.get("subproject", None), self.request.GET.get("lang", None), ) except Http404: messages.error(self.request, _("Failed to find matching project!"))
def password(request): ''' Password change / set form. ''' if appsettings.DEMO_SERVER and request.user.username == 'demo': return deny_demo(request) do_change = False if not request.user.has_usable_password(): do_change = True change_form = None elif request.method == 'POST': change_form = PasswordChangeForm(request.POST) if change_form.is_valid(): cur_password = change_form.cleaned_data['password'] do_change = request.user.check_password(cur_password) if not do_change: messages.error(request, _('You have entered an invalid password.')) else: change_form = PasswordChangeForm() if request.method == 'POST': form = PasswordForm(request.POST) if form.is_valid() and do_change: # Clear flag forcing user to set password redirect_page = '#auth' if 'show_set_password' in request.session: del request.session['show_set_password'] redirect_page = '' request.user.set_password(form.cleaned_data['password1']) request.user.save() # Update session hash update_session_auth_hash(request, request.user) messages.success(request, _('Your password has been changed.')) return redirect_profile(redirect_page) else: form = PasswordForm() return render(request, 'accounts/password.html', { 'title': _('Change password'), 'change_form': change_form, 'form': form, })
def show_project(request, project): obj = get_project(request, project) dict_langs = Dictionary.objects.filter(project=obj).values_list( 'language', flat=True).distinct() if request.method == 'POST' and can_edit_project(request.user, obj): settings_form = ProjectSettingsForm(request.POST, instance=obj) if settings_form.is_valid(): settings_form.save() messages.success(request, _('Settings saved')) return redirect(obj) else: messages.error( request, _('Invalid settings, please check the form for errors!')) else: settings_form = ProjectSettingsForm(instance=obj) dicts = [] for language in Language.objects.filter(id__in=dict_langs): dicts.append({ 'language': language, 'count': Dictionary.objects.filter(language=language, project=obj).count(), }) last_changes = Change.objects.prefetch().filter( Q(translation__subproject__project=obj) | Q(dictionary__project=obj))[:10] language_stats = sort_unicode(get_per_language_stats(obj), lambda tup: force_text(tup[0])) language_stats = [(tup[0], translation_percent(tup[1], tup[2])) for tup in language_stats] return render( request, 'project.html', { 'object': obj, 'project': obj, 'dicts': dicts, 'last_changes': last_changes, 'last_changes_url': urlencode({'project': obj.slug}), 'add_user_form': UserManageForm(), 'settings_form': settings_form, 'language_stats': language_stats, })
def execute_locked(request, obj, message, call, *args, **kwargs): """ Helper function to catch possible lock exception. """ try: result = call(*args, **kwargs) # With False the call is supposed to show errors on its own if result is None or result: messages.success(request, message) except FileLockException: messages.error( request, _('Failed to lock the repository, another operation in progress.')) return redirect_param(obj, '#repository')
def show_form_errors(request, form): ''' Shows all form errors as a message. ''' for error in form.non_field_errors(): messages.error(request, error) for field in form: for error in field.errors: messages.error( request, _('Error in parameter %(field)s: %(error)s') % { 'field': field.name, 'error': error } )
def check_user_form(request, project): obj = get_project(request, project) if not can_manage_acl(request.user, obj): raise PermissionDenied() form = UserManageForm(request.POST) if form.is_valid(): return obj, form else: for error in form.errors: for message in form.errors[error]: messages.error(request, message) return obj, None
def _get_queryset_project(self): """ Filtering by translation/project. """ if 'project' in self.request.GET: try: self.project, self.subproject, self.translation = \ get_project_translation( self.request, self.request.GET.get('project', None), self.request.GET.get('subproject', None), self.request.GET.get('lang', None), ) except Http404: messages.error(self.request, _('Failed to find matching project!'))
def execute_locked(request, obj, message, call, *args, **kwargs): """ Helper function to catch possible lock exception. """ try: result = call(request, *args, **kwargs) # With False the call is supposed to show errors on its own if result is None or result: messages.success(request, message) except FileLockException: messages.error( request, _('Failed to lock the repository, another operation in progress.') ) return redirect_param(obj, '#repository')
def edit_check_flags(request, pk): """ Change source string check flags. """ source = get_object_or_404(Source, pk=pk) if not can_edit_flags(request.user, source.subproject.project): raise PermissionDenied() form = CheckFlagsForm(request.POST) if form.is_valid(): source.check_flags = form.cleaned_data['flags'] source.save() else: messages.error(request, _('Failed to change check flags!')) return redirect(request.POST.get('next', source.get_absolute_url()))
def edit_priority(request, pk): """ Change source string priority. """ source = get_object_or_404(Source, pk=pk) if not can_edit_priority(request.user, source.subproject.project): raise PermissionDenied() form = PriorityForm(request.POST) if form.is_valid(): source.priority = form.cleaned_data['priority'] source.save() else: messages.error(request, _('Failed to change a priority!')) return redirect(request.POST.get('next', source.get_absolute_url()))
def add_host_key(request): """ Adds host key for a host. """ host = request.POST.get('host', '') port = request.POST.get('port', '') if len(host) == 0: messages.error(request, _('Invalid host name given!')) else: cmdline = ['ssh-keyscan'] if port: cmdline.extend(['-p', port]) cmdline.append(host) try: output = subprocess.check_output( cmdline, stderr=subprocess.STDOUT, env=get_clean_env(), ) keys = [] for key in output.decode('utf-8').splitlines(): key = key.strip() if not is_key_line(key): continue keys.append(key) host, keytype, fingerprint = parse_hosts_line(key) messages.warning( request, _( 'Added host key for %(host)s with fingerprint ' '%(fingerprint)s (%(keytype)s), ' 'please verify that it is correct.' ) % { 'host': host, 'fingerprint': fingerprint, 'keytype': keytype, } ) if len(keys) == 0: messages.error( request, _('Failed to fetch public key for a host!') ) with open(ssh_file(KNOWN_HOSTS), 'a') as handle: for key in keys: handle.write('%s\n' % key) except subprocess.CalledProcessError as exc: messages.error( request, _('Failed to get host key: %s') % exc.output ) except OSError as exc: messages.error( request, _('Failed to get host key: %s') % str(exc) )
def show_subproject(request, project, subproject): obj = get_subproject(request, project, subproject) last_changes = Change.objects.prefetch().filter( translation__subproject=obj)[:10] new_lang_form = get_new_language_form(request, obj)(obj) if (request.method == 'POST' and can_edit_subproject(request.user, obj.project)): settings_form = SubprojectSettingsForm(request.POST, instance=obj) if settings_form.is_valid(): settings_form.save() messages.success(request, _('Settings saved')) return redirect(obj) else: messages.error( request, _('Invalid settings, please check the form for errors!')) else: settings_form = SubprojectSettingsForm(instance=obj) return render( request, 'subproject.html', { 'object': obj, 'project': obj.project, 'translations': sort_objects(obj.translation_set.enabled()), 'show_language': 1, 'reports_form': ReportsForm(), 'last_changes': last_changes, 'last_changes_url': urlencode({ 'subproject': obj.slug, 'project': obj.project.slug }), 'new_lang_form': new_lang_form, 'settings_form': settings_form, })
def upload_screenshot(request, pk): """ Upload screenshot handler. """ source = get_object_or_404(Source, pk=pk) if not can_upload_screenshot(request.user, source.subproject.project): raise PermissionDenied() form = ScreenshotUploadForm(request.POST, request.FILES, instance=source) if form.is_valid(): form.save() else: for error in form.errors: for message in form.errors[error]: messages.error(request, message) return redirect(request.POST.get('next', source.get_absolute_url()))
def handle_translate(translation, request, user_locked, this_unit_url, next_unit_url): ''' Saves translation or suggestion to database and backend. ''' # Antispam protection antispam = AntispamForm(request.POST) if not antispam.is_valid(): # Silently redirect to next entry return HttpResponseRedirect(next_unit_url) # Check whether translation is not outdated translation.check_sync() form = TranslationForm(translation, None, request.POST) if not form.is_valid(): return unit = form.cleaned_data['unit'] go_next = True if 'suggest' in request.POST: go_next = perform_suggestion(unit, form, request) elif not can_translate(request.user, unit.translation): messages.error( request, _('You don\'t have privileges to save translations!') ) elif not user_locked: # Custom commit message message = request.POST.get('commit_message') if message and message != unit.translation.commit_message: # Commit pending changes so that they don't get new message unit.translation.commit_pending(request, request.user) # Store new commit message unit.translation.commit_message = message unit.translation.save() go_next = perform_translation(unit, form, request) # Redirect to next entry if go_next: return HttpResponseRedirect(next_unit_url) else: return HttpResponseRedirect(this_unit_url)
def _get_queryset_project(self): """ Filtering by translation/project. """ if 'project' in self.request.GET: try: self.project, self.subproject, self.translation = \ get_project_translation( self.request, self.request.GET.get('project', None), self.request.GET.get('subproject', None), self.request.GET.get('lang', None), ) except Http404: messages.error( self.request, _('Failed to find matching project!') )
def revoke_owner(request, project): obj, form = check_user_form(request, project) if form is not None: if obj.owners.count() <= 1: messages.error(request, _('You can not remove last owner!')) else: # Ensure owner stays within project if obj.enable_acl: obj.add_user(form.cleaned_data['user']) obj.owners.remove(form.cleaned_data['user']) return redirect_param( 'project', '#acl', project=obj.slug, )
def password(request): """ Password change / set form. """ if appsettings.DEMO_SERVER and request.user.username == "demo": return deny_demo(request) do_change = False if not request.user.has_usable_password(): do_change = True change_form = None elif request.method == "POST": change_form = PasswordChangeForm(request.POST) if change_form.is_valid(): cur_password = change_form.cleaned_data["password"] do_change = request.user.check_password(cur_password) if not do_change: messages.error(request, _("You have entered an invalid password.")) else: change_form = PasswordChangeForm() if request.method == "POST": form = PasswordForm(request.POST) if form.is_valid() and do_change: # Clear flag forcing user to set password if "show_set_password" in request.session: del request.session["show_set_password"] request.user.set_password(form.cleaned_data["password1"]) request.user.save() # Update session hash update_session_auth_hash(request, request.user) messages.success(request, _("Your password has been changed.")) return redirect("profile") else: form = PasswordForm() return render( request, "accounts/password.html", {"title": _("Change password"), "change_form": change_form, "form": form} )
def auth_complete(self, *args, **kwargs): try: return super(EmailAuth, self).auth_complete(*args, **kwargs) except AuthMissingParameter as error: if error.parameter == 'email': messages.error( self.strategy.request, _( 'Failed to verify your registration! ' 'Probably the verification token has expired. ' 'Please try the registration again.' ) ) report_error( error, sys.exc_info(), extra_data=self.data ) return redirect(reverse('login')) raise
def delete_user(request, project): obj, form = check_user_form(request, project) if form is not None and obj.enable_acl: is_owner = obj.owners.filter(id=form.cleaned_data['user'].id).exists() if is_owner and obj.owners.count() <= 1: messages.error(request, _('You can not remove last owner!')) else: if is_owner: obj.owners.remove(form.cleaned_data['user']) obj.remove_user(form.cleaned_data['user']) messages.success(request, _('User has been removed from this project.')) return redirect_param( 'project', '#acl', project=obj.slug, )
def mail_admins_contact(request, subject, message, context, sender): """ Sends a message to the admins, as defined by the ADMINS setting. """ LOGGER.info("contact form from %s", sender) if not settings.ADMINS: messages.error(request, _("Message could not be sent to administrator!")) LOGGER.error("ADMINS not configured, can not send message!") return mail = EmailMultiAlternatives( "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject % context), message % context, to=[a[1] for a in settings.ADMINS], headers={"Reply-To": sender}, ) mail.send(fail_silently=False) messages.success(request, _("Message has been sent to administrator."))
def generate_ssh_key(request): """ Generates SSH key. """ try: # Actually generate the key subprocess.check_output( [ 'ssh-keygen', '-q', '-N', '', '-C', 'Weblate', '-t', 'rsa', '-f', ssh_file(RSA_KEY) ], stderr=subprocess.STDOUT, env=get_clean_env(), ) messages.success(request, _('Created new SSH key.')) except (subprocess.CalledProcessError, OSError) as exc: messages.error( request, _('Failed to generate key: %s') % getattr(exc, 'output', str(exc)))
def handle_merge(translation, request, next_unit_url): ''' Handles unit merging. ''' if not can_translate(request.user, translation): messages.error(request, _('You don\'t have privileges to save translations!')) return mergeform = MergeForm(translation, request.GET) if not mergeform.is_valid(): messages.error(request, _('Invalid merge request!')) return unit = mergeform.cleaned_data['unit'] merged = Unit.objects.get(pk=mergeform.cleaned_data['merge']) if unit.checksum != merged.checksum: messages.error(request, _('Can not merge different messages!')) else: # Store unit unit.target = merged.target unit.fuzzy = merged.fuzzy saved = unit.save_backend(request) # Update stats if there was change if saved: request.user.profile.translated += 1 request.user.profile.save() # Redirect to next entry return HttpResponseRedirect(next_unit_url)