feat: add login for plugin

This commit is contained in:
2025-03-23 16:48:19 +08:00
parent 74a484718a
commit cb490470c1
18 changed files with 1079 additions and 369 deletions

View File

@@ -1,8 +1,64 @@
import './routes/index.ts';
import { app } from './app.ts';
import type { App } from '@kevisual/router';
import { User } from './models/user.ts';
import { addAuth } from '@kevisual/code-center-module/models';
// import { addAuth } from '@kevisual/code-center-module/models';
// addAuth(app);
import { createCookie, getSomeInfoFromReq } from './routes/user/me.ts';
/**
* 添加auth中间件, 用于验证token
* 添加 id: auth 必须需要user成功
* 添加 id: auth-can 可以不需要user成功有则赋值
*
* @param app
*/
export const addAuth = (app: App) => {
app
.route({
path: 'auth',
id: 'auth',
})
.define(async (ctx) => {
const token = ctx.query.token;
if (!token) {
app.throw(401, 'Token is required');
}
const user = await User.getOauthUser(token);
if (!user) {
app.throw(401, 'Token is invalid');
}
const someInfo = getSomeInfoFromReq(ctx);
if (someInfo.isBrowser && !ctx.req?.cookies?.['token']) {
createCookie({ accessToken: token }, ctx);
}
ctx.state.tokenUser = user;
})
.addTo(app);
app
.route({
path: 'auth',
key: 'can',
id: 'auth-can',
})
.define(async (ctx) => {
if (ctx.query?.token) {
const token = ctx.query.token;
const user = await User.getOauthUser(token);
if (token) {
ctx.state.tokenUser = user;
const someInfo = getSomeInfoFromReq(ctx);
if (someInfo.isBrowser && !ctx.req?.cookies?.['token']) {
createCookie({ accessToken: token }, ctx);
}
} else {
ctx.state.tokenUser = null;
}
}
})
.addTo(app);
};
addAuth(app);
app
@@ -53,6 +109,7 @@ app
if (!tokenUser) {
ctx.throw(401, 'No User For authorized');
}
try {
const user = await User.findOne({
where: {