diff --git a/src/accounts-client.js b/src/accounts-client.js index 1c420b7..e2cd610 100644 --- a/src/accounts-client.js +++ b/src/accounts-client.js @@ -10,14 +10,14 @@ const accountsClient = Axios.create({ * @param ctx {import('koa').Context} * @returns {Promise} */ -module.exports.getUsername = async (ctx) => { +module.exports.getExternalId = async (ctx) => { try { const { data } = await accountsClient.get('/api/me', { headers: { cookie: ctx.get('cookie') } }) - return data.data.username + return data.data.openid } catch (e) { return undefined } diff --git a/src/asktug-proxy.js b/src/asktug-proxy.js index e6bffa2..a0157fc 100644 --- a/src/asktug-proxy.js +++ b/src/asktug-proxy.js @@ -29,39 +29,27 @@ const request = (url, options, cb) => { /** * * @param ctx {import('koa').Context} - * @param username {string} + * @param externalId {string} * @return Promise */ -function proxyAsktug (ctx, username) { +function proxyAsktug (ctx, externalId) { const { req, res } = ctx return new Promise((resolve, reject) => { - //// https://github.com/discourse/discourse/pull/7129 - //// utf8 username is invalid - // + const headers = { + 'Accept': 'application/json', + 'x-forwarded-for': ctx.request.get('x-forwarded-for'), + } let url = asktug.url + req.url - if (username) { - // https://github.com/pingcap/discourse/blob/69a66722364fb23e82e8bb81cf7645c1b7e585db/lib/auth/default_current_user_provider.rb#L300 - // We could only use one of header or query to pass auth info - const sig = `api_key=${encodeURIComponent(asktug.token)}&api_username=${encodeURIComponent(username)}` - if (url.indexOf('?') > 0) { - if (url.endsWith('&') || url.endsWith('?')) { - url += sig - } else { - url += '&' + sig - } - } else { - url += '?' + sig - } + if (externalId) { + headers['Api-Key'] = asktug.token + headers['Api-User-External-Id'] = externalId } const clientRequest = request(url, { method: req.method, timeout: 1500, - headers: { - 'Accept': 'application/json', - 'x-forwarded-for': ctx.request.get('x-forwarded-for'), - } + headers, }, asktugRes => { res.statusCode = asktugRes.statusCode res.statusMessage = asktugRes.statusMessage diff --git a/src/index.js b/src/index.js index 3a238c4..5d7ef00 100644 --- a/src/index.js +++ b/src/index.js @@ -1,6 +1,6 @@ const Koa = require('koa') const logger = require('koa-logger') -const { getUsername } = require('./accounts-client') +const { getExternalId } = require('./accounts-client') const proxyAsktug = require('./asktug-proxy') const { asktug } = require('./config') const Axios = require("axios"); @@ -61,8 +61,8 @@ app.use(async (ctx, next) => { // ACCOUNTS_COOKIE_NAME app.use(async ctx => { try { - const username = await getUsername(ctx) - await proxyAsktug(ctx, username) + const externalId = await getExternalId(ctx) + await proxyAsktug(ctx, externalId) } catch (e) { console.error('proxy failed', e) ctx.status = e?.response?.status ?? e?.status ?? 500