Hey everyone, I think that I have written Javascript to get page redirection to the intended page after login working properly.
I have attached the code below and would like everyone to try it out/ review it for improvements. If anyone knows of a way that the JavaScript can be run on the layout/page side BEFORE Tadabase redirects from the intended URL to the login page, I believe that the default page security settings could stay on. This would be ideal but I could not figure out a way to capture the inbound URL or add JavaScript to the redirecting screen.
Layout Setup/ Settings
- Change layout and page security to “anyone, no login required”
- Remove login redirect rules
- Remove page rules that redirect users
- If this is not done, the Javascript does not run.
Layout Code
This code needs to be placed on all of your layouts. Make sure to set which roles should be allowed to enter the page using the “allowed” list.
var userToken = TB.getUserToken();
// Store the url attempt to the session
sessionStorage.setItem('packredirectTo', window.location.href);
if (!userToken) {
// Hide all components on the page
for (let i = 1; i < 50; i++) {
TB.hideComponent("component_".concat(i));}
// Redirect to the login page
window.location.href = '/login';
}
// Delete stored URL from storage on login
if (userToken.length > 0) {
sessionStorage.removeItem('packredirectTo');
}
// Security
const role = "{loggedInUser.Role}";
const allowed = ["Contractor", "Student", "Staff"]
if (allowed.includes(role)) {
// Role is allowed
console.log(`Script Finished`);
} else {
// Role is not allowed
window.location.href = '/login';
}
/* END Capture the current URL before redirecting to login */
Login Page Code
Place this code on your login page. Make sure to change the component number, roles, and slugs of your default home pages.
If you have component IDs that go above 50, change 50 to your highest ID value. This may be able to be hard coded with a list and a for loop.
/* better redirect */
TB.render('component_4', function() {
// Get user role
const role = "{loggedInUser.Role}";
// Get packed redirect URL
const redirectTo = sessionStorage.getItem('packredirectTo')
// If the user has a role, handle the redirection
if (role.length > 0) {
const storedRedirectTo = sessionStorage.getItem('packredirectTo');
// Hide all components on the page
for (let i = 1; i < 50; i++) {
TB.hideComponent("component_".concat(i));}
if (storedRedirectTo) {
window.location.href = storedRedirectTo;
sessionStorage.removeItem('packredirectTo');
//If there was not an attempt to reach another page, redirect to default page based on the role
} else {
console.log("No valid stored redirect, redirecting to success page");
// define role
if (role == "Staff"){
// define slug
window.location.href = '/staff-home';
}
if (role == "Student"){
window.location.href = '/student-home';
}
} else {
console.log("User has no role, no redirection performed");
}
});
/* end of better redirect */
Would love @moe 's opinion!