在环回中将AccessToken链接到用户

时间:2019-12-05 03:16:37

标签: access-token strongloop 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 });

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

1 个答案:

答案 0 :(得分:0)

因此,看来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"
    }
  ]
}

要将令牌链接到用户,我们只需要传递值userId

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