feat: 添加刷新令牌支持

* 服务端: 添加对应的接口, 对原有令牌系统稍有修改, 添加了令牌类型
* 客户端: 自动刷新访问令牌, 登录时顺带获取刷新令牌
This commit is contained in:
CrescentLeaf
2025-10-06 17:13:23 +08:00
parent dced175d7a
commit 85477fe46e
6 changed files with 80 additions and 20 deletions

View File

@@ -3,6 +3,7 @@ import config from "../config.ts"
import User from "../data/User.ts"
import crypto from 'node:crypto'
import Token from "./Token.ts"
import TokenType from "./TokenType.ts"
function normalizeKey(key: string, keyLength = 32) {
const hash = crypto.createHash('sha256')
@@ -31,38 +32,28 @@ export default class TokenManager {
}
}
static make(user: User, time_: number | null | undefined, device_id: string) {
static make(user: User, time_: number | null | undefined, device_id: string, type: TokenType = "access_token") {
const time = (time_ || Date.now())
return this.encode({
author: user.bean.id,
auth: this.makeAuth(user),
made_time: time,
expired_time: time + (1 * 1000 * 60 * 60 * 24),
device_id: device_id
expired_time: time + (type == 'access_token' ? (1000 * 60 * 60 * 2) : (40 * 1000 * 60 * 60 * 24)),
device_id: device_id,
type
})
}
/**
* 獲取新令牌
* 注意: 只驗證用戶, 不驗證令牌有效性!
*/
static makeNewer(user: User, token: string) {
if (this.check(user, token))
return this.make(user, Date.now() + (1 * 1000 * 60 * 60 * 24), this.decode(token).device_id)
}
static check(user: User, token: string) {
const tk = this.decode(token)
return this.makeAuth(user) == tk.auth
}
/**
* 嚴格檢驗令牌: 時間, 用戶, (設備 ID)
*/
static checkToken(token: Token, deviceId?: string) {
static checkToken(token: Token, deviceId?: string, type: TokenType = 'access_token') {
if (token.expired_time < Date.now()) return false
if (!token.author || !User.findById(token.author)) return false
if (deviceId != null)
if (token.device_id != deviceId)
return false
if (token.type != type)
return false
return true
}
}