Allow a user access to 2 specific pages using jQuery - javascript

I have a site where users must log in to access pages. When they are not logged in I redirect them to the log in page and it then sets a cookie / token. I know this is not the most stable way of doing it but it works and its not a high traffic site whatsoever. maybe 5 users. My issue now is I need to give the users access to a contact us page even if the cookie / token is not set / valid. I tried to add another conditional to the function but it creates an infinite loop. Any ideas of handling this situation?
jQuery :
function checkIfTokenExists() {
var current_url = window.location.pathname;
var logInToken = _siteNs.Utils.readCookie('SST');
if (!logInToken) {
if (current_url != '/login.html') {
window.location.replace('/login.html');
}
} else if (logInToken) {
_siteNs.authenticateUtils.authenticateSite();
}
}
What I would like is if url is equal to /contact.html the users will be able to access regardless of cookie / token

You can early return before the token check, if the current URL is the contact page.
function checkIfTokenExists() {
var current_url = window.location.pathname;
var logInToken = _siteNs.Utils.readCookie('SST');
if (current_url == '/contact.html') {
return;
}
// ... rest of your code

Related

Integrate Salesforce registration page with VanillaJS oidc-client-js, getting the error - No matching state found in storage

Integrate Salesforce registration page with VanillaJS, getting the error - No matching state found in storage
We are redirecting the user to Salesforce registration page when Create Account button is created.
Once the User registers in Salesforce, the user is redirected to our site but we are getting this error. ('No matching state found in storage').
We tried the below solution but still getting the same error.
As I stated in my answer, the oidc client maintains state information
in the local storage so that it can verify that it got the response
back from the intended server. You can mimic this by generating a
secure random string and saving it in localStorage. Do this before
sending a request to your auth server to register a new user.
Reference- Integrate third party login in from my registration page with IdentityServer4 and Angular 6 - 'No matching state found in storage'
Is there a function related to creating registration? How to fix this issue?
Thanks.
Appreciate your help.
After spending days on this issue. Finally found the workaround as registration is not a feature of OIDC.
To overcome this issue, need to follow the Sign In process same as for Sign Up process, created the startSignupMainWindow method same as startSigninMainWindow and passing the signUpFlag:true as shown below in code.
/* This function is written to mimic the oidc library sign in process flow */
function startSignupMainWindow() {
var someState = {
message: window.location.href,
signUpFlag: true
};
mgr.signinRedirect({
state: someState,
useReplaceToNavigate: true
}).then(function() {
log("signinRedirect done");
}).catch(function(err) {
log(err);
});
}
Reading the signUpFlag:true in UserManager.js and swapping the Salesforce Sign In page Url with Sign Up page url and calling the Register function in Code.
UserManager.js(oidc - client - dev - js / src / UserManager.js)
//UserManager Customised Code :
return this.createSigninRequest(args).then(signinRequest => {
Log.debug("UserManager._signinStart: got signin request");
navigatorParams.url = signinRequest.url;
navigatorParams.id = signinRequest.state.id;
if (signinRequest.state._data.signUpFlag) {
register(signinRequest.state._id, signinRequest.state._code_challenge);
} else {
return handle.navigate(navigatorParams);
}
})
The below code is Register function written in code.
/* This function is written to send the code_challenge to salesforce server so that
salesforce server holds the code challenge and used to verify the further requests(token-request)
against the code_challenge it received initially.*/
//Customised register function written outside the library (Inside our App):
function register(_id, code_challenge) {
var date = new Date();
var baseUrl = "SALESFORCE_URL/login/SelfRegister?expid=id";
var expId = "id";
var userPage = encodeURIComponent(window.location.href);
var appDetails = "response_type=code&" +
"client_id=CLIENT_ID" +
"client_secret=CLIENT_SECRET&" +
"redirect_uri=CALLBACK_URL&" +
"state=" + _id + "&code_challenge=" + code_challenge + "&code_challenge_method=S256&response_mode=query";
var encodedapp = encodeURIComponent(appDetails);
var startUrl = "/services/oauth2/authorize/expid?" + encodedapp;
var signUpUrl = baseUrl + "&startURL=" + startUrl;
window.open(signUpUrl, "_self");
};

Microsoft authorization with new tab

I need to implement login functionality with Microsoft via a new tab.
Currently our login process works with Microsoft in a way which is not really suited for our needs. The user clicks a login button, gets redirected to the Microsoft sign in page, enters his information and gets redirected back to our login page. This all happens on the same tab. In the code bellow is an example of this:
authenticateOffice(finallyCallback?: () => void): void {
finallyCallback = finallyCallback || (() => {
});
let currentUrl = location.href;
this.redirectLocationUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
let url = "https://login.microsoftonline.com/".concat(this.office365Domain, "/oauth2/v2.0/authorize?client_id=", this.clientId,
"&response_type=id_token&redirect_uri=", this.redirectLocationUrl, "&response_mode=fragment&scope=openid profile&state=12345&nonce=678910");
window.location.href = url;
}
Pretty straightforward and nothing too complex.
What we need to do in layman's terms is:
1. Open a new tab when clicking the login button
2. User enters his information on the Microsoft login page
3. When authorized, tab is automatically closed
4. Our login page then receives the "id_token" from Microsoft from oauth2 and with this I do the rest of my login logic
else if (!StringHelper.isNullOrEmpty(window.location.hash) && window.location.hash.startsWith('#id_token')) {
let response = window.location.hash;
this._office365Service.getOfficeId(response)
.subscribe((result: string) => {
let key = result;
if (key) {
this._loginService.processOfficeIdResult(key);
} else {
abp.message.warn(this._localizationService.localize('Office365User', this.localizationSourceName));
}
});
}
My question is this:
How can we regain or rather take control of this "new" tab and do something with it?
How can we know when authorization is complete?If it fails or is successful?
In my previous research all i could come by was the callback approach but how can you send a function to a new tab which knows when to close the tab?And how can you receive authorization information when the user is successfully authenticated?
var win = window.open("window.html");
And then what? You write a function which calls itself every second and checks for input?
(just throwing ideas here)

Redirect to clicked url with cookies.js

We normally use a prehome as the website of Forbes USA.
Every time we enter i.e. http://johnwho.url the page is redirected to a Welcome Home, and 8 sec later will be redirected to the original home , adding a cookie that will not show this pre-home again util 24 hores later.
like:
//Redirect
welcome = function() {
var cookie_name = 'welcome';
var value = true;
var go = Cookies.get(cookie_name);
if (go == null) {
Cookies.set(cookie_name, value, { expires: 1, path: '/' });
window.location = "/bienvenidos/"
} else {
return false;
}
}
window.onload = welcome();
But what if we want to redirect site wide, from an article or different url.
how can we change the redirect path to the selected(clicked) url??
What would be the best option to achieve this?
I know two ways: first you store all URLs which used to redirect into DB and use GET attributes which contains id from DB, another idea use GET attribute, which store URL.
For first solution URL looks like http://example.com/redirect/?urlID=100,
for the second issue -> http://example.com/redirect/?url=http://my-anothersite.example.com

JavaScript persist a search query through out the whole site

I'm currently fetching a query (e.g, http://localhost:49781/HTML/index.html?inputName=Marcus) from a html form using this following JavaScript:
function setSignedName() {
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
document.getElementById("signed_in_name").innerHTML += split[1];
} else {
document.getElementById("signed_in_name").innerHTML = "Not signed in";
}
running the script will get the result: Marcus.
I want this string to be persisted through out my site, so when the user navigates to another page the inputName will still be Marcus.
What is the best way of achieving this?
Edit: This approach is only for display/non-production use, I know using a server side language like PHP is the best approach.
I believe the best way is using localStorage. It works in all major browsers and it's easy to use:
function setSignedName() {
var userName = "";
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
userName += split[1];
} else {
userName = "Not signed in";
}
document.getElementById("signed_in_name").innerHTML = userName;
localStorage.setItem("userName", userName);
}
To access it:
var userName = localStorage.getItem("userName");
And this is it. Check for it in the Resources tab in Developer tools(F12) in your fav broswer.
You'll want to either repopulate it through GET parameters in your server side language, or if you want to hack it together, use a cookie and repopulate it with JavaScript on page load with "pushState".
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState()_method

