serializers.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.foundation.models import BizLog
  6. from apps.customer.tool import WechatHandel
  7. jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
  8. jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
  9. User = get_user_model()
  10. class WechatLoginSerializer(serializers.Serializer):
  11. def validate(self, attrs):
  12. code = self.initial_data.get('code') # 用户code
  13. appid = self.initial_data.get('appid') # 小程序appid
  14. activity_id = self.initial_data.get('activity_id') # 活动id
  15. if code and appid:
  16. customer_wechat, activity_id = WechatHandel.login(code, appid, activity_id)
  17. if not customer_wechat.customer:
  18. return {
  19. 'bind': 0,
  20. 'openid': customer_wechat.openid,
  21. 'activity_id': activity_id
  22. }
  23. user = customer_wechat.customer.user
  24. if not user.enabled:
  25. msg = '用户帐户已禁用.'
  26. raise serializers.ValidationError(msg)
  27. payload = jwt_payload_handler(user)
  28. BizLog.objects.addnew(user, BizLog.INSERT, u'用户微信登录,username=%s' % user.username)
  29. return {
  30. 'bind': 1,
  31. 'token': jwt_encode_handler(payload),
  32. 'openid': customer_wechat.openid,
  33. 'name': customer_wechat.customer.name or '',
  34. 'tel': customer_wechat.customer.tel or '',
  35. 'face': customer_wechat.customer.face or '',
  36. 'activity_id': activity_id,
  37. }
  38. else:
  39. msg = '参数无效'
  40. raise serializers.ValidationError(msg)
  41. class WechatBindSerializer(serializers.Serializer):
  42. def validate(self, attrs):
  43. appid = self.initial_data.get('appid')
  44. openid = self.initial_data.get('openid')
  45. phoneEncryptedData = self.initial_data.get('encryptedData')
  46. phoneIv = self.initial_data.get('iv')
  47. activity_id = self.initial_data.get('activity_id')
  48. if openid and phoneEncryptedData and phoneIv:
  49. customer = WechatHandel.bindWechat(appid, openid, phoneEncryptedData, phoneIv, activity_id)
  50. user = customer.user
  51. payload = jwt_payload_handler(user)
  52. BizLog.objects.addnew(user, BizLog.INSERT, u'用户微信登录,username=%s' % user.username)
  53. return {
  54. 'token': jwt_encode_handler(payload),
  55. 'name': customer.name or '',
  56. 'tel': customer.tel or '',
  57. 'face': customer.face or '',
  58. 'gender': customer.gender or 0,
  59. }
  60. else:
  61. msg = '参数无效'
  62. raise serializers.ValidationError(msg)