ASP.NET MVC. Check if user is authorized from JavaScript - javascript

I'm using ASP.NET MVC Framework 3 and Forms Authentication. I know, how to check on servers side, if the user is authorized for some action (with [Authorize]) and I know, how to check this within an action or a view (with User.Identity.IsAuthenticated or other members of 'User').
What I'm trying to do - is to define some JavaScript code, that will be executed differently, depending if the user is authorized.
Consider such script on the page:
<script>
function Foo(){
if(userAuthorized)
alert("You\'re in the system");
} else {
alert("You\'re not authorized");
}
<script>
Function Foo() is triggered by some event, say click. And I'd like to have an ability to check, if user is authorized, on clients side.
The best solution I've came up with is to actually render global variables initialization in view. Like this:
#if(User.Identity.IsAuthenticated)
{
<script>
var userAuthorized = true;
</script>
}
else
{
<script>
var userAuthorized = false;
</script>
}
But it doesn't seems to me as a good approach. Are there any other ways?
Thanks in advance.
PS: This is a usability issue, of course I'm doing necessary checks on server.

I like the idea in #Gaby's comment, though I am not sure whether that's doable since I don't have the whole picture on your project.
At the very least you can simplify your code by doing...
<script>
var userAuthorized = #User.Identity.IsAuthenticated.ToString().ToLower();
</script>

Another couple of options would be to use a custom HTML data- attribute or create a simple ajax request that asks the server if the user is authenticated.

Related

A new Cookie is added instead of replacing existing one

I just finished localizing my web application using spring boot configuration as a base.
#Bean
public LocaleResolver localeResolver() {
return new CookieLocaleResolver();
}
Due to a requirement one is supposed to be able to change locale/language of the website by pressing a button. Said function is implemented with a little bit of JS and a cookie.
<script>
function updateCookie(lang) {
let name = "org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE"
document.cookie = name+"="+lang
location.reload()
}
</script>
<a onclick="updateCookie('de')" class="flag-icon flag-icon-de mr-2"></a>
The idea is to update said cookie on click of a button and use it throughout the whole application. This works fine until I am trying to call a specific endpoint in my application.
In order to debug my application I use:
window.onload = function () {
alert(document.cookie)
}
Now to my problem:
When User-Testing the application this is the alert-feedback:
org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=de
Switching to other pages, refreshing, changing language etc. properly resets the cookie with a different value.
When calling a specific endpoint though, I get the following alert:
org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=de;
org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=fr
Instead of resetting/changing the existing cookie, a new one is added with the value 'de;'. A seemingly random semicolon is added.
This doesn't happen with endpoints using similar logic and almost identical implementation.
There is no further logic outside the little bit of JS code I've posted and I'm not touching the cookie in the backend.
Unfortunately I'm out of ideas. Any tips/help would be appreciated.

How to override the crowd-html submit button to include additional data

I'm working on a fairly simple form using crowd-html elements, which makes everything very simple. As part of our study, we want to see how workers interact with the form, so we have a bunch of basic JS logging. That is all prepared as a JSON and the idea is to log it using AWS API Gateway and AWS Lambda. The code all seems to work in unit tests, but not in the real form. I am trying to do this:
document.querySelector('crowd-form').onsubmit = function (e) {
if (!validateForm()) {
window.alert("Please check the form carefully, it isn't filled out completely!");
e.preventDefault();
} else {
let event_data = {
'specific_scroll_auditor': auditor_scrolled_pixels_specific.submit_callable(),
'specific_clicks_auditor': auditor_clicks_specific.submit_callable(),
'mouse_movements_total': auditor_mouse_movement_total.submit_callable(),
'on_focus_time': auditor_on_focus_time.submit_callable(),
'total_task_time': auditor_total_task_time.submit_callable(),
'focus_changes': auditor_focus_changes.submit_callable()
};
log_client_event('auditors', event_data);
post_event_log()
}
}
Note that the validation bit works, but the logging does not. I've tested post_event_log() on it's own, and that works just fine, so it seems like either 1) for some reason I never get to that else clause, or 2) the submission happens more quickly than I can call the logging functions. (but why, since the validation works?)
I also tried this, borrowed from the turkey code (https://github.com/CuriousG102/turkey) which was our inspiration.
$(window).ready(function () {
window.onbeforeunload = function () {
let event_data = {
'specific_scroll_auditor': auditor_scrolled_pixels_specific.submit_callable(),
'specific_clicks_auditor': auditor_clicks_specific.submit_callable(),
'mouse_movements_total': auditor_mouse_movement_total.submit_callable(),
'on_focus_time': auditor_on_focus_time.submit_callable(),
'total_task_time': auditor_total_task_time.submit_callable(),
'focus_changes': auditor_focus_changes.submit_callable()
};
log_client_event('auditors', event_data);
post_event_log()
}
});
That also doesn't work. I would prefer to do this in some simple way like what I have above, rather than completely rewrite the submit function, but maybe I have to?
your custom UI is placed inside a sandboxed iFrame by Ground Truth. It does that only for the real job, and not for previews (you're code might work while previewing the UI from AWS Console). The sandbox attribute on the iFrame goes like this
sandbox="allow-scripts allow-same-origin allow-forms"
Refer https://www.w3schools.com/tags/att_iframe_sandbox.asp for descriptions. Ajax calls are blocked regardless of the presence of allow-same-origin (not that you could change it in any way). See for a thorough explanation IFRAME sandbox attribute is blocking AJAX calls
This example might help.
It updates the onSubmit function to do some pre-submit validations.
https://github.com/aws-samples/amazon-sagemaker-ground-truth-task-uis/blob/master/images/keypoint-additional-answer-validation.liquid.html
Hope this helps. Let us know if not.
Thank you,
Amazon Mechanical Turk

Adding Changes Saved Javascript Popup

This is a MVC3 project using razor. Instead of displaying another view to inform the user that the changes have been saved successfully I would like to simply fire a JavaScript popup informing them... Everything I have found on the web either opens a whole new browser window, or misses what I am trying to accomplish all together... I know there is a simpler way to go about doing this but this is where I am... At the end of the controller function that does the save on the return I simply use redirect and send it to another controller function that displays a screen saying "Changes Have Been Saved Successfully" then the user clicks a button there which will take them back to the index page... IMO this is a bit shotty and think it can be cleaned up through the use of Javascript...I have not found any luck on this yet.. Currently the below code is what I am using:
Function SomeFunctionName()
db.SaveChanges()
Return RedirectToAction(ChangesSaved)
End Function
Function ChangesSaved()
Return View()
End Function
And the javascript that I have implemented in the ChangesSaved view.
#Code
ViewData("Title") = "ChangesSaved"
End Code
<script type="text/javascript">
alert("Changes Have Been Saved Successfully");
</script>
There are a few problems with this though...
How do I tell the javascript When the user clicks OK it should take them to another page.
I did just try the below and since I am very new to java/javascript it failed:
var r=alert("Changes Have Been Saved Successfully");
if (r == true) {
#html.Action("***********","Admin")
}
If I were you I would post your form using Jquery. Then you can set a callback. In Mvc you can return JSON data, a simple value indicating that the save worked would be enough. Then you can call your alert although you might consider using a jQuery UI dialog as it's way more flexible. If you haven't ever used jQuery I wouldn't be afraid, it's easy and there is a lot of great examples out there.
Take a look at this http://api.jquery.com/jQuery.post/ and this, ASP.NET MVC controller actions that return JSON or partial html

App-wide authentication handler for Javascript functions?

What is the best approach to handle authentication on a bunch of Javascript actions on a page without littering the code base with "if authenticated()" checks?
For example: we have 10 like buttons, some comment buttons and a few other actions that require authentication. When a user is not authenticated, we want to redirect them to a login/signup page. However, we want to avoid littering the code with if (user.isAuthenticated()) { xxx } calls. In our particular case we want to use these mostly for events in backbone, although I don't think that matters for the general question.
With the help of underscorejs. You can write something like this:
function authWrapper(func){
if (user.isAuthenticated()) {
func.apply(this, _.rest(arguments));
}else{
...
}
}
Suppose you're using jQuery, when binding the events, write this:
$(...).bind('event', _.wrap(function(...){...}, authWrapper));
or
$(...).bind('event', _.wrap(thehandler, authWrapper));
How about creating a method that does the checking, using a callback for the method that should be called if authentication is ok? Something like:
function checkNdRun(cb,params){
params = [].slice.call(params);
if (/*[authenticationCheckingLogic here]*/){
cb.apply(null,params);
} else {
alert('please login first');
}
}
//usage example
somebutton.onclick =
function(e){checkNdRun(functionToRun,e,/*[other parameters]*/);};

javascript mvc and ajax form submitting

I just started to investigate mvc on javascript client side (JavaScript MVC). Everything looked great until I got to form submitting :) View part won't do it, that's simple. Event is attached in Controller, so Controller is good place to validate form data, but I'm not sure I want my Controller to know specific server address (were to post my form), so would be great to have a method in Model, but then I don't want my Model to know about my Form (which is actually html structure...).
Well, what do I miss about MVC conception? I am also not sure I want to serialize my form in Controller and then pass it as parameter to my Model. For now, the only option I see to make Model independent is to have JavaScript structure (entity), which will be filled by controller (based on form data) and will be passed to the Model method to be saved on server. Very smplified code:
Info = {
name,
address,
// 15 more properties
...
}
InfoController = {
...
onFormSubmit: function() {
...
info.name = document.getElementById("info-name").value;
info.adress = document.getElementById("info-address").value;
...
InfoModel.save( info );
}
}
InfoModel = {
...
save: function( info ) {
// here some code to setialize info object
// send it to server
...
}
}
But it makes my code too complicated (comparing to simple form serizlization by some side frameworks and just sending it..). What's the right choice?
Just answering my own question. Short answer - yes, I was right with my assumptions ;)
I took a look at JavaScriptMVC, and noticed one simple thing I missed, a simple function can be developed which will create javascript object based on form (they have function called formParams which performs this type of converting). This way my controller is simplified:
InfoController = {
...
onFormSubmit: function() {
...
var info = $infoForm.formParams();
InfoModel.save( info );
}
}
Now it does not look that complicated, and its advantage is that there is one place (model) which knows how to save data (validation; url to send; some other stuff like add this entity to client side 'storage'; firing an event that something new is going to be created; whatever else according to our needs), and if I have one more place, or control flow to perform this operation again I won't write this code again, and it does not depend on presentation (is it form, or just set of inputs, wizard etc.). Also Model becomes quite reusable.
Actually before using this approach we had something similar, but it was not that structured (among different presentations for my application which can run javascript).

Categories