99 lines
3.0 KiB
JavaScript
99 lines
3.0 KiB
JavaScript
import { generateNewIdAsync } from "oak-domain/lib/utils/uuid";
|
|
import { applicationProjection, extraFileProjection } from "../../types/Projection";
|
|
import { getDefaultHandlers } from "./handler";
|
|
const handlerMap = new Map();
|
|
export const registerUserinfoHandler = (type, handler) => {
|
|
if (handlerMap.has(type)) {
|
|
throw new Error(`oauth provider type ${type} 的 userinfo 处理器已注册`);
|
|
}
|
|
handlerMap.set(type, handler);
|
|
};
|
|
export const processUserInfo = (type, data) => {
|
|
const handler = handlerMap.get(type);
|
|
if (!handler) {
|
|
throw new Error(`oauth provider type ${type} 的 userinfo 处理器未注册`);
|
|
}
|
|
return handler(data);
|
|
};
|
|
const defaulthandlers = getDefaultHandlers();
|
|
Object.entries(defaulthandlers).forEach(([type, handler]) => {
|
|
registerUserinfoHandler(type, handler);
|
|
});
|
|
function validateToken(token) {
|
|
if (!token) {
|
|
return { token: "", error: "Missing authorization token" };
|
|
}
|
|
// Token validation logic here
|
|
if (!token.startsWith("Bearer ")) {
|
|
return { token: "", error: "Invalid token format" };
|
|
}
|
|
return { token: token.slice(7), error: null };
|
|
}
|
|
// 工具函数
|
|
export async function checkOauthTokenAvaliable(context, token) {
|
|
// Validate and decode the token
|
|
const decoded = validateToken(token);
|
|
if (decoded.error) {
|
|
return {
|
|
error: decoded.error,
|
|
statusCode: 401
|
|
};
|
|
}
|
|
// 获取token记录
|
|
const [tokenRecord] = await context.select("oauthToken", {
|
|
data: {
|
|
id: 1,
|
|
user: {
|
|
id: 1,
|
|
name: 1,
|
|
nickname: 1,
|
|
birth: 1,
|
|
gender: 1,
|
|
extraFile$entity: {
|
|
$entity: 'extraFile',
|
|
data: extraFileProjection,
|
|
filter: {
|
|
tag1: 'avatar',
|
|
}
|
|
}
|
|
},
|
|
accessExpiresAt: 1,
|
|
revokedAt: 1,
|
|
code: {
|
|
id: 1,
|
|
application: applicationProjection,
|
|
}
|
|
},
|
|
filter: {
|
|
accessToken: decoded.token,
|
|
}
|
|
}, {});
|
|
if (!tokenRecord) {
|
|
return { error: "Invalid token", statusCode: 401 };
|
|
}
|
|
if (tokenRecord.accessExpiresAt < Date.now()) {
|
|
return { error: "Token expired", statusCode: 401 };
|
|
}
|
|
if (tokenRecord.revokedAt) {
|
|
return { error: "Token revoked", statusCode: 401 };
|
|
}
|
|
if (!tokenRecord.user) {
|
|
return { error: "User not found", statusCode: 401 };
|
|
}
|
|
if (!tokenRecord.code || !tokenRecord.code.application) {
|
|
return { error: "Application not found", statusCode: 401 };
|
|
}
|
|
// 更新最后使用日期
|
|
await context.operate("oauthToken", {
|
|
id: await generateNewIdAsync(),
|
|
action: "update",
|
|
data: {
|
|
lastUsedAt: Date.now(),
|
|
},
|
|
filter: {
|
|
id: tokenRecord.id,
|
|
}
|
|
}, {});
|
|
return { error: null, tokenRecord };
|
|
}
|