Access javascript sessionStorage in php - javascript

In my Laravel project's app.js, I have this:
let isModalShown = sessionStorage.getItem('book_modal_has_shown');
if(!isModalShown) {
sessionStorage.setItem("book_modal_has_shown", "true");
$('#show_nudge_modal').modal('show');
This acts like a client-side check to stop the modal from coming out if the modal has already appeared (in the previous requests).
In my Controller, I have this:
$unreadBook = Book::getRandomUnreadBook();
return view('home')->with(['book' => $unreadBook]);
The problem is even if the modal does not appear on the client side, Book::getRandomUnreadBook() causes the database fetch operation. I want to add a server side check also to stop this useless database access.

Related

Can I do DOM manipulation within an Express POST request?

I'm working with basic HTML/CSS frontend, I currently have a landing page with a form on it that sends some data to a database. When the request is done, it is expecting some sort of response. In this case, I am re-rendering the page, however, I want to replace the form with some sort of a thank you message, something so the user knows that it has sent correctly. I have tried the solution of simply having a separate near identical page with the form removed and replaced, however, this kind of code cloning seems like an inefficient way to do it. Is there a way I could do some sort of front-end DOM manipulation from within my node app instead?
Generally, if you want to manipulate how the DOM looks server side you would need to render your entire page server side and then send it to the front end.
If you want to simply manipulate the DOM after a request is received on the front end, whic is a pretty regular practice for this type of stuff; regardless of the back end language(s) used, you can:
Submit form
Let user know form is submitting to server (Best practice for UX)
Once you receive your response, manipulate the DOM however you would like
For this use case, I've taken advantage of the async/await syntactical pattern which will allow you to wait for a response while not ending up in a nested callback pattern.
The attached snipped will fake a request to the server through a set timeout value, and echo what you put into the form back to the page. It's on a three second delay and uses AJAX to make the request.
*You can simplify this code by removing some logging and comments, but I've made it more verbose than necessary for learning purposes.
**I've purposely put the submit button outside of the form element so that it does not auto-post on submit. If you want to submit this way, you can use event.preventDefault() within the function, catch the event before it bubbles, and do this instead. Either way will work fine.
async function getDataAsync0(data) {
return new Promise(async (res) => {
setTimeout(()=>{
res(data);
},3000)
});
}
$(`#submitButton`).click(async () => {
// Create div to display what's going on
let statusAreaElement = $(`#statusArea`);
// Submit Event
statusAreaElement.html(`Submitted... Waiting for response...`);
// Cache input element
let inputElement = $(`#input01`);
// Cache form element
let formWrapperElement = $(`#formWrapper`);
// Cache success message div
let successMessageElement = $(`#successMessage`);
// Get value
let value = inputElement.val();
// Send value, await response;
let response = await getDataAsync0(value);
statusAreaElement.html(`Response returned -> ${response}`)
// Clear input element
inputElement.val(``);
// Hide form, show success message
formWrapperElement.hide();
successMessageElement.show();
})
#statusArea {
position: absolute;
left: 0;
bottom: 0;
}
#successMessage {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formWrapper">
<form>
<label for="input01">Form Input</label>
<input id="input01" type="text">
</form>
<button id="submitButton">
Submit Form
</button>
</div>
<div id="successMessage">
Thanks for your submission!
</div>
<div id="statusArea">
</div>
JSFiddle offers an echo service so I've also written the same code into a fiddle so you can see it actually call the server and echo back the response.
Here is that link:
https://jsfiddle.net/stickmanray/ug3mvjq0/37/
This code pattern should be all you need for what you are trying to do. Again, this request is also over AJAX so the DOM does not need to completely reload; if you are actually going to be making a regular post (without AJAX) to the server and then reload the page afterwards, you can do the same thing - or simply construct the new page you wanted to send to them server side and then redirect them from there.
I hope this helps!
Can I do DOM manipulation within an Express POST request?
No. The server builds up a response (a big chunk of html), that gets sent to the client which parses it and builds up the DOM. You cannot directly work with that from the server.
However you can:
1) Modify the html the server sends (have a look at express.render)
2) Run a clientide script that opens a connection to the server (websockets, AJAX) and then mutate the DOM there when the server sends something.

How clear all session elements when user log out in ASP .NET MVC 5?

