def get_view_description(view_cls, html=False): """ Given a view class, return a textual description to represent the view. This name is used in the browsable API, and in OPTIONS responses. This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting. """ description = view_cls.__doc__ or '' description = formatting.dedent(smart_text(description)) if hasattr(view_cls, 'serializer_class'): doc_url = get_doc_url( 'api' '{0}s'.format( view_cls.serializer_class.Meta.model.__name__.lower() ) ) else: doc_url = get_doc_url('api') description = '\n\n'.join(( description, DOC_TEXT.format(doc_url) )) if html: return formatting.markup_description(description) return description
def data_root(request): return render( request, 'data-root.html', { 'hooks_docs': weblate.get_doc_url('api', 'hooks'), 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), })
def data_root(request): return render_to_response('data-root.html', RequestContext(request, { 'hooks_docs': weblate.get_doc_url('api', 'hooks'), 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), 'projects': Project.objects.all_acl(request.user), }))
def data_project(request, project): obj = get_project(request, project) return render_to_response('data.html', RequestContext(request, { 'object': obj, 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), }))
def data_root(request): return render( request, 'data-root.html', { 'hooks_docs': weblate.get_doc_url('api', 'hooks'), 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), 'projects': Project.objects.all_acl(request.user), })
def data_root(request): site = Site.objects.get_current() return render_to_response('data-root.html', RequestContext(request, { 'site_domain': site.domain, 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), 'projects': Project.objects.all_acl(request.user), }))
def data_project(request, project): obj = get_project(request, project) return render( request, 'data.html', { 'object': obj, 'hooks_docs': weblate.get_doc_url('api', 'hooks'), 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), })
def data_project(request, project): obj = get_project(request, project) site = Site.objects.get_current() return render_to_response('data.html', RequestContext(request, { 'object': obj, 'site_domain': site.domain, 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), }))
def data_root(request): return render_to_response( 'data-root.html', RequestContext( request, { 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), 'projects': Project.objects.all_acl(request.user), }))
def data_project(request, project): obj = get_project(request, project) return render_to_response( 'data.html', RequestContext( request, { 'object': obj, 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), }))
def data_root(request): return render( request, 'data-root.html', { 'hooks_docs': weblate.get_doc_url('api', 'hooks'), 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), } )
def data_root(request): return render_to_response( "data-root.html", RequestContext( request, { "api_docs": weblate.get_doc_url("api", "exports"), "rss_docs": weblate.get_doc_url("api", "rss"), "projects": Project.objects.all_acl(request.user), }, ), )
def data_project(request, project): obj = get_project(request, project) return render( request, 'data.html', { 'object': obj, 'hooks_docs': weblate.get_doc_url('api', 'hooks'), 'api_docs': weblate.get_doc_url('api', 'exports'), 'rss_docs': weblate.get_doc_url('api', 'rss'), } )
def data_project(request, project): obj = get_project(request, project) return render_to_response( "data.html", RequestContext( request, { "object": obj, "api_docs": weblate.get_doc_url("api", "exports"), "rss_docs": weblate.get_doc_url("api", "rss"), }, ), )
def ssh(request): """ Show information and manipulate with SSH key. """ # Check whether we can generate SSH key can_generate = can_generate_key() if not is_home_writable(): can_generate = False messages.error( request, _('Can not write to home directory, please check documentation.')) # Grab action type action = request.POST.get('action', None) # Generate key if it does not exist yet if can_generate and action == 'generate': generate_ssh_key(request) # Read key data if it exists key = get_key_data() # Add host key if action == 'add-host': add_host_key(request) return render( request, "admin/ssh.html", { 'public_key': key, 'can_generate': can_generate, 'host_keys': get_host_keys(), 'ssh_docs': weblate.get_doc_url('admin/projects', 'private'), })
def ssh(request): """ Show information and manipulate with SSH key. """ # Check whether we can generate SSH key can_generate = can_generate_key() # Grab action type action = request.POST.get("action", None) # Generate key if it does not exist yet if can_generate and action == "generate": generate_ssh_key(request) # Read key data if it exists key = get_key_data() # Add host key if action == "add-host": add_host_key(request) return render( request, "admin/ssh.html", { "public_key": key, "can_generate": can_generate, "host_keys": get_host_keys(), "ssh_docs": weblate.get_doc_url("admin/projects", "private"), }, )
def ssh(request): """ Show information and manipulate with SSH key. """ # Check whether we can generate SSH key can_generate = can_generate_key() # Grab action type action = request.POST.get('action', None) # Generate key if it does not exist yet if can_generate and action == 'generate': generate_ssh_key(request) # Read key data if it exists key = get_key_data() # Add host key if action == 'add-host': add_host_key(request) context = admin_context(request) context['public_key'] = key context['can_generate'] = can_generate context['host_keys'] = get_host_keys() context['ssh_docs'] = weblate.get_doc_url('admin/projects', 'private') return render( request, "admin/ssh.html", context, )
def ssh(request): """Show information and manipulate with SSH key.""" # Check whether we can generate SSH key can_generate = can_generate_key() # Grab action type action = request.POST.get('action') # Generate key if it does not exist yet if can_generate and action == 'generate': generate_ssh_key(request) # Read key data if it exists key = get_key_data() # Add host key if action == 'add-host': add_host_key(request) context = admin_context(request) context['public_key'] = key context['can_generate'] = can_generate context['host_keys'] = get_host_keys() context['ssh_docs'] = weblate.get_doc_url('admin/projects', 'private') return render( request, "admin/ssh.html", context, )
def __init__(self, *args, **kwargs): super(CheckFlagsForm, self).__init__(*args, **kwargs) self.fields['flags'].help_text = ugettext( 'Please enter a comma separated list of check flags, ' 'see <a href="{url}">documentation</a> for more details.' ).format( url=get_doc_url('admin/checks', 'custom-checks') )
def get_doc_url(self): ''' Returns link to documentation. ''' return weblate.get_doc_url( 'usage', 'check-%s' % self.check_id.replace('_', '-') )
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 elif not request.user.is_authenticated: # Spam check if is_spam('\n'.join(form.cleaned_data['target']), request): messages.error( request, _('Your suggestion has been identified as spam!') ) return False # Invite user to become translator if there is nobody else # and the project is accepting translations translation = unit.translation if (not translation.subproject.suggestion_voting or not translation.subproject.suggestion_autoaccept): recent_changes = Change.objects.content(True).filter( translation=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.' )) messages.info(request, mark_safe( '<a href="{0}">{1}</a>'.format( escape(get_doc_url('user/translating')), escape(_( 'See our documentation for more information ' 'on translating using Weblate.' )), ) )) # Create the suggestion result = Suggestion.objects.add( unit, join_plural(form.cleaned_data['target']), request, can_vote_suggestion(request.user, unit) ) if not result: messages.error(request, _('Your suggestion already exists!')) return result
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 request.user.has_perm('suggestion.add', unit.translation): # Need privilege to add messages.error( request, _('You don\'t have privileges to add suggestions!') ) # Stay on same entry return False elif not request.user.is_authenticated: # Spam check if is_spam('\n'.join(form.cleaned_data['target']), request): messages.error( request, _('Your suggestion has been identified as spam!') ) return False # Invite user to become translator if there is nobody else # and the project is accepting translations translation = unit.translation if (not translation.component.suggestion_voting or not translation.component.suggestion_autoaccept): recent_changes = Change.objects.content(True).filter( translation=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.' )) messages.info(request, mark_safe( '<a href="{0}">{1}</a>'.format( escape(get_doc_url('user/translating')), escape(_( 'See our documentation for more information ' 'on translating using Weblate.' )), ) )) # Create the suggestion result = Suggestion.objects.add( unit, join_plural(form.cleaned_data['target']), request, request.user.has_perm('suggestion.vote', unit) ) if not result: messages.error(request, _('Your suggestion already exists!')) return result
def render(self, name, value, attrs=None, renderer=None, **kwargs): """Render all textareas with correct plural labels.""" unit = value values = unit.get_target_plurals() lang = unit.translation.language plural = unit.translation.plural tabindex = self.attrs['tabindex'] # Need to add extra class attrs['class'] = 'translation-editor form-control' attrs['tabindex'] = tabindex attrs['lang'] = lang.code attrs['dir'] = lang.direction attrs['rows'] = 3 attrs['maxlength'] = unit.get_max_length() # Okay we have more strings ret = [] base_id = 'id_{0}'.format(unit.checksum) for idx, val in enumerate(values): # Generate ID fieldname = '{0}_{1}'.format(name, idx) fieldid = '{0}_{1}'.format(base_id, idx) attrs['id'] = fieldid attrs['tabindex'] = tabindex + idx # Render textare textarea = super(PluralTextarea, self).render(fieldname, val, attrs, renderer, **kwargs) # Label for plural if len(values) == 1: if unit.translation.is_template: label = ugettext('Source') else: label = ugettext('Translation') else: label = plural.get_plural_label(idx) ret.append( EDITOR_TEMPLATE.format( self.get_toolbar(lang, fieldid, unit, idx), fieldid, label, textarea)) # Show plural equation for more strings if len(values) > 1: ret.append( PLURALS_TEMPLATE.format( get_doc_url('user/translating', 'plurals'), ugettext('Documentation for plurals.'), '<abbr title="{0}">{1}</abbr>: {2}'.format( ugettext('This equation identifies which plural form ' 'will be used based on given count (n).'), ugettext('Plural equation'), plural.equation))) # Join output return mark_safe(''.join(ret))
def render(self, name, value, attrs=None): ''' Renders all textareas with correct plural labels. ''' lang, value, checksum = value tabindex = self.attrs['tabindex'] # Need to add extra class attrs['class'] = 'translation-editor form-control' attrs['tabindex'] = tabindex attrs['lang'] = lang.code attrs['dir'] = lang.direction # Okay we have more strings ret = [] base_id = 'id_{0}'.format(checksum) for idx, val in enumerate(value): # Generate ID fieldname = '{0}_{1}'.format(name, idx) fieldid = '{0}_{1}'.format(base_id, idx) attrs['id'] = fieldid attrs['tabindex'] = tabindex + idx # Render textare textarea = super(PluralTextarea, self).render(fieldname, escape_newline(val), attrs) # Label for plural if len(value) == 1: label = ugettext('Translation') else: label = lang.get_plural_label(idx) ret.append( EDITOR_TEMPLATE.format( self.get_toolbar(lang, fieldid, checksum), fieldid, label, textarea)) # Show plural equation for more strings pluralmsg = '' if len(value) > 1: pluralinfo = u'<abbr title="{0}">{1}</abbr>: {2}'.format( ugettext('This equation identifies which plural form ' 'will be used based on given count (n).'), ugettext('Plural equation'), lang.pluralequation) pluralmsg = PLURALS_TEMPLATE.format( weblate.get_doc_url('user/translating', 'plurals'), ugettext('Documentation for plurals.'), pluralinfo) # Join output return mark_safe(''.join(ret) + pluralmsg)
def render(self, name, unit, attrs=None): """ Renders all textareas with correct plural labels. """ values = unit.get_target_plurals() lang = unit.translation.language tabindex = self.attrs["tabindex"] # Need to add extra class attrs["class"] = "translation-editor form-control" attrs["tabindex"] = tabindex attrs["lang"] = lang.code attrs["dir"] = lang.direction attrs["rows"] = 3 # Okay we have more strings ret = [] base_id = "id_{0}".format(unit.checksum) for idx, val in enumerate(values): # Generate ID fieldname = "{0}_{1}".format(name, idx) fieldid = "{0}_{1}".format(base_id, idx) attrs["id"] = fieldid attrs["tabindex"] = tabindex + idx # Render textare textarea = super(PluralTextarea, self).render(fieldname, val, attrs) # Label for plural if len(values) == 1: label = ugettext("Translation") else: label = lang.get_plural_label(idx) ret.append(EDITOR_TEMPLATE.format(self.get_toolbar(lang, fieldid, unit, idx), fieldid, label, textarea)) # Show plural equation for more strings pluralmsg = "" if len(values) > 1: pluralinfo = u'<abbr title="{0}">{1}</abbr>: {2}'.format( ugettext("This equation identifies which plural form " "will be used based on given count (n)."), ugettext("Plural equation"), lang.pluralequation, ) pluralmsg = PLURALS_TEMPLATE.format( weblate.get_doc_url("user/translating", "plurals"), ugettext("Documentation for plurals."), pluralinfo ) # Join output return mark_safe("".join(ret) + pluralmsg)
def ssh(request): """ Show information and manipulate with SSH key. """ # Check whether we can generate SSH key try: ret = subprocess.check_call( ['which', 'ssh-keygen'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=get_clean_env(), ) can_generate = (ret == 0 and not os.path.exists(RSA_KEY_FILE)) except subprocess.CalledProcessError: can_generate = False if not os.access(os.path.expanduser('~'), os.W_OK): can_generate = False messages.error( request, _('Can not write to home directory, please check documentation.') ) # Grab action type action = request.POST.get('action', None) # Generate key if it does not exist yet if can_generate and action == 'generate': generate_ssh_key(request) # Read key data if it exists key = get_key_data() # Add host key if action == 'add-host': add_host_key(request) return render( request, "admin/ssh.html", { 'public_key': key, 'can_generate': can_generate, 'host_keys': get_host_keys(), 'ssh_docs': weblate.get_doc_url('admin/projects', 'private'), } )
def ssh(request): ''' Show information and manipulate with SSH key. ''' # Path to key, we default to RSA keys key_path = os.path.expanduser('~/.ssh/id_rsa.pub') # Check whether we can generate SSH key try: ret = os.system('which ssh-keygen > /dev/null 2>&1') can_generate = (ret == 0 and not os.path.exists(key_path)) except: can_generate = False # Generate key if it does not exist yet if can_generate and request.method == 'POST': try: ret = os.system('ssh-keygen -q -N \'\' -C Weblate -t rsa -f %s' % key_path[:-4]) if ret != 0: messages.error(request, _('Failed to generate key!')) else: messages.info(request, _('Created new SSH key.')) except: messages.error(request, _('Failed to generate key!')) # Read key data if it exists if os.path.exists(key_path): key_data = file(key_path).read() key_type, key_fingerprint, key_id = key_data.strip().split() key = { 'key': key_data, 'type': key_type, 'fingerprint': key_fingerprint, 'id': key_id, } else: key = None return render_to_response( "admin/ssh.html", RequestContext( request, { 'public_key': key, 'can_generate': can_generate, 'ssh_docs': weblate.get_doc_url('admin', 'private'), }))
def ssh(request): ''' Show information and manipulate with SSH key. ''' # Path to key, we default to RSA keys key_path = os.path.expanduser('~/.ssh/id_rsa.pub') # Check whether we can generate SSH key try: ret = os.system('which ssh-keygen > /dev/null 2>&1') can_generate = (ret == 0 and not os.path.exists(key_path)) except: can_generate = False # Generate key if it does not exist yet if can_generate and request.method == 'POST': try: ret = os.system( 'ssh-keygen -q -N \'\' -C Weblate -t rsa -f %s' % key_path[:-4] ) if ret != 0: messages.error(request, _('Failed to generate key!')) else: messages.info(request, _('Created new SSH key.')) except: messages.error(request, _('Failed to generate key!')) # Read key data if it exists if os.path.exists(key_path): key_data = file(key_path).read() key_type, key_fingerprint, key_id = key_data.strip().split() key = { 'key': key_data, 'type': key_type, 'fingerprint': key_fingerprint, 'id': key_id, } else: key = None return render_to_response("admin/ssh.html", RequestContext(request, { 'public_key': key, 'can_generate': can_generate, 'ssh_docs': weblate.get_doc_url('admin', 'private'), }))
class CheckFlagsForm(forms.Form): flags = forms.CharField( label=_('Check flags'), required=False, help_text=_( 'Please enter a comma separated list of check flags, ' 'see <a href="{url}">documentation</a> for more details.').format( url=weblate.get_doc_url('admin/checks', 'custom-checks'))) def clean_flags(self): """ Be a little bit more tolerant on whitespaces. """ flags = [ x.strip() for x in self.cleaned_data['flags'].strip().split(',') ] flags = ','.join([x for x in flags if x]) validate_check_flags(flags) return flags
def ssh(request): """ Show information and manipulate with SSH key. """ # Check whether we can generate SSH key try: ret = subprocess.check_call( ['which', 'ssh-keygen'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) can_generate = (ret == 0 and not os.path.exists(RSA_KEY_FILE)) except subprocess.CalledProcessError: can_generate = False if not os.access(os.path.expanduser('~'), os.W_OK): can_generate = False messages.error( request, _('Can not write to home directory, please check documentation.')) # Grab action type action = request.POST.get('action', None) # Generate key if it does not exist yet if can_generate and action == 'generate': generate_ssh_key(request) # Read key data if it exists key = get_key_data() # Add host key if action == 'add-host': add_host_key(request) return render( request, "admin/ssh.html", { 'public_key': key, 'can_generate': can_generate, 'host_keys': get_host_keys(), 'ssh_docs': weblate.get_doc_url('admin/projects', 'private'), })
def ssh(request): """ Show information and manipulate with SSH key. """ # Check whether we can generate SSH key can_generate = can_generate_key() if not is_home_writable(): can_generate = False messages.error( request, _('Can not write to home directory, please check documentation.') ) # Grab action type action = request.POST.get('action', None) # Generate key if it does not exist yet if can_generate and action == 'generate': generate_ssh_key(request) # Read key data if it exists key = get_key_data() # Add host key if action == 'add-host': add_host_key(request) return render( request, "admin/ssh.html", { 'public_key': key, 'can_generate': can_generate, 'host_keys': get_host_keys(), 'ssh_docs': weblate.get_doc_url('admin/projects', 'private'), } )
def documentation_icon(page, anchor='', right=False): return { 'right': right, 'doc_url': weblate.get_doc_url(page, anchor), }
def render(self, name, unit, attrs=None): ''' Renders all textareas with correct plural labels. ''' values = unit.get_target_plurals() lang = unit.translation.language tabindex = self.attrs['tabindex'] # Need to add extra class attrs['class'] = 'translation-editor form-control' attrs['tabindex'] = tabindex attrs['lang'] = lang.code attrs['dir'] = lang.direction attrs['rows'] = 3 # Okay we have more strings ret = [] base_id = 'id_{0}'.format(unit.checksum) for idx, val in enumerate(values): # Generate ID fieldname = '{0}_{1}'.format(name, idx) fieldid = '{0}_{1}'.format(base_id, idx) attrs['id'] = fieldid attrs['tabindex'] = tabindex + idx # Render textare textarea = super(PluralTextarea, self).render( fieldname, val, attrs ) # Label for plural if len(values) == 1: label = ugettext('Translation') else: label = lang.get_plural_label(idx) ret.append( EDITOR_TEMPLATE.format( self.get_toolbar(lang, fieldid, unit, idx), fieldid, label, textarea ) ) # Show plural equation for more strings pluralmsg = '' if len(values) > 1: pluralinfo = '<abbr title="{0}">{1}</abbr>: {2}'.format( ugettext( 'This equation identifies which plural form ' 'will be used based on given count (n).' ), ugettext('Plural equation'), lang.pluralequation ) pluralmsg = PLURALS_TEMPLATE.format( get_doc_url('user/translating', 'plurals'), ugettext('Documentation for plurals.'), pluralinfo ) # Join output return mark_safe(''.join(ret) + pluralmsg)
def doc_url(page, anchor=''): ''' Returns link to Weblate documentation. ''' return weblate.get_doc_url(page, anchor)
def documentation(page, anchor=""): """ Returns link to Weblate documentation. """ return weblate.get_doc_url(page, anchor)
def doc_url(page, anchor=''): """Return link to Weblate documentation.""" return weblate.get_doc_url(page, anchor)
def get_doc_url(self): ''' Returns link to documentation. ''' return weblate.get_doc_url('user/checks', self.doc_id)
def get_doc_url(self): """ Returns link to documentation. """ return weblate.get_doc_url("user/checks", self.doc_id)
def render(self, name, value, attrs=None, renderer=None, **kwargs): """Render all textareas with correct plural labels.""" unit = value values = unit.get_target_plurals() lang = unit.translation.language plural = unit.translation.plural tabindex = self.attrs['tabindex'] # Need to add extra class attrs['class'] = 'translation-editor form-control' attrs['tabindex'] = tabindex attrs['lang'] = lang.code attrs['dir'] = lang.direction attrs['rows'] = 3 attrs['maxlength'] = unit.get_max_length() # Okay we have more strings ret = [] base_id = 'id_{0}'.format(unit.checksum) for idx, val in enumerate(values): # Generate ID fieldname = '{0}_{1}'.format(name, idx) fieldid = '{0}_{1}'.format(base_id, idx) attrs['id'] = fieldid attrs['tabindex'] = tabindex + idx # Render textare textarea = super(PluralTextarea, self).render( fieldname, val, attrs, renderer, **kwargs ) # Label for plural if len(values) == 1: if unit.translation.is_template: label = ugettext('Source') else: label = ugettext('Translation') else: label = plural.get_plural_label(idx) if (not unit.translation.is_template and get_language() != lang.code): label += ' <span class="badge">{}</span>'.format(lang) ret.append( EDITOR_TEMPLATE.format( self.get_toolbar(lang, fieldid, unit, idx), fieldid, label, textarea ) ) # Show plural equation for more strings if len(values) > 1: ret.append( PLURALS_TEMPLATE.format( get_doc_url('user/translating', 'plurals'), ugettext('Documentation for plurals.'), '<abbr title="{0}">{1}</abbr>: {2}'.format( ugettext( 'This equation identifies which plural form ' 'will be used based on given count (n).' ), ugettext('Plural equation'), plural.equation ) ) ) # Join output return mark_safe(''.join(ret))
def get_doc_url(self): """Return link to documentation.""" return weblate.get_doc_url('user/checks', self.doc_id)
def ssh(request): """ Show information and manipulate with SSH key. """ # Check whether we can generate SSH key try: ret = subprocess.check_call(["which", "ssh-keygen"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) can_generate = ret == 0 and not os.path.exists(RSA_KEY_FILE) except: can_generate = False # Grab action type action = request.POST.get("action", None) # Generate key if it does not exist yet if can_generate and action == "generate": # Create directory if it does not exist key_dir = os.path.dirname(RSA_KEY_FILE) # Try generating key try: if not os.path.exists(key_dir): os.makedirs(key_dir) subprocess.check_output( ["ssh-keygen", "-q", "-N", "", "-C", "Weblate", "-t", "rsa", "-f", RSA_KEY_FILE[:-4]], stderr=subprocess.STDOUT, ) messages.info(request, _("Created new SSH key.")) except (subprocess.CalledProcessError, OSError) as exc: messages.error(request, _("Failed to generate key: %s") % getattr(exc, "output", str(exc))) # Read key data if it exists key = get_key_data() # Add host key if action == "add-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) keys = [line for line in output.splitlines() if " ssh-rsa " in line or " ecdsa-sha2-nistp256 " in line] for key in keys: 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}, ) with open(KNOWN_HOSTS_FILE, "a") as handle: for key in keys: handle.write("%s\n" % key) except (subprocess.CalledProcessError, OSError) as exc: messages.error(request, _("Failed to get host key: %s") % exc.output) return render( request, "admin/ssh.html", { "public_key": key, "can_generate": can_generate, "host_keys": get_host_keys(), "ssh_docs": weblate.get_doc_url("admin/projects", "private"), }, )
def ssh(request): ''' Show information and manipulate with SSH key. ''' # Path to key, we default to RSA keys key_path = os.path.expanduser('~/.ssh/id_rsa.pub') # Check whether we can generate SSH key try: ret = subprocess.check_call(['which', 'ssh-keygen']) can_generate = (ret == 0 and not os.path.exists(key_path)) except: can_generate = False # Grab action type action = request.POST.get('action', None) # Generate key if it does not exist yet if can_generate and action == 'generate': # Create directory if it does not exist key_dir = os.path.dirname(key_path) if not os.path.exists(key_dir): os.makedirs(key_dir) # Try generating key try: subprocess.check_output( [ 'ssh-keygen', '-q', '-N', '', '-C', 'Weblate', '-t', 'rsa', '-f', key_path[:-4] ], stderr=subprocess.STDOUT, ) messages.info(request, _('Created new SSH key.')) except subprocess.CalledProcessError as exc: messages.error( request, _('Failed to generate key: %s') % exc.output ) # Read key data if it exists if os.path.exists(key_path): key_data = file(key_path).read() key_type, key_fingerprint, key_id = key_data.strip().split(None, 2) key = { 'key': key_data, 'type': key_type, 'fingerprint': key_fingerprint, 'id': key_id, } else: key = None # Add host key if action == 'add-host': host = request.POST.get('host', '') if len(host) == 0: messages.error(request, _('Invalid host name given!')) else: output = subprocess.check_output(['ssh-keyscan', host]) keys = [ line for line in output.splitlines() if ' ssh-rsa ' in line ] for key in keys: host, fingerprint = parse_hosts_line(key) messages.warning( request, _( 'Added host key for %(host)s with fingerprint ' '%(fingerprint)s, please verify that it is correct.' ) % { 'host': host, 'fingerprint': fingerprint, } ) with open(os.path.expanduser('~/.ssh/known_hosts'), 'a') as handle: for key in keys: handle.write('%s\n' % key) return render_to_response("admin/ssh.html", RequestContext(request, { 'public_key': key, 'can_generate': can_generate, 'host_keys': get_host_keys(), 'ssh_docs': weblate.get_doc_url('admin', 'private'), }))
def ssh(request): ''' Show information and manipulate with SSH key. ''' # Check whether we can generate SSH key try: ret = subprocess.check_call( ['which', 'ssh-keygen'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) can_generate = (ret == 0 and not os.path.exists(RSA_KEY_FILE)) except: can_generate = False # Grab action type action = request.POST.get('action', None) # Generate key if it does not exist yet if can_generate and action == 'generate': # Create directory if it does not exist key_dir = os.path.dirname(RSA_KEY_FILE) # Try generating key try: if not os.path.exists(key_dir): os.makedirs(key_dir) subprocess.check_output( [ 'ssh-keygen', '-q', '-N', '', '-C', 'Weblate', '-t', 'rsa', '-f', RSA_KEY_FILE[:-4] ], stderr=subprocess.STDOUT, ) messages.info(request, _('Created new SSH key.')) except (subprocess.CalledProcessError, OSError) as exc: messages.error(request, _('Failed to generate key: %s') % exc.output) # Read key data if it exists if os.path.exists(RSA_KEY_FILE): key_data = file(RSA_KEY_FILE).read() key_type, key_fingerprint, key_id = key_data.strip().split(None, 2) key = { 'key': key_data, 'type': key_type, 'fingerprint': key_fingerprint, 'id': key_id, } else: key = None # Add host key if action == 'add-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, ) keys = [ line for line in output.splitlines() if ' ssh-rsa ' in line or ' ecdsa-sha2-nistp256 ' in line ] for key in keys: 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, }) with open(KNOWN_HOSTS_FILE, 'a') as handle: for key in keys: handle.write('%s\n' % key) except (subprocess.CalledProcessError, OSError) as exc: messages.error(request, _('Failed to get host key: %s') % exc.output) return render_to_response( "admin/ssh.html", RequestContext( request, { 'public_key': key, 'can_generate': can_generate, 'host_keys': get_host_keys(), 'ssh_docs': weblate.get_doc_url('admin/projects', 'private'), }))
def ssh(request): ''' Show information and manipulate with SSH key. ''' # Check whether we can generate SSH key try: ret = subprocess.check_call( ['which', 'ssh-keygen'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) can_generate = (ret == 0 and not os.path.exists(RSA_KEY_FILE)) except: can_generate = False # Grab action type action = request.POST.get('action', None) # Generate key if it does not exist yet if can_generate and action == 'generate': # Create directory if it does not exist key_dir = os.path.dirname(RSA_KEY_FILE) # Try generating key try: if not os.path.exists(key_dir): os.makedirs(key_dir) subprocess.check_output( [ 'ssh-keygen', '-q', '-N', '', '-C', 'Weblate', '-t', 'rsa', '-f', RSA_KEY_FILE[:-4] ], stderr=subprocess.STDOUT, ) messages.info(request, _('Created new SSH key.')) except (subprocess.CalledProcessError, OSError) as exc: messages.error( request, _('Failed to generate key: %s') % getattr(exc, 'output', str(exc)) ) # Read key data if it exists key = get_key_data() # Add host key if action == 'add-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, ) keys = [ line for line in output.splitlines() if ' ssh-rsa ' in line or ' ecdsa-sha2-nistp256 ' in line ] for key in keys: 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, } ) with open(KNOWN_HOSTS_FILE, 'a') as handle: for key in keys: handle.write('%s\n' % key) except (subprocess.CalledProcessError, OSError) as exc: messages.error( request, _('Failed to get host key: %s') % exc.output ) return render_to_response("admin/ssh.html", RequestContext(request, { 'public_key': key, 'can_generate': can_generate, 'host_keys': get_host_keys(), 'ssh_docs': weblate.get_doc_url('admin/projects', 'private'), }))