define readonly fields and own delete action for SSH key admin

- implement custom perform_delete_selected action for SshPublicKeyAdmin that
  ensures that the authorized_keys files of all affected users are rebuilt
  after deleting keys
- implement custom get_actions to replace the default delete_selected action
  with the custom perform_delete_selected
- define get_readonly_fields to make sure that the key algorithm and data
  cannot be changed
This commit is contained in:
Jan Dittberner 2015-01-31 23:39:09 +01:00
parent 7dd4c78345
commit b993053d2a

View file

@ -6,9 +6,12 @@ from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from fileservertasks.tasks import set_file_ssh_authorized_keys
from gvawebcore.forms import (
PASSWORD_MISMATCH_ERROR
)
from taskresults.models import TaskResult
from .models import (
AdditionalGroup,
Group,
@ -278,6 +281,7 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
<osusers.models.SshPublicKey>`.
"""
actions = ['perform_delete_selected']
add_form = SshPublicKeyCreationForm
list_display = ['user', 'algorithm', 'comment']
@ -310,6 +314,67 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
return super(SshPublicKeyAdmin, self).get_form(
request, obj, **defaults)
def get_readonly_fields(self, request, obj=None):
"""
Make sure that algorithm and data of SSH public keys are not editable.
:param request: the current HTTP request
:param obj: either a :py:class:`SshPublicKey
<osusers.models.SshPublicKey>` instance or None for a new SSH
public key
:return: a list of fields
:rtype: list
"""
if obj:
return ['algorithm', 'data']
return []
def perform_delete_selected(self, request, queryset):
"""
Action to delete a list of selected ssh keys.
This action makes sure that the ssh keys of all users affected by the
current deletion are refreshed on the file server.
:param request: the current HTTP request
:param queryset: Django ORM queryset representing the selected ssh keys
"""
users = set([
item['user'] for item in
queryset.values('user').distinct()
])
queryset.delete()
for user in users:
TaskResult.objects.create_task_result(
set_file_ssh_authorized_keys.delay(
User.objects.get(uid=user).username, [
str(key) for key in SshPublicKey.objects.filter(
user_id=user)
]),
'set_file_ssh_authorized_keys'
)
perform_delete_selected.short_description = _(
'Delete selected SSH public keys')
def get_actions(self, request):
"""
Get the available actions for SSH public keys.
This overrides the default behavior to remove the default
`delete_selected` action.
:param request: the current HTTP request
:return: list of actions
:rtype: list
"""
actions = super(SshPublicKeyAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
admin.site.register(Group, GroupAdmin)
admin.site.register(User, UserAdmin)