I follow below code :
function My_Function() {
var x;
if (confirm("Exit?") == true) {
x = "Ok";
window.location.href = '#Url.Action("Login", "Account")';
Session.Abandon();
} else {
x = "Cancel";
}
}
I want to prevent is that , after logging out , then I click the back navigation button , I don't want to go back to the previous page.
Browsers can cache content locally. So no matter what you are doing on your server, after logging out, if the user clicks on the Back button, the browser can decide to get the last page from the local cache and display it.
In order to prevent this behavior you could serve all controller actions that require authentication with cache disabled. This can be achieved by decorating them with a custom [NoCache] filter. This filter will ensure that the proper response headers are set when serving actions that require authentication to prevent the browser from caching them.
This being said, please note that the Session.Abandon(); call should be done on your server - inside your Logout controller action that is supposed to clear the authentication cookies and session state.
Session.Clear and Session.RemoveAll are identical; the latter just calls the former. They immediately remove all items stored in the session, but the session itself survives. Session_OnEnd does not fire.
Session.Abandon doesn't actually clear the values immediately, it just marks the session to be abandoned at the end of the current request. You can continue to read the values for the rest of the request. If you write to the session later in the request, the new value will be quietly discarded at the end of the request with no warning. Session_OnEnd fires at the end of the request, not when Abandon is called.

Ajax inside wordpress security

Before I get to the question, let me explain how we have things set up.
We have a proxy.php file, in which class Proxy is defined with functions that call upon a rest for creating/editing/getting Wordpress posts, fields etc.
Then, we have a proxyhandler.php, in which Proxy class is initialized and serves as a handle between proxy.php and a javascript file.
In javascript file we have an ajax call to proxyhandler.php in which we send our secret and other data.
Now, the problem arises here:
We define the secret through wp_localize_script, by using md5 custom string + timestamp. We send the encripted string and timestamp through ajax to proxy handler, where we use the previous (hardcoded inside proxyhandler) string and timestamp to generate a md5 string again, and check the one sent against the one generated. If they are the same, we continue by doing whatever was requested, if they dont fit, we just return that the secret didn't match.
Now, the real issue comes here - by using wp_localize_script, the variable for the secret is global and as such, anyone can utilize it via dev tools and can send any ajax request to proxyhandler that they want.
What would be the proper procedure to make it more secure? We've thought of doing this:
Instead of using wp_localize_script, we put the script inside a php file, we define the secret using a php variable and then simply echo the secret file into ajax. Would this be viable, or are there any other ways?
Instead of sending an encrypted string in global scope, then check against it, you should use nonce in your AJAX request:
var data = {
action: 'your_action',
whatever_data: who_know,
_ajax_nonce: <?= wp_create_nonce('your_ajax_nonce') ?>
};
Then, use check_ajax_refer() to verify that nonce:
function your_callback_function()
{
// Make sure to verify nonce
check_ajax_refer('your_ajax_nonce');
// If logged in user, make sure to check capabilities.
if ( current_user_can($capability) ) {
// Process data.
} else {
// Do something else.
}
...
}
Depend on the AJAX METHOD, you can use $_METHOD['whatever_data'] to retrieve who_know data without needing to use wp_localize_script().
Also remember that we can allow only logged in users process AJAX data:
// For logged in users
add_action('wp_ajax_your_action', 'your_callback_function');
// Remove for none logged in users
// add_action('wp_ajax_nopriv_your_action', 'your_callback_function');
The final thing is to make sure NONCE_KEY and NONCE_SALT in your wp-config.php are secure.

global variables doesn't change value in Javascript

My project is composed by 2 html pages:
index.html, which contains the login and the registration form.
user_logged.html, which contains all the features of a logged-in user.
Now, what I want to do is a control if the user is really logged in, to avoid the case where a user paste a url in the browser and can see the pages of another user.
hours as now, if a user paste this url in the browser:
www.user_loggato.html?user=x#profile
is as if logged in as user x and this is not nice.
My html pages both use js files that contains scripts.
I decided to create a global variable called logged inizialized to false and change the variable to true when the login is succesful.
The problem is that the variable, remains false.
here is the code:
var logged=false; (write in the file a.js)
while in the file b.js I have:
function login() {
//if succesfull
logged=true;
window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";
Now with some alerts I found that my variable logged is always false. Why?
Javascript is not the way to go, as it runs on the client side. Even if there would be a way to share javascript variables between different requests, the user could manipulate them.
You have to take a server side technique for this (maybe PHP with sessions).
JS variables will reset on every submit/refresh. You could use sessionStorage or cookies for this purpose. For example:
Put this in your login form:
function login() {
window.sessionStorage[logged] = true;
window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";
}
And in your user_loggato.html, you can retrive it like:
function getLoginStatus() {
return window.sessionStorage['logged'];
}
Hope this helps.

Pass client side value to server side

I need to use a javascript variable value in server side.
Example:
JavaScript
var result = false;
CS Code
if(result)
{
Console.Write("Welcome..")
}
else
{
Console.Write("plz try again..")
}
Note
I don't want to post a hidden field.
With each request, any server side code will run and then any client side code will run. You can't switch between them at will.
Your options are:
Provide all the data to the client in the first place, then use JS to decide which of them to keep/delete/show/hide/etc
Use Ajax to make a second request to the server with the data you get from JS, return content, and then do something with that content in the JS callback function.
Make a second request to the server and load a complete new page.
Remember to build on things that work.
best way to do this use hidden fields...

Categories