49 lines
1.2 KiB
TypeScript
49 lines
1.2 KiB
TypeScript
import { app } from '@/app.ts';
|
|
import { CustomError } from '@kevisual/router';
|
|
import { getAccessToken } from './lib/get-token.ts';
|
|
import { GithubModel } from './models/github.ts';
|
|
|
|
app
|
|
.route({
|
|
path: 'github',
|
|
key: 'token',
|
|
middleware: ['auth'],
|
|
})
|
|
.define(async (ctx) => {
|
|
const tokenUser = ctx.state.tokenUser;
|
|
const github = await GithubModel.findOne({
|
|
where: {
|
|
uid: tokenUser.id,
|
|
},
|
|
logging: false,
|
|
});
|
|
if (github) {
|
|
ctx.body = {
|
|
githubToken: github.githubToken,
|
|
};
|
|
return;
|
|
}
|
|
const { code } = ctx.query;
|
|
if (!code) {
|
|
throw new CustomError(400, 'code is required');
|
|
}
|
|
try {
|
|
console.log('get access token from github, code:', code);
|
|
const token = await getAccessToken(code);
|
|
if (!token) {
|
|
throw new CustomError(500, 'Failed to get access token');
|
|
}
|
|
await GithubModel.create({
|
|
uid: tokenUser.id,
|
|
githubToken: token,
|
|
});
|
|
ctx.body = {
|
|
githubToken: token,
|
|
};
|
|
} catch (e) {
|
|
console.error('get access token from github error:', e);
|
|
throw new CustomError(500, 'Failed to get access token');
|
|
}
|
|
})
|
|
.addTo(app);
|