keycloak-demo/controllers/oauth/index.js

81 lines
2.1 KiB
JavaScript
Raw Normal View History

2021-09-01 11:30:21 +00:00
const debug = require("debug")("ctrl:common");
const util = require("util");
const url = require("url");
const sso = require("src/utils/sso/index.js");
const { get: getCacheInstance } = require("src/utils/cache.js");
const { codeMessage, APIError } = require("src/utils/response/index.js");
const config = require("src/config/index.js");
const { jwt } = require("src/utils/pkgs.js");
2021-08-31 10:24:42 +00:00
const controller = {};
module.exports = controller;
2021-09-01 11:30:21 +00:00
controller.verifyCode = () => async (ctx) => {
2021-08-31 10:24:42 +00:00
const { code, session_state: sessionState, state } = ctx.query;
// logout flow redirect tot frontend
2021-09-01 11:30:21 +00:00
if (state === "logout") {
2021-08-31 10:24:42 +00:00
ctx.redirect(config.server.frontend_url);
return;
}
// get back url from redis
2021-09-01 11:30:21 +00:00
const cacheKey = `login-${state}`;
const cache = getCacheInstance();
2021-08-31 10:24:42 +00:00
2021-09-01 11:30:21 +00:00
const data = cache.get(cacheKey);
if (!data) ctx.throw("get login cache fail");
2021-08-31 10:24:42 +00:00
const stateObj = JSON.parse(data);
const { back_url: backURL } = stateObj;
2021-09-01 11:30:21 +00:00
if (!backURL) ctx.throw("cache data missing");
2021-08-31 10:24:42 +00:00
const u = new url.URL(backURL);
try {
const token = await sso.getToken(code, sessionState);
// generate jwt token
const jwtToken = jwt.sign(
{
2021-09-01 07:20:53 +00:00
user_id: token.user_id,
2021-08-31 10:24:42 +00:00
sso: true,
},
config.server.jwt_secret,
{
expiresIn: config.server.jwt_expire,
2021-09-01 11:30:21 +00:00
issuer: "lawsnote",
2021-08-31 10:24:42 +00:00
}
);
2021-09-01 11:30:21 +00:00
u.searchParams.append(
"success",
Buffer.from(JSON.stringify({ token: jwtToken })).toString("base64")
);
2021-08-31 10:24:42 +00:00
try {
2021-09-01 11:30:21 +00:00
cache.del(cacheKey);
2021-08-31 10:24:42 +00:00
} catch (err) {
debug(`delete cache fail: ${util.inspect(err, false, null)}`);
}
} catch (err) {
debug(`openid verify fail: ${util.inspect(err, false, null)}`);
/** @type {object} */
const errObj = { ...codeMessage.CodeInternalError };
if (err instanceof APIError) {
// @ts-ignore
Object.assign(errObj, err.object.object);
}
errObj.errorStack = err.stack;
errObj.errorMessage = err.message;
2021-09-01 11:30:21 +00:00
u.searchParams.append(
"error",
Buffer.from(JSON.stringify(errObj)).toString("base64")
);
2021-08-31 10:24:42 +00:00
}
ctx.redirect(u.toString());
};