Skip to content

Commit

Permalink
Changes by mohlerki
Browse files Browse the repository at this point in the history
  • Loading branch information
arnegns committed Oct 13, 2023
1 parent 51fd12a commit d1ef3e6
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 53 deletions.
70 changes: 48 additions & 22 deletions controllers/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,13 @@ router.post('/login/email', async (req, res) => {
password,
};

const loginEmailRedirect = await authHelper.loginUser(req, res, 'local', payload, redirect, 'Email');
try {
const loginEmailRedirect = await authHelper.loginUser(req, res, 'local', payload, redirect);

res.redirect(loginEmailRedirect.redirect);
res.redirect(loginEmailRedirect.redirect);
} catch (ldapLoginError) {
return authHelper.handleLoginError(req, res, ldapLoginError.error, redirect, 'local');
}
});

router.get('/login/email', (req, res) => {
Expand Down Expand Up @@ -127,7 +131,7 @@ router.post('/login/ldap', async (req, res) => {
return authHelper.handleLoginError(req, res, {
type: 'BAD_REQUEST',
code: 400,
}, redirect);
}, redirect, 'ldap');
}

const systemIdAndAliasCombination = system.split('//');
Expand All @@ -136,7 +140,7 @@ router.post('/login/ldap', async (req, res) => {
return authHelper.handleLoginError(req, res, {
type: 'BAD_REQUEST',
code: 400,
}, redirect);
}, redirect, 'ldap');
}

const systemId = systemIdAndAliasCombination[0];
Expand All @@ -148,9 +152,13 @@ router.post('/login/ldap', async (req, res) => {
schoolId,
};

const loginLdapRedirect = await authHelper.loginUser(req, res, 'ldap', payload, redirect, 'LDAP');
try {
const loginLdapRedirect = await authHelper.loginUser(req, res, 'ldap', payload, redirect);

res.redirect(loginLdapRedirect.redirect);
res.redirect(loginLdapRedirect.redirect);
} catch (ldapLoginError) {
return authHelper.handleLoginError(req, res, ldapLoginError.error, redirect, 'ldap');
}
});

router.get('/login/ldap', (req, res) => {
Expand All @@ -174,7 +182,7 @@ const redirectOAuth2Authentication = async (req, res, systemId, migration, redir
system = await api(req, { version: 'v3' })
.get(`/systems/public/${systemId}`);
} catch (error) {
return authHelper.handleLoginError(req, res, error.error, redirect);
return authHelper.handleLoginError(req, res, error.error, redirect, 'oauth2');
}

const { oauthConfig } = system;
Expand All @@ -183,7 +191,7 @@ const redirectOAuth2Authentication = async (req, res, systemId, migration, redir
return authHelper.handleLoginError(req, res, {
type: 'UNPROCESSABLE_ENTITY',
code: 422,
}, redirect);
}, redirect, 'oauth2');
}

const state = shortid.generate();
Expand All @@ -197,6 +205,7 @@ const redirectOAuth2Authentication = async (req, res, systemId, migration, redir
postLoginRedirect: redirect,
migration,
logoutEndpoint: oauthConfig.logoutEndpoint,
provider: oauthConfig.provider,
};

res.redirect(authenticationUrl.toString());
Expand Down Expand Up @@ -234,16 +243,16 @@ router.get('/login/oauth2-callback', async (req, res) => {
return authHelper.handleLoginError(req, res, {
type: 'UNAUTHORIZED',
code: 401,
});
}, undefined, 'oauth2');
}

const redirect = oauth2State.postLoginRedirect;
const { postLoginRedirect } = oauth2State;

if (error) {
return authHelper.handleLoginError(req, res, {
type: error.toUpperCase(),
code: 401,
}, redirect);
}, postLoginRedirect, 'oauth2', oauth2State.systemName, oauth2State.provider);
}

