如何检查是否在Meteor框架中通过第三方服务登录?

时间:2019-05-02 04:07:48

标签: meteor

您如何检查用户是否通过Meteor框架中的第三方(Google,Facebook等)登录?另外,这可能来自客户端吗?

1 个答案:

答案 0 :(得分:2)

有多种方法可以做到这一点。在服务器端,您将具有类似Accounts.onCreateUser((options, user) => {... })的功能。 如果您已经发布了最低限度的用户数据,则可以使用onCreateUser添加密钥,并保存以下内容:loginVia: "email""FB"等。然后发布该密钥或使用方法。

最直接的解决方案是检查社会服务是否存在(如果寻找特定服务)。 例如:

const isFBUser: Meteor.users.find({ _id :....  }, { 'services.facebook': { $exists: true } }).count() // results in 1 record or 0 records = true / false

如果您想知道用户是否通过电子邮件而不是第三方来访问,您可以检查电子邮件

const isThirdParty = Meteor.users.find({_id: ...}, emails: { $exists: true })

使用合并帐户系统也是很常见的,这样,来自FB且电子邮件为gigi@gmail.com的人将被允许使用电子邮件而非社交帐户登录到您的应用程序。在这种情况下,您最终需要保存上次登录的来源。

我将在这里为您提供onCreateUser的一部分,作为如何从第三方用户提取数据并将其保存在使用配置文件中的示例。在同一行上,您可以保存第三方来源(如上所述)

if (user.services) {
    const fb = user.services.facebook
    const google = user.services.google

    let avatar = null
    let fbi = null  // I use this to keep a record of the FB user Id
    let ggli = null // // I use this to keep a record of the Google user Id 

    if (fb) {
      /**
       * I upload to S3 and I don't wait for a response. A little risky...
       */
      put_from_url(`https://graph.facebook.com/${fb.id}/picture?width=500&height=500`, `avatar/${fb.id}.jpg`, (err, res) => {
        if (err) {
          console.log('Could not upload FB photo to S3, ', err)
        } else {
          // console.log(res)
        }
      })

      user.profile = extend(user.profile, {
        firstName: fb.first_name,
        lastName: fb.last_name,
        email: fb.email,
        displayName: fb.name,
        gender: startCase(toLower(fb.gender)),
        avatar: `${fb.id}.jpg`
      })
      avatar = `${fb.id}.jpg`
      fbi = fb.id
      roles = ['user', 'social']
    }

    if (google) {
      /**
       * I upload to S3 and I don't wait for a response. A little risky...
       */
      put_from_url(google.picture + '?sz=500', `avatar/${google.id}.jpg`, err => {
        if (err) {
          console.log('Could not upload Google photo to S3, ', err)
        }
      })

      user.profile = extend(user.profile, {
        firstName: google.given_name,
        lastName: google.family_name,
        email: google.email,
        displayName: google.name,
        gender: startCase(toLower(google.gender)),
        avatar: `${google.id}.jpg`
      })
      avatar = `${google.id}.jpg`
      ggli = google.id
      roles = ['user', 'social']
    }

    /**
     * Create a slug for each user. Requires a display name for all users.
     */

    let slug
    slug = Meteor.call('/app/create/slug', user.profile.displayName, 'user')

还请检查用户对象结构:

enter image description here

然后检查一下。通过第三方的用户没有电子邮件字段,因此您可以检查其存在。

enter image description here