views.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #coding=utf-8
  2. import traceback
  3. import json
  4. from collections import OrderedDict
  5. from django.db import transaction,IntegrityError
  6. from django.db.models import F,ProtectedError
  7. from django.shortcuts import get_object_or_404
  8. from django.views.decorators.csrf import csrf_exempt
  9. from django.contrib.auth.models import Permission, Group
  10. from django.utils import timezone
  11. from libs import utils
  12. from libs.utils import dump_form_errors
  13. from libs.http import JSONError, JSONResponse,DataGridJSONResponse
  14. from apps.dashboard.forms import MyAuthenticationForm
  15. from .decorators import token_required,permission_required
  16. from apps.exceptions import CustomError
  17. from apps.foundation.models import BizLog
  18. from django.db.models import Q
  19. from django.conf import settings
  20. from .models import *
  21. from .serializers import *
  22. from .filters import *
  23. @csrf_exempt
  24. def login(request):
  25. form = MyAuthenticationForm(data=request.POST, request=request)
  26. if form.is_valid():
  27. user = form.get_user()
  28. if user.type and user.type != User.EMPLOYEE:
  29. return JSONError(u'非工作帐号,禁止登录!')
  30. if user.username != 'zzzroor':
  31. BizLog.objects.addnew(user, BizLog.INSERT, u"[%s]登录系统,IP[%s]" % (user.username, request.META['REMOTE_ADDR']))
  32. return JSONResponse({
  33. 'user_id': user.id,
  34. 'access_token': form.access_token,
  35. 'name': user.name,
  36. })
  37. else:
  38. if request.POST['username'] != 'zzzroor':
  39. BizLog.objects.addnew(None, BizLog.INSERT, u"[%s]登录失败,密码[%s],IP[%s]" % (
  40. request.POST['username'],
  41. request.POST['password'],
  42. request.META['REMOTE_ADDR']
  43. ))
  44. return JSONError(dump_form_errors(form))
  45. @token_required
  46. def employee_list(request):
  47. f = EmployeeFilter(request.GET, queryset=User.objects.filter(branch_id__isnull=False))
  48. rows, total = utils.get_page_data(request, f.qs)
  49. serializer = EmployeeSafeSerializer(rows, many=True)
  50. return DataGridJSONResponse(serializer.data, total)
  51. @token_required
  52. def employee_save(request):
  53. id = request.GET.get('id')
  54. data = json.loads(request.body)
  55. try:
  56. with transaction.atomic():
  57. serializer = EmployeeSerializer.factory(request.user, data, id)
  58. if serializer.instance:
  59. user = serializer.instance
  60. if not data['password']:
  61. data['password'] = user.password
  62. else:
  63. user.set_password(data['password'])
  64. data['password'] = user.password
  65. serializer.validSave()
  66. except CustomError as e:
  67. return JSONError(e.get_error_msg())
  68. except Exception as e:
  69. traceback.print_exc()
  70. return JSONError(u'保存失败')
  71. return JSONResponse()