serializers.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # coding=utf-8
  2. from django.contrib.auth import get_user_model
  3. from rest_framework import serializers
  4. from rest_framework_jwt.settings import api_settings
  5. from apps.customer.models import *
  6. from apps.log.models import BizLog
  7. User = get_user_model()
  8. jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
  9. jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
  10. class WechatLoginSerializer(serializers.Serializer):
  11. def validate(self, attrs):
  12. code = self.initial_data.get('code')
  13. appid = self.initial_data.get('appid')
  14. if code and appid:
  15. wx_customer = CustomerWechat.login(code, appid)
  16. if not wx_customer.customer:
  17. return {
  18. 'bind': 0,
  19. 'openid': wx_customer.openid
  20. }
  21. user = wx_customer.customer.user
  22. if not user.is_active:
  23. msg = '用户帐户已禁用.'
  24. raise serializers.ValidationError(msg)
  25. payload = jwt_payload_handler(user)
  26. BizLog.objects.addnew(user, BizLog.INSERT, u'用户微信登录,username=%s' % user.username)
  27. return {
  28. 'bind': 1,
  29. 'token': jwt_encode_handler(payload),
  30. 'openid': wx_customer.openid,
  31. 'name': wx_customer.customer.name or '',
  32. 'tel': wx_customer.customer.tel or '',
  33. 'face': wx_customer.customer.face and wx_customer.customer.face.get_path() or '',
  34. 'gender': wx_customer.customer.gender or 0,
  35. }
  36. else:
  37. msg = '参数无效'
  38. raise serializers.ValidationError(msg)
  39. class WechatBindSerializer(serializers.Serializer):
  40. def validate(self, attrs):
  41. appid = self.initial_data.get('appid')
  42. openid = self.initial_data.get('openid')
  43. phoneEncryptedData = self.initial_data.get('encryptedData')
  44. phoneIv = self.initial_data.get('iv')
  45. if openid and phoneEncryptedData and phoneIv:
  46. customer = CustomerWechat.bindWechat(appid, openid, phoneEncryptedData, phoneIv)
  47. user = customer.user
  48. payload = jwt_payload_handler(user)
  49. BizLog.objects.addnew(user, BizLog.INSERT, u'用户微信登录,username=%s' % user.username)
  50. return {
  51. 'token': jwt_encode_handler(payload),
  52. 'name': customer.name or '',
  53. 'tel': customer.tel or '',
  54. 'face': customer.face and customer.face.get_path() or '',
  55. 'gender': customer.gender or 0
  56. }
  57. else:
  58. msg = '参数无效'
  59. raise serializers.ValidationError(msg)
  60. class CustomerSerializer(serializers.ModelSerializer):
  61. class Meta:
  62. model = Customer
  63. fields = '__all__'