const payload = {
Expand All @@ -254,36 +263,46 @@ router.get('/login/oauth2-callback', async (req, res) => {

let loginResponse;
if (oauth2State.migration && await authHelper.isAuthenticated(req)) {
await authHelper.migrateUser(req, res, payload);
} else {
const migrationRedirect = await authHelper.migrateUser(req, res, payload);
delete req.session.oauth2State;

return res.redirect(migrationRedirect);
}

try {
loginResponse = await authHelper.loginUser(
req,
res,
'oauth2',
payload,
redirect,
postLoginRedirect,
);
} catch (loginError) {
return authHelper.handleLoginError(
req,
res,
error.error,
postLoginRedirect,
'oauth2',
oauth2State.systemName,
oauth2State.provider,
);
}

if (loginResponse?.error) {
return authHelper.handleLoginError(req, res, loginResponse.error, redirect);
}

let postLoginRedirect = loginResponse.redirect;
let loginRedirect = loginResponse.redirect;
if (oauth2State.logoutEndpoint && loginResponse.login?.externalIdToken) {
postLoginRedirect = authHelper.getLogoutUrl(
loginRedirect = authHelper.getLogoutUrl(
req,
res,
oauth2State.logoutEndpoint,
loginResponse.login.externalIdToken,
postLoginRedirect,
loginRedirect,
);
}

delete req.session.oauth2State;

res.redirect(postLoginRedirect);
res.redirect(loginRedirect);
});

const redirectAuthenticated = (req, res) => {
Expand Down Expand Up @@ -362,6 +381,7 @@ const renderLogin = async (req, res) => {

let oauthErrorLogout = false;

// TODO N21-1374: remove old login flow
if (req.query.error) {
res.locals.notification = {
type: 'danger',
Expand All @@ -375,6 +395,12 @@ const renderLogin = async (req, res) => {
}
}

if (req.session.oauth2Logout) {
oauthErrorLogout = req.session.oauth2Logout.provider;

delete req.session.oauth2Logout;
}

const strategyOfSchool = req.query.strategy;
const idOfSchool = req.query.schoolId;

Expand Down
39 changes: 12 additions & 27 deletions helpers/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ const setErrorNotification = (res, req, error, systemName) => {
};
};

const handleLoginError = async (req, res, error, postLoginRedirect, strategy, systemName) => {
const handleLoginError = async (req, res, error, postLoginRedirect, strategy, systemName, provider) => {
setErrorNotification(res, req, error, systemName);

if (req.session.oauth2State) {
Expand All @@ -352,8 +352,13 @@ const handleLoginError = async (req, res, error, postLoginRedirect, strategy, sy
if (postLoginRedirect) {
queryString.append('redirect', redirectHelper.getValidRedirect(postLoginRedirect));
}

if (strategy === 'ldap' || strategy === 'email') {
queryString.append('strategy', strategy);
} else if (strategy === 'oauth2' && provider) {
req.session.oauth2Logout = {
provider,
};
}

const redirect = redirectHelper.joinPathWithQuery('/login', queryString.toString());
Expand Down Expand Up @@ -437,33 +442,14 @@ const getMigrationStatus = async (req, res, userId, accessToken) => {
return migration;
};

// eslint-disable-next-line consistent-return
const loginUser = async (req, res, strategy, payload, postLoginRedirect, systemName) => {
let accessToken;
let loginResponse;
try {
loginResponse = await requestLogin(req, strategy, payload);
const loginUser = async (req, res, strategy, payload, postLoginRedirect) => {
const loginResponse = await requestLogin(req, strategy, payload);

accessToken = loginResponse.accessToken;
} catch (errorResponse) {
logger.error('Login failed.');

return handleLoginError(req, res, errorResponse.error, postLoginRedirect, strategy, systemName);
}
const { accessToken } = loginResponse;

const currentUser = jwt.decode(accessToken);

let migration;
try {
migration = await getMigrationStatus(req, res, currentUser.userId, accessToken);
} catch (errorResponse) {
logger.error('Fetching migration status failed');

return {
error: errorResponse.error,
redirect: handleLoginError(req, res, errorResponse.error, postLoginRedirect, strategy, systemName),
};
}
const migration = await getMigrationStatus(req, res, currentUser.userId, accessToken);

setCookie(res, 'jwt', accessToken);

Expand Down Expand Up @@ -496,8 +482,7 @@ const getLogoutUrl = (req, res, logoutEndpoint, idTokenHint, redirect) => {
const logoutUrl = new URL(logoutEndpoint);
logoutUrl.searchParams.append('id_token_hint', idTokenHint);

const validRedirect = redirectHelper.getValidRedirect(redirect);
const postLoginRedirect = `${Configuration.get('HOST')}${validRedirect || '/dashboard'}`;
const postLoginRedirect = `${Configuration.get('HOST')}${redirect || '/dashboard'}`;
logoutUrl.searchParams.append('post_logout_redirect_uri', postLoginRedirect);

return logoutUrl.toString();
Expand Down Expand Up @@ -533,7 +518,7 @@ const migrateUser = async (req, res, payload) => {

await clearCookie(req, res);

res.redirect(redirect);
return redirect;
};

module.exports = {
Expand Down
17 changes: 13 additions & 4 deletions static/scripts/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,19 @@ $(document).ready(() => {
}
});

if ($oauthErrorLogout && $oauthSystems.length > 0 && $oauthErrorLogout.eq(0).text() === 'true') {
const $iservButton = $oauthSystems.find('.btn-oauth[data-provider="iserv"]');
if ($oauthErrorLogout && $oauthSystems.length > 0 && $oauthErrorLogout.eq(0).text()) {
const logoutErrorOrProvider = $oauthErrorLogout.eq(0).text();

let $loginButton;
if (logoutErrorOrProvider === 'true') {
// TODO N21-1374: remove old login flow
$loginButton = $oauthSystems.find('.btn-oauth[data-provider="iserv"]');
} else if (logoutErrorOrProvider !== 'false') {
$loginButton = $oauthSystems.find(`.btn-oauth[data-provider="${logoutErrorOrProvider}"]`);
}

if ($iservButton.length > 0) {
const logoutWindow = window.open($iservButton.eq(0).data('logout'));
if ($loginButton && $loginButton.length > 0) {
const logoutWindow = window.open($loginButton.eq(0).data('logout'));
window.focus();
setTimeout(() => {
logoutWindow.close();
Expand All @@ -165,6 +173,7 @@ $(document).ready(() => {
}
}

// TODO N21-1374: remove old login flow
$oauthSystems.each((index, element) => {
const $oauthButton = $(element).find('.btn-oauth').eq(0);

Expand Down

0 comments on commit d1ef3e6

Please sign in to comment.