access-token - 将 AccessToken 链接到 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
与用户建立了关系(参考: https ://github.com/strongloop/loopback/blob/master/common/models/access-token.json#L27 )。userId
{
"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 });
推荐阅读
- azure - Azure DataBrick PYTHONPATH 指向导入的轮子?
- python - 如何找到在 python 的特定列表中多次出现的元素的所有索引?
- javascript - 如何使用 Javascript 将 textarea 文本保存为 excel 格式
- awk - 在 awk 中使用 Bash int 变量问题
- kubernetes - 我如何将 kubectl kustomize 的输出实际获取到我的集群中?
- http - 为什么要导出 Golang 的 http.DefaultClient?
- django - Django: form.is_valid() false
- ios - 当我们更改项目的部分时,NSFetchResultsController 是否可以执行移动和更新操作?
- firebase - 按日期对收藏夹进行 Firestore 数据建模方法
- angular - How to add pagination in angular material table that bind to API response