feat: some add auth
This commit is contained in:
51
src/routes/github/lib/get-token.ts
Normal file
51
src/routes/github/lib/get-token.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import fetch from 'node-fetch';
|
||||
import { useConfig } from '@abearxiong/use-config';
|
||||
|
||||
type GithubConfig = {
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
redirect_uri: string;
|
||||
};
|
||||
const { github } = useConfig<{ github: GithubConfig }>();
|
||||
// 获取 GitHub access_token 的函数
|
||||
async function getGithubToken(github: GithubConfig, code) {
|
||||
const { clientId, clientSecret, redirect_uri } = github;
|
||||
// 设置请求 URL 和参数
|
||||
const tokenUrl = 'https://github.com/login/oauth/access_token';
|
||||
const params = {
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code: code,
|
||||
redirect_uri: redirect_uri,
|
||||
};
|
||||
|
||||
try {
|
||||
// 发送 POST 请求获取 access_token
|
||||
const response = await fetch(tokenUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify(params),
|
||||
});
|
||||
|
||||
// 解析响应 JSON
|
||||
const data: any = await response.json();
|
||||
|
||||
if (data.access_token) {
|
||||
console.log('Access Token:', data.access_token);
|
||||
return data.access_token;
|
||||
} else {
|
||||
console.error('Error:', data.error || 'Failed to get access token');
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching access token:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const getAccessToken = async (code?: string) => {
|
||||
return getGithubToken(github, code);
|
||||
};
|
||||
Reference in New Issue
Block a user