how to force redirect to login page in javascript

I am building a website where I want users to have to log in to be able to view a certin page (kn this case it is called gallery.php) I implemented some code I found on this site, which redirects the user back to the login page when they click on the gallery link in the menu. However when I log in, and get redirected to the gallery again, the website does not acknowledge that I have logged in and redirects me back to the login page again. I am aware that questions like this have been asked before, but any help would be appreciated. My code is bellow
//from login.html
<!--//
/*This Script allows people to enter by using a form that asks for a
UserID and Password*/
function pasuser(form) {
if (form.id.value=="Admin") {
if (form.pass.value=="rycbar123") {
var sessionTimeout = 1; //hours
var loginDuration = new Date();
loginDuration.setTime(loginDuration.getTime()+(sessionTimeout*60*60*1000));
document.cookie = "SistaDansenSession=Valid; "+loginDuration.toGMTString()+"; path=gallery.php";
location="gallery.php"
} else {
alert("Invalid Password")
}
} else { alert("Invalid UserID")
}
}
//from gallery.php
<!--force login code-->
<script type="text/javascript">
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1) {
alert("You must be logged in to view this page")
location.href = "login.html";
}
else {
alert("login succesful")
} </script>
Thanks so much
Try changing:
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1)
to
if (document.cookie.indexOf("SistaDansenSession") < 0)
When you set the cookie, you are setting the cookie attribute 'SistaDansenSession' equal to the value 'Valid'. In your original code, you are attempting to retrieve a cookie attribute 'SistaDansenSession=Valid', whereas the attribute you want to retrieve is just 'SistaDansenSession'. When the cookie is set, the attribute exists, so it will have an index that is >= 0. In that case, the redirect to the login does not occur - which I think is your desired behavior.

Categories