Link Loopback 中用户的 AccessToken

Link AccessToken to a user in Loopback

我想向访问令牌添加一个自定义属性 (expireAt),以便 MongoDB 使用它在过期时自动删除过期的访问令牌。

在使用 AccessToken 模型创建访问令牌时添加自定义属性运行良好:

const ttl = 600;

const expireAt = new Date();
expireAt.setSeconds(expireAt.getSeconds() + ttl);

const token = await AccessToken.create({ ttl, expireAt });

但是,当我想为用户创建访问令牌时,我无法在创建令牌时添加自定义属性exprieAt,所以我先创建,然后更新它:

const ttl = 600;

const expireAt = new Date();
expireAt.setSeconds(expireAt.getSeconds() + ttl);

// Create the access token for the user
const token = await user.createAccessToken(options);
// Update token to set the custom date and time to expire
token.expireAt = expireAt;
token.save();

// Return the token together with the user data
return Object.assign({}, token.toJSON(), { user });

有没有一种方法可以为具有自定义属性的用户创建令牌(使用实例方法或模型方法都可以),而无需执行两个步骤 - 创建和更新?

所以 AccessToken 模型似乎通过 userId 属性与用户建立了关系(参考:https://github.com/strongloop/loopback/blob/master/common/models/access-token.json#L27)。

{
  "name": "AccessToken",
  "properties": {
    "id": {
      "type": "string",
      "id": true
    },
    "ttl": {
      "type": "number",
      "ttl": true,
      "default": 1209600,
      "description": "time to live in seconds (2 weeks by default)"
    },
    "scopes": {
      "type": ["string"],
      "description": "Array of scopes granted to this access token."
    },
    "created": {
      "type": "Date",
      "defaultFn": "now"
    }
  },
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "User",
      "foreignKey": "userId"
    }
  },
  "acls": [
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    }
  ]
}

到link给用户的token,我们只需要传入值userId:

AccessToken.create({ ttl, expireAt, userId });