core: oauth: enhancement

This commit is contained in:
undefined committed 2022-02-09 18:44:41 +08:00
1 parent 04ec44dab9
commit b1f90ab5a1
10 files changed
+55 -26

No files matched your search

+13 -10
View File
@@ -1,38 +1,40 @@
import 'hydrooj';
import * as superagent from 'superagent';
import superagent from 'superagent';
declare module 'hydrooj' {
interface SystemKeys {
'login-with-github.id': string,
'login-with-github.secret': string,
'login-with-github.id': string;
'login-with-github.secret': string;
'login-with-github.endpoint': string;
}
interface Lib {
oauth_github: typeof import('./lib'),
oauth_github: typeof import('./lib');
}
}
async function get() {
const { system, token } = global.Hydro.model;
const [appid, [state]] = await Promise.all([
system.get('login-with-github.id'),
const [[appid, endpoint = 'https://github.com'], [state]] = await Promise.all([
system.getMany(['login-with-github.id', 'login-with-github.endpoint']),
token.add(token.TYPE_OAUTH, 600, { redirect: this.request.referer }),
]);
this.response.redirect = `https://github.com/login/oauth/authorize?client_id=${appid}&state=${state}`;
this.response.redirect = `${endpoint}/login/oauth/authorize?client_id=${appid}&state=${state}`;
}
async function callback({ state, code }) {
const { system, token } = global.Hydro.model;
const { UserFacingError } = global.Hydro.error;
const [[appid, secret, url], s] = await Promise.all([
const [[appid, secret, endpoint, url], s] = await Promise.all([
system.getMany([
'login-with-github.id',
'login-with-github.secret',
'login-with-github.endpoint',
'server.url',
]),
token.get(state, token.TYPE_OAUTH),
]);
const res = await superagent.post('https://github.com/login/oauth/access_token')
const res = await superagent.post(`${endpoint || 'https://github.com'}/login/oauth/access_token`)
.send({
client_id: appid,
client_secret: secret,
@@ -47,7 +49,7 @@ async function callback({ state, code }) {
);
}
const t = res.body.access_token;
const userInfo = await superagent.get('https://api.github.com/user')
const userInfo = await superagent.get(`${endpoint || 'https://api.github.com'}/user`)
.set('User-Agent', 'Hydro-OAuth')
.set('Authorization', `token ${t}`);
const ret = {
@@ -55,6 +57,7 @@ async function callback({ state, code }) {
email: userInfo.body.email,
bio: userInfo.body.bio,
uname: [userInfo.body.name, userInfo.body.login],
avatar: `github:${userInfo.body.login}`,
};
this.response.redirect = s.redirect;
await token.del(s._id, token.TYPE_OAUTH);