login-by-apple.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const {
  2. initApple
  3. } = require('../../lib/third-party/index')
  4. const {
  5. ERROR
  6. } = require('../../common/error')
  7. const {
  8. preUnifiedLogin,
  9. postUnifiedLogin
  10. } = require('../../lib/utils/unified-login')
  11. const {
  12. LOG_TYPE
  13. } = require('../../common/constants')
  14. /**
  15. * 苹果登录
  16. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#login-by-apple
  17. * @param {Object} params
  18. * @param {String} params.identityToken 苹果登录返回的identityToken
  19. * @param {String} params.nickname 用户昵称
  20. * @param {String} params.inviteCode 邀请码
  21. * @returns
  22. */
  23. module.exports = async function (params = {}) {
  24. const schema = {
  25. identityToken: 'string',
  26. nickname: {
  27. required: false,
  28. type: 'nickname'
  29. },
  30. inviteCode: {
  31. required: false,
  32. type: 'string'
  33. }
  34. }
  35. this.middleware.validate(params, schema)
  36. const {
  37. identityToken,
  38. nickname,
  39. inviteCode
  40. } = params
  41. const appleApi = initApple.call(this)
  42. let verifyResult
  43. try {
  44. verifyResult = await appleApi.verifyIdentityToken(identityToken)
  45. } catch (error) {
  46. console.error(error)
  47. await this.middleware.uniIdLog({
  48. success: false,
  49. type: LOG_TYPE.LOGIN
  50. })
  51. throw {
  52. errCode: ERROR.GET_THIRD_PARTY_ACCOUNT_FAILED
  53. }
  54. }
  55. const {
  56. openid
  57. } = verifyResult
  58. const {
  59. type,
  60. user
  61. } = await preUnifiedLogin.call(this, {
  62. user: {
  63. apple_openid: openid
  64. }
  65. })
  66. return postUnifiedLogin.call(this, {
  67. user,
  68. extraData: {
  69. nickname
  70. },
  71. isThirdParty: true,
  72. type,
  73. inviteCode
  74. })
  75. }