Bump version to 0.10.2
[ganeti_webmgr.git] / muddle_users / views / group.py
blobfb93b63a7058c9f2e2fbcae41fa5c6d7d9023e8b
1 import json
3 from django import forms
4 from django.contrib.auth.decorators import login_required
5 from django.contrib.auth.models import User, Group
6 from django.core.urlresolvers import reverse
7 from django.http import HttpResponse, HttpResponseForbidden, \
8 HttpResponseNotAllowed, HttpResponseRedirect
9 from django.shortcuts import get_object_or_404, render_to_response
10 from django.template import RequestContext
12 from object_permissions.signals import view_add_user, view_remove_user
14 from muddle_users.signals import (view_group_edited, view_group_created,
15 view_group_deleted)
18 class GroupForm(forms.ModelForm):
19 """
20 Form for editing Groups
21 """
22 class Meta:
23 model = Group
26 class UserForm(forms.Form):
27 """
28 Base form for dealing with users
29 """
30 group = None
31 user = forms.ModelChoiceField(queryset=User.objects.all())
33 def __init__(self, group=None, *args, **kwargs):
34 self.group=group
35 super(UserForm, self).__init__(*args, **kwargs)
38 class AddUserForm(UserForm):
39 def clean_user(self):
40 """ Validate that user is not in group already """
41 user = self.cleaned_data['user']
42 if self.group.user_set.filter(id=user.id).exists():
43 raise forms.ValidationError("User is already a member of this group")
44 return user
47 class RemoveUserForm(UserForm):
48 def clean_user(self):
49 """ Validate that user is in group """
50 user = self.cleaned_data['user']
51 if not self.group.user_set.filter(id=user.id).exists():
52 raise forms.ValidationError("User is not a member of this group")
53 return user
56 @login_required
57 def list(request, template='group/list.html'):
58 """
59 List all user groups.
60 """
61 user = request.user
62 if request.user.is_superuser:
63 groups = Group.objects.all()
64 else:
65 groups = user.get_objects_any_perms(Group, ['admin'])
66 if not groups:
67 return HttpResponseForbidden()
69 return render_to_response(template,
70 {'groups':groups},
71 context_instance=RequestContext(request))
74 @login_required
75 def detail(request, id=None, template='group/detail.html'):
76 """
77 Display group details
79 @param id: id of Group
80 """
81 group = get_object_or_404(Group, id=id) if id else None
82 user = request.user
84 if not (user.is_superuser or user.has_perm('admin', group)):
85 return HttpResponseForbidden()
87 return render_to_response(template,
88 {'object':group,
89 'group':group,
90 'users':group.user_set.all(),
91 'url':reverse('group-permissions', args=[id])
93 context_instance=RequestContext(request))
96 @login_required
97 def edit(request, id=None, template="group/edit.html"):
98 """
99 Edit a group
101 @param id: id of group to edit, or None for a new group
102 @param template: template used for rendering a form
104 group = get_object_or_404(Group, id=id) if id else None
105 user = request.user
107 if not (user.is_superuser or user.has_perm('admin', group)):
108 return HttpResponseForbidden()
110 method = request.method
111 if method == 'POST':
112 # form data, this was a submission
113 form = GroupForm(request.POST, instance=group)
114 if form.is_valid():
115 group = form.save()
116 if not id:
117 view_group_created.send(sender=group, editor=user)
118 else:
119 view_group_edited.send(sender=group, editor=user)
121 return HttpResponseRedirect(group.get_absolute_url())
123 elif method == 'DELETE':
124 group.delete()
125 view_group_deleted.send(sender=group, editor=user)
126 return HttpResponse('1', mimetype='application/json')
128 else:
129 form = GroupForm(instance=group)
131 return render_to_response(template, {
132 'form':form,
133 'group':group,
135 context_instance=RequestContext(request),
139 @login_required
140 def add_user(request, id, user_row_template='group/user_row.html'):
142 ajax call to add a user to a Group
144 @param id: id of Group
146 editor = request.user
147 group = get_object_or_404(Group, id=id)
149 if not (editor.is_superuser or editor.has_perm('admin', group)):
150 return HttpResponseForbidden('You do not have sufficient privileges')
152 if request.method == 'POST':
153 form = AddUserForm(group, request.POST)
154 if form.is_valid():
155 user = form.cleaned_data['user']
156 group.user_set.add(user)
158 # signal
159 view_add_user.send(sender=editor, user=user, obj=group)
161 # return html for new user row
162 url = reverse('group-permissions', args=[id])
163 return render_to_response(
164 user_row_template,
165 {'user_detail':user, 'object':group, 'url':url},
166 context_instance=RequestContext(request))
168 # error in form return ajax response
169 content = json.dumps(form.errors)
170 return HttpResponse(content, mimetype='application/json')
172 form = AddUserForm()
173 return render_to_response("group/add_user.html",
174 {'form':form, 'group':group},
175 context_instance=RequestContext(request))
178 @login_required
179 def remove_user(request, id):
181 Ajax call to remove a user from an Group
183 @param id: id of Group
185 editor = request.user
186 group = get_object_or_404(Group, id=id)
188 if not (editor.is_superuser or editor.has_perm('admin', group)):
189 return HttpResponseForbidden('You do not have sufficient privileges')
191 if request.method != 'POST':
192 return HttpResponseNotAllowed('GET')
194 form = RemoveUserForm(group, request.POST)
195 if form.is_valid():
196 user = form.cleaned_data['user']
197 group.user_set.remove(user)
198 user.revoke_all(group)
200 # signal
201 view_remove_user.send(sender=editor, user=user, obj=group)
203 # return success
204 return HttpResponse('1', mimetype='application/json')
206 # error in form return ajax response
207 content = json.dumps(form.errors)
208 return HttpResponse(content, mimetype='application/json')