jumpserver/apps/users/views.py

533 lines
20 KiB
Python
Raw Normal View History

2016-08-14 09:21:04 +00:00
# ~*~ coding: utf-8 ~*~
2016-08-08 16:43:11 +00:00
2016-08-23 04:18:19 +00:00
from __future__ import unicode_literals
from django import forms
from django.conf import settings
2016-09-06 07:03:37 +00:00
from django.contrib.auth import login as auth_login, logout as auth_logout
2016-09-10 05:16:58 +00:00
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
2016-09-08 13:51:44 +00:00
from django.core.files.storage import default_storage
2016-09-15 03:19:36 +00:00
from django.http import HttpResponseRedirect
2016-09-19 13:08:08 +00:00
from django.shortcuts import reverse, redirect
2016-09-06 07:03:37 +00:00
from django.utils.decorators import method_decorator
2016-09-03 11:02:18 +00:00
from django.utils.translation import ugettext as _
2016-09-06 07:03:37 +00:00
from django.urls import reverse_lazy
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.base import TemplateView
2016-08-14 09:21:04 +00:00
from django.views.generic.list import ListView
2016-09-17 05:04:26 +00:00
from django.views.generic.edit import CreateView, DeleteView, UpdateView, FormView, SingleObjectMixin, \
2016-09-18 06:28:34 +00:00
FormMixin
2016-08-16 14:13:06 +00:00
from django.views.generic.detail import DetailView
2016-09-08 13:51:44 +00:00
from formtools.wizard.views import SessionWizardView
from common.mixins import JSONResponseMixin
2016-09-15 03:19:36 +00:00
from common.utils import get_object_or_none, get_logger
2016-11-10 08:59:50 +00:00
from perms.models import AssetPermission
2016-08-24 09:14:21 +00:00
from .models import User, UserGroup
from .utils import AdminUserRequiredMixin, user_add_success_next, send_reset_password_mail
2016-11-10 15:54:21 +00:00
from .hands import write_login_log_async
2016-11-09 15:49:10 +00:00
from . import forms
2016-08-25 11:29:59 +00:00
2016-09-16 17:04:52 +00:00
2016-09-15 03:19:36 +00:00
logger = get_logger(__name__)
2016-08-26 08:56:50 +00:00
2016-09-06 07:03:37 +00:00
@method_decorator(sensitive_post_parameters(), name='dispatch')
@method_decorator(csrf_protect, name='dispatch')
@method_decorator(never_cache, name='dispatch')
class UserLoginView(FormView):
template_name = 'users/login.html'
2016-11-09 15:49:10 +00:00
form_class = forms.UserLoginForm
2016-09-06 07:03:37 +00:00
redirect_field_name = 'next'
def get(self, request, *args, **kwargs):
if request.user.is_staff:
2016-09-08 11:30:22 +00:00
return redirect(self.get_success_url())
return super(UserLoginView, self).get(request, *args, **kwargs)
2016-09-06 07:03:37 +00:00
def form_valid(self, form):
auth_login(self.request, form.get_user())
2016-11-10 15:54:21 +00:00
login_ip = self.request.META.get('REMOTE_ADDR', '')
user_agent = self.request.META.get('HTTP_USER_AGENT', '')
write_login_log_async.delay(self.request.user.username, self.request.user.name,
login_type='W', login_ip=login_ip, user_agent=user_agent)
2016-09-08 11:30:22 +00:00
return redirect(self.get_success_url())
def get_success_url(self):
2016-09-08 13:51:44 +00:00
if self.request.user.is_first_login:
2016-09-10 05:16:58 +00:00
return reverse('users:user-first-login')
2016-09-08 13:51:44 +00:00
2016-09-08 11:30:22 +00:00
return self.request.POST.get(
self.redirect_field_name,
self.request.GET.get(self.redirect_field_name, reverse('index')))
2016-09-06 07:03:37 +00:00
@method_decorator(never_cache, name='dispatch')
class UserLogoutView(TemplateView):
2016-11-09 11:29:15 +00:00
template_name = 'flash_message_standalone.html'
2016-09-06 07:03:37 +00:00
def get(self, request, *args, **kwargs):
auth_logout(request)
return super(UserLogoutView, self).get(request)
def get_context_data(self, **kwargs):
context = {
'title': _('Logout success'),
'messages': _('Logout success, return login page'),
'redirect_url': reverse('users:login'),
'auto_redirect': True,
}
kwargs.update(context)
return super(UserLogoutView, self).get_context_data(**kwargs)
2016-09-26 08:33:10 +00:00
class UserListView(AdminUserRequiredMixin, TemplateView):
template_name = 'users/user_list.html'
2016-08-14 09:21:04 +00:00
def get_context_data(self, **kwargs):
context = super(UserListView, self).get_context_data(**kwargs)
2016-09-26 08:33:10 +00:00
context.update({'app': _('Users'), 'action': _('User list'), 'groups': UserGroup.objects.all()})
2016-08-14 09:21:04 +00:00
return context
2016-08-14 11:18:41 +00:00
class UserCreateView(AdminUserRequiredMixin, SuccessMessageMixin, CreateView):
2016-08-14 11:18:41 +00:00
model = User
2016-11-09 15:49:10 +00:00
form_class = forms.UserCreateUpdateForm
template_name = 'users/user_create.html'
success_url = reverse_lazy('users:user-list')
2016-09-08 10:12:53 +00:00
success_message = _('Create user <a href="%s">%s</a> successfully.')
def get_context_data(self, **kwargs):
context = super(UserCreateView, self).get_context_data(**kwargs)
2016-09-03 16:51:36 +00:00
context.update({'app': _('Users'), 'action': _('Create user')})
return context
2016-08-14 11:18:41 +00:00
def form_valid(self, form):
2016-08-24 09:14:21 +00:00
user = form.save(commit=False)
user.created_by = self.request.user.username or 'System'
2016-08-16 14:13:06 +00:00
user.save()
2016-08-31 17:12:02 +00:00
user_add_success_next(user)
return super(UserCreateView, self).form_valid(form)
2016-08-23 04:18:19 +00:00
def get_success_message(self, cleaned_data):
return self.success_message % (
reverse_lazy('users:user-detail', kwargs={'pk': self.object.pk}),
self.object.name,
)
2016-08-28 15:58:22 +00:00
class UserUpdateView(AdminUserRequiredMixin, UpdateView):
model = User
2016-11-09 15:49:10 +00:00
form_class = forms.UserCreateUpdateForm
template_name = 'users/user_update.html'
2016-09-18 13:00:07 +00:00
context_object_name = 'user_object'
success_url = reverse_lazy('users:user-list')
def form_valid(self, form):
2016-08-17 14:17:16 +00:00
username = self.object.username
user = form.save(commit=False)
user.username = username
user.save()
2016-08-16 14:13:06 +00:00
password = self.request.POST.get('password', '')
if password:
user.set_password(password)
return super(UserUpdateView, self).form_valid(form)
2016-08-16 14:13:06 +00:00
def get_context_data(self, **kwargs):
context = super(UserUpdateView, self).get_context_data(**kwargs)
2016-09-06 07:09:00 +00:00
context.update({'app': _('Users'), 'action': _('Update user')})
return context
2016-08-16 14:13:06 +00:00
2016-08-28 15:58:22 +00:00
class UserDetailView(AdminUserRequiredMixin, DetailView):
2016-08-16 14:13:06 +00:00
model = User
template_name = 'users/user_detail.html'
2016-11-09 11:29:15 +00:00
context_object_name = "user"
2016-08-16 16:23:52 +00:00
def get_context_data(self, **kwargs):
groups = UserGroup.objects.exclude(id__in=self.object.groups.all())
2016-09-04 11:05:47 +00:00
context = {'app': _('Users'), 'action': _('User detail'), 'groups': groups}
kwargs.update(context)
return super(UserDetailView, self).get_context_data(**kwargs)
2016-08-18 17:39:08 +00:00
class UserGroupListView(AdminUserRequiredMixin, TemplateView):
template_name = 'users/user_group_list.html'
2016-08-18 17:39:08 +00:00
def get_context_data(self, **kwargs):
context = super(UserGroupListView, self).get_context_data(**kwargs)
context.update({'app': _('Users'), 'action': _('User group list')})
2016-08-18 17:39:08 +00:00
return context
class UserGroupCreateView(AdminUserRequiredMixin, CreateView):
2016-08-18 17:39:08 +00:00
model = UserGroup
2016-11-09 15:49:10 +00:00
form_class = forms.UserGroupForm
2016-11-15 11:33:04 +00:00
template_name = 'users/user_group_create_update.html'
success_url = reverse_lazy('users:user-group-list')
2016-08-18 17:39:08 +00:00
def get_context_data(self, **kwargs):
context = super(UserGroupCreateView, self).get_context_data(**kwargs)
2016-08-18 17:39:08 +00:00
users = User.objects.all()
context.update({'app': _('Users'), 'action': _('Create user group'), 'users': users})
2016-08-18 17:39:08 +00:00
return context
def form_valid(self, form):
user_group = form.save()
2016-08-18 17:39:08 +00:00
users_id_list = self.request.POST.getlist('users', [])
2016-09-19 13:08:08 +00:00
users = User.objects.filter(id__in=users_id_list)
user_group.created_by = self.request.user.username or 'Admin'
2016-09-19 13:08:08 +00:00
user_group.users.add(*users)
user_group.save()
return super(UserGroupCreateView, self).form_valid(form)
2016-08-18 17:39:08 +00:00
2016-09-19 13:08:08 +00:00
class UserGroupUpdateView(AdminUserRequiredMixin, UpdateView):
model = UserGroup
2016-11-09 15:49:10 +00:00
form_class = forms.UserGroupForm
2016-11-15 11:33:04 +00:00
template_name = 'users/user_group_create_update.html'
2016-09-19 13:08:08 +00:00
success_url = reverse_lazy('users:user-group-list')
def get_context_data(self, **kwargs):
2016-11-15 11:33:04 +00:00
# self.object = self.get_object()
2016-09-19 13:08:08 +00:00
context = super(UserGroupUpdateView, self).get_context_data(**kwargs)
users = User.objects.all()
2016-11-15 11:33:04 +00:00
group_users = [user.id for user in self.object.users.all()]
2016-09-19 13:08:08 +00:00
context.update({
'app': _('Users'),
'action': _('Update User Group'),
'users': users,
'group_users': group_users
})
return context
def form_valid(self, form):
user_group = form.save()
users_id_list = self.request.POST.getlist('users', [])
users = User.objects.filter(id__in=users_id_list)
user_group.users.clear()
user_group.users.add(*users)
user_group.save()
return super(UserGroupUpdateView, self).form_valid(form)
2016-08-18 17:39:08 +00:00
2016-09-18 13:00:07 +00:00
class UserGroupDetailView(AdminUserRequiredMixin, DetailView):
model = UserGroup
2016-11-14 16:48:48 +00:00
context_object_name = 'user_group'
2016-09-18 13:00:07 +00:00
template_name = 'users/user_group_detail.html'
def get_context_data(self, **kwargs):
2016-11-14 16:48:48 +00:00
users = User.objects.exclude(id__in=self.object.users.all())
context = {
'app': _('Users'),
'action': _('User Group Detail'),
'users': users,
}
2016-09-18 13:00:07 +00:00
kwargs.update(context)
return super(UserGroupDetailView, self).get_context_data(**kwargs)
2016-08-18 17:39:08 +00:00
class UserGroupDeleteView(DeleteView):
pass
2016-08-31 12:39:25 +00:00
2016-09-06 07:09:00 +00:00
class UserForgotPasswordView(TemplateView):
template_name = 'users/forgot_password.html'
2016-08-31 12:39:25 +00:00
2016-09-15 03:19:36 +00:00
def post(self, request):
2016-09-01 15:09:58 +00:00
email = request.POST.get('email')
user = get_object_or_none(User, email=email)
if not user:
2016-09-03 16:51:36 +00:00
return self.get(request, errors=_('Email address invalid, input again'))
2016-09-01 15:09:58 +00:00
else:
send_reset_password_mail(user)
2016-09-06 07:09:00 +00:00
return HttpResponseRedirect(reverse('users:forgot-password-sendmail-success'))
2016-08-31 12:39:25 +00:00
2016-09-01 15:09:58 +00:00
2016-09-06 07:09:00 +00:00
class UserForgotPasswordSendmailSuccessView(TemplateView):
2016-11-09 11:29:15 +00:00
template_name = 'flash_message_standalone.html'
2016-09-01 15:09:58 +00:00
def get_context_data(self, **kwargs):
context = {
2016-09-03 16:51:36 +00:00
'title': _('Send reset password message'),
'messages': _('Send reset password mail success, login your mail box and follow it '),
2016-09-01 15:09:58 +00:00
'redirect_url': reverse('users:login'),
}
kwargs.update(context)
2016-09-06 07:09:00 +00:00
return super(UserForgotPasswordSendmailSuccessView, self).get_context_data(**kwargs)
2016-09-01 15:09:58 +00:00
class UserResetPasswordSuccessView(TemplateView):
2016-11-09 11:29:15 +00:00
template_name = 'flash_message_standalone.html'
2016-09-01 15:09:58 +00:00
def get_context_data(self, **kwargs):
context = {
2016-09-03 16:51:36 +00:00
'title': _('Reset password success'),
'messages': _('Reset password success, return to login page'),
2016-09-01 15:09:58 +00:00
'redirect_url': reverse('users:login'),
2016-09-02 16:39:06 +00:00
'auto_redirect': True,
2016-09-01 15:09:58 +00:00
}
kwargs.update(context)
return super(UserResetPasswordSuccessView, self).get_context_data(**kwargs)
class UserResetPasswordView(TemplateView):
template_name = 'users/reset_password.html'
2016-09-02 10:10:26 +00:00
def get(self, request, *args, **kwargs):
token = request.GET.get('token')
user = User.validate_reset_token(token)
if not user:
2016-09-03 16:51:36 +00:00
kwargs.update({'errors': _('Token invalid or expired')})
2016-09-02 10:10:26 +00:00
return super(UserResetPasswordView, self).get(request, *args, **kwargs)
2016-09-01 15:09:58 +00:00
def post(self, request, *args, **kwargs):
password = request.POST.get('password')
password_confirm = request.POST.get('password-confirm')
token = request.GET.get('token')
if password != password_confirm:
2016-09-03 16:51:36 +00:00
return self.get(request, errors=_('Password not same'))
2016-09-01 15:09:58 +00:00
2016-09-02 10:10:26 +00:00
user = User.validate_reset_token(token)
if not user:
2016-09-03 16:51:36 +00:00
return self.get(request, errors=_('Token invalid or expired'))
2016-09-01 15:09:58 +00:00
2016-09-02 10:10:26 +00:00
user.reset_password(password)
2016-09-01 15:09:58 +00:00
return HttpResponseRedirect(reverse('users:reset-password-success'))
2016-09-08 13:51:44 +00:00
2016-09-10 05:16:58 +00:00
class UserFirstLoginView(LoginRequiredMixin, SessionWizardView):
2016-09-08 13:51:44 +00:00
template_name = 'users/first_login.html'
2016-11-09 15:49:10 +00:00
form_list = [forms.UserInfoForm, forms.UserKeyForm]
2016-09-08 13:51:44 +00:00
file_storage = default_storage
2016-09-10 05:16:58 +00:00
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated() and not request.user.is_first_login:
return redirect(reverse('index'))
return super(UserFirstLoginView, self).dispatch(request, *args, **kwargs)
2016-09-08 13:51:44 +00:00
def done(self, form_list, form_dict, **kwargs):
2016-09-10 05:16:58 +00:00
user = self.request.user
for form in form_list:
for field in form:
if field.value():
setattr(user, field.name, field.value())
if field.name == 'enable_otp':
user.enable_otp = field.value()
user.is_first_login = False
2016-09-18 06:28:34 +00:00
user.is_public_key_valid = True
2016-09-10 05:16:58 +00:00
user.save()
2016-09-08 13:51:44 +00:00
return redirect(reverse('index'))
def get_context_data(self, **kwargs):
context = super(UserFirstLoginView, self).get_context_data(**kwargs)
context.update({'app': _('Users'), 'action': _('First Login')})
return context
2016-09-10 05:16:58 +00:00
def get_form_initial(self, step):
user = self.request.user
if step == '0':
return {
'name': user.name or user.username,
'enable_otp': user.enable_otp or True,
'wechat': user.wechat or '',
'phone': user.phone or ''
}
return super(UserFirstLoginView, self).get_form_initial(step)
2016-09-16 17:04:52 +00:00
2016-09-18 06:28:34 +00:00
def get_form(self, step=None, data=None, files=None):
form = super(UserFirstLoginView, self).get_form(step, data, files)
if step is None:
step = self.steps.current
if step == '1':
form.user = self.request.user
return form
2016-09-16 17:04:52 +00:00
2016-11-10 14:06:23 +00:00
class UserAssetPermissionView(AdminUserRequiredMixin, FormMixin, SingleObjectMixin, ListView):
2016-11-10 08:59:50 +00:00
model = User
2016-09-16 17:04:52 +00:00
template_name = 'users/user_asset_permission.html'
2016-11-10 08:59:50 +00:00
context_object_name = 'user'
2016-11-10 14:06:23 +00:00
form_class = forms.UserPrivateAssetPermissionForm
2016-11-10 08:59:50 +00:00
2016-11-10 14:06:23 +00:00
def get(self, request, *args, **kwargs):
self.object = self.get_object(queryset=User.objects.all())
return super(UserAssetPermissionView, self).get(request, *args, **kwargs)
2016-09-16 17:04:52 +00:00
def get_context_data(self, **kwargs):
context = {
'app': 'Users',
'action': 'User asset permissions',
}
kwargs.update(context)
return super(UserAssetPermissionView, self).get_context_data(**kwargs)
2016-11-15 11:33:04 +00:00
class UserGroupAssetPermissionView(AdminUserRequiredMixin, FormMixin, SingleObjectMixin, ListView):
model = UserGroup
template_name = 'users/user_group_asset_permission.html'
context_object_name = 'user_group'
form_class = forms.UserPrivateAssetPermissionForm
def get(self, request, *args, **kwargs):
self.object = self.get_object(queryset=UserGroup.objects.all())
return super(UserGroupAssetPermissionView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = {
'app': 'Users',
'action': 'User group asset permissions',
}
kwargs.update(context)
return super(UserGroupAssetPermissionView, self).get_context_data(**kwargs)
2016-09-16 17:04:52 +00:00
class UserAssetPermissionCreateView(AdminUserRequiredMixin, CreateView):
2016-11-09 15:49:10 +00:00
form_class = forms.UserPrivateAssetPermissionForm
2016-09-17 05:04:26 +00:00
model = AssetPermission
def get(self, request, *args, **kwargs):
2016-11-15 11:33:04 +00:00
user = self.get_object(queryset=User.objects.all())
return redirect(reverse('users:user-asset-permission', kwargs={'pk': user.id}))
2016-09-17 05:04:26 +00:00
def post(self, request, *args, **kwargs):
2016-11-15 11:33:04 +00:00
self.user = self.get_object(queryset=User.objects.all())
2016-09-17 05:04:26 +00:00
return super(UserAssetPermissionCreateView, self).post(request, *args, **kwargs)
def get_form(self, form_class=None):
form = super(UserAssetPermissionCreateView, self).get_form(form_class=form_class)
2016-11-15 11:33:04 +00:00
form.user = self.user
return form
def form_invalid(self, form):
return redirect(reverse('users:user-asset-permission', kwargs={'pk': self.user.id}))
def get_success_url(self):
return reverse('users:user-asset-permission', kwargs={'pk': self.user.id})
class UserGroupAssetPermissionCreateView(AdminUserRequiredMixin, CreateView):
2016-11-15 15:09:36 +00:00
form_class = forms.UserGroupPrivateAssetPermissionForm
2016-11-15 11:33:04 +00:00
model = AssetPermission
def get(self, request, *args, **kwargs):
user_group = self.get_object(queryset=UserGroup.objects.all())
return redirect(reverse('users:user-group-asset-permission', kwargs={'pk': user_group.id}))
def post(self, request, *args, **kwargs):
self.user_group = self.get_object(queryset=UserGroup.objects.all())
return super(UserGroupAssetPermissionCreateView, self).post(request, *args, **kwargs)
def get_form(self, form_class=None):
form = super(UserGroupAssetPermissionCreateView, self).get_form(form_class=form_class)
form.user_group = self.user_group
2016-09-17 05:04:26 +00:00
return form
def form_invalid(self, form):
2016-11-15 11:33:04 +00:00
return redirect(reverse('users:user-group-asset-permission', kwargs={'pk': self.user_group.id}))
2016-09-17 05:04:26 +00:00
def get_success_url(self):
2016-11-15 11:33:04 +00:00
return reverse('users:user-group-asset-permission', kwargs={'pk': self.user_group.id})
2016-09-17 05:04:26 +00:00
2016-09-17 07:20:33 +00:00
2016-11-10 14:06:23 +00:00
class UserGrantedAssetView(AdminUserRequiredMixin, DetailView):
model = User
2016-09-17 07:20:33 +00:00
template_name = 'users/user_granted_asset.html'
2016-11-10 14:06:23 +00:00
context_object_name = 'user'
2016-09-17 07:20:33 +00:00
def get(self, request, *args, **kwargs):
self.object = self.get_object(queryset=User.objects.all())
return super(UserGrantedAssetView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = {
'app': 'User',
'action': 'User granted asset',
}
kwargs.update(context)
return super(UserGrantedAssetView, self).get_context_data(**kwargs)
2016-11-15 11:33:04 +00:00
class UserGroupGrantedAssetView(AdminUserRequiredMixin, DetailView):
model = User
template_name = 'users/user_group_granted_asset.html'
context_object_name = 'user_group'
def get(self, request, *args, **kwargs):
self.object = self.get_object(queryset=UserGroup.objects.all())
return super(UserGroupGrantedAssetView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = {
'app': 'User',
'action': 'User group granted asset',
}
kwargs.update(context)
return super(UserGroupGrantedAssetView, self).get_context_data(**kwargs)
class BulkImportUserView(AdminUserRequiredMixin, JSONResponseMixin, FormView):
2016-11-09 15:49:10 +00:00
form_class = forms.FileForm
def form_invalid(self, form):
try:
error = form.errors.values()[-1][-1]
except Exception as e:
print e
error = _('Invalid file.')
data = {
'success': False,
'msg': error
}
return self.render_json_response(data)
def form_valid(self, form):
from openpyxl import load_workbook
try:
wb = load_workbook(form.cleaned_data['excel'])
ws = wb['users']
except Exception as e:
print e
error = _('Not a valid Excel file.')
data = {
'success': False,
'msg': error
}
return self.render_json_response(data)
errors = []
for index, row in enumerate(ws.rows):
user_data = [cell.value for cell in row]
if len(user_data) != 4:
errors.append("Row {}: invalid user data format.".format(index))
continue
username, email, enable_otp, role = user_data
data = {
'username': username,
'email': email,
'enable_otp': True if enable_otp in ['T', '1', 1, True] else False,
'role': role
}
2016-11-09 15:49:10 +00:00
form = forms.UserBulkImportForm(data, auto_id=False)
if form.is_valid():
form.save()
else:
form_errors = form.errors.as_data()
for key, err_list in form_errors.iteritems():
error_line = "{} :".format(key)
for errs in err_list:
error_line = "{}{}".format(error_line, ";".join([err for err in errs.messages]))
errors.append("Row {}: {}".format(index, error_line))
data = {
'success': True if not errors else False,
'msg': 'ok' if not errors else '<br />'.join(errors)
}
return self.render_json_response(data)