Using custom Loopback user model with loopback-component-passport

无人久伴 提交于 2019-12-01 00:37:46

You will have to extend all passport related models, so you can have them linked to your custom user model.

user.json

{
  "name": "user",
  "plural": "users",
  "base": "User",
  "relations": {
    "accessTokens": {
      "type": "hasMany",
      "model": "accessToken",
      "foreignKey": "userId"
    },
    "identities": {
      "type": "hasMany",
      "model": "userIdentity",
      "foreignKey": "userId"
    },
    "credentials": {
      "type": "hasMany",
      "model": "userCredential",
      "foreignKey": "userId"
    }
  },
  "validations": [],
  "acls": [],
  "methods": []
}

user-identity.json

{
  "name": "userIdentity",
  "plural": "userIdentities",
  "base": "UserIdentity",
  "properties": {},
  "validations": [],
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "user",
      "foreignKey": "userId"
    }
  },
  "acls": [],
  "methods": []
}

user-credential.json

{
  "name": "userCredential",
  "plural": "userCredentials",
  "base": "UserCredential",
  "properties": {},
  "validations": [],
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "user",
      "foreignKey": "userId"
    }
  },
  "acls": [],
  "methods": []
}

access-token.json

{
  "name": "accessToken",
  "plural": "accessTokens",
  "base": "AccessToken",
  "properties": {},
  "validations": [],
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "user",
      "foreignKey": "userId"
    }
  },
  "acls": [],
  "methods": {}
}

server.js (relevant part)

const PassportConfigurator = require('loopback-component-passport').PassportConfigurator
const passportConfigurator = new PassportConfigurator(app)

let providersConfig = require('./providers.json')

passportConfigurator.init()

passportConfigurator.setupModels({
  userModel: app.models.user,
  userIdentityModel: app.models.userIdentity,
  userCredentialModel: app.models.userCredential
})

for (let s in providersConfig) { // Configure providers based on providers.json config
  let c = providersConfig[s]
  c.session = c.session !== false
  passportConfigurator.configureProvider(s, c)
}

There is also an example repository, which might be useful for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!