serializers.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. 'user_id': customer_wechat.customer.id,
  38. }
  39. else:
  40. msg = '参数无效'
  41. raise serializers.ValidationError(msg)
  42. class WechatBindSerializer(serializers.Serializer):
  43. def validate(self, attrs):
  44. appid = self.initial_data.get('appid')
  45. openid = self.initial_data.get('openid')
  46. phoneEncryptedData = self.initial_data.get('encryptedData')
  47. phoneIv = self.initial_data.get('iv')
  48. activity_id = self.initial_data.get('activity_id')
  49. if openid and phoneEncryptedData and phoneIv:
  50. customer = WechatHandel.bindWechat(appid, openid, phoneEncryptedData, phoneIv, activity_id)
  51. user = customer.user
  52. payload = jwt_payload_handler(user)
  53. BizLog.objects.addnew(user, BizLog.INSERT, u'用户微信登录,username=%s' % user.username)
  54. return {
  55. 'token': jwt_encode_handler(payload),
  56. 'name': customer.name or '',
  57. 'tel': customer.tel or '',
  58. 'face': customer.face or '',
  59. 'gender': customer.gender or 0,
  60. 'user_id': customer.id,
  61. }
  62. else:
  63. msg = '参数无效'
  64. raise serializers.ValidationError(msg)