81 lines
2.5 KiB
JavaScript
81 lines
2.5 KiB
JavaScript
/**
|
||
* 授权服务
|
||
* 提供账号授权检查功能
|
||
*/
|
||
|
||
const db = require('../middleware/dbProxy');
|
||
const dayjs = require('dayjs');
|
||
|
||
class AuthorizationService {
|
||
/**
|
||
* 检查账号授权状态
|
||
* @param {string|number} identifier - 账号标识(sn_code 或 id)
|
||
* @param {string} identifierType - 标识类型:'sn_code' 或 'id'
|
||
* @returns {Promise<Object>} 授权检查结果 {is_authorized: boolean, remaining_days: number, message: string}
|
||
*/
|
||
async checkAuthorization(identifier, identifierType = 'sn_code') {
|
||
const pla_account = db.getModel('pla_account');
|
||
|
||
const where = {};
|
||
where[identifierType] = identifier;
|
||
|
||
const account = await pla_account.findOne({ where });
|
||
|
||
if (!account) {
|
||
return {
|
||
is_authorized: false,
|
||
remaining_days: 0,
|
||
message: '账号不存在'
|
||
};
|
||
}
|
||
|
||
const accountData = account.toJSON();
|
||
const authDate = accountData.authorization_date;
|
||
const authDays = accountData.authorization_days || 0;
|
||
|
||
// 如果没有授权信息,默认不允许
|
||
if (!authDate || authDays <= 0) {
|
||
return {
|
||
is_authorized: false,
|
||
remaining_days: 0,
|
||
message: '账号未授权,请联系管理员'
|
||
};
|
||
}
|
||
|
||
// 计算剩余天数
|
||
const startDate = dayjs(authDate);
|
||
const endDate = startDate.add(authDays, 'day');
|
||
const now = dayjs();
|
||
const remaining = endDate.diff(now, 'day', true);
|
||
const remaining_days = Math.max(0, Math.ceil(remaining));
|
||
|
||
if (remaining_days <= 0) {
|
||
return {
|
||
is_authorized: false,
|
||
remaining_days: 0,
|
||
message: '账号授权已过期,请联系管理员续费'
|
||
};
|
||
}
|
||
|
||
return {
|
||
is_authorized: true,
|
||
remaining_days: remaining_days,
|
||
message: `授权有效,剩余 ${remaining_days} 天`
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 检查账号授权状态(快速检查,只返回是否授权)
|
||
* @param {string|number} identifier - 账号标识(sn_code 或 id)
|
||
* @param {string} identifierType - 标识类型:'sn_code' 或 'id'
|
||
* @returns {Promise<boolean>} 是否授权
|
||
*/
|
||
async isAuthorized(identifier, identifierType = 'sn_code') {
|
||
const result = await this.checkAuthorization(identifier, identifierType);
|
||
return result.is_authorized;
|
||
}
|
||
}
|
||
|
||
module.exports = new AuthorizationService();
|
||
|