App-wide authentication handler for Javascript functions? - javascript

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]*/);};

Related

is there any alternative of Javascript confirm?

I have created one application. In the application I have used javascript confirm function a lot.
confirm("Do you want to proceed");
I don't like the default UI of confirm. I want to use customized confirm with better UI.
Problem:
I got some options for customized confirm. But if I will use them I need to change all default confirm methods(needs lot of changes).
Is there any way to achieve this in minimal change.
like:
window.confrim = function() {
/*
What logic I should write which will return the
value(true or false) selected by user.
*/
}
I have one JS file which is imported in all HTML files.
So I can place the above function logic in the common JS file.
The biggest issue with customising confirm is that the native confirm is blocking. So you can just write:
if( confirm("Continue?")) {
doStuff();
}
But your own code can't do that. Instead, you would need to create some kind of callback. An example might be:
myConfirm("Continue?",function() {
doStuff();
},function() {
cancelStuff();
});
Exactly how you implement this is up to you - I actually have a more flexible version of this on my projects, where I make a call of the form:
Dialog("Title", "Contents", [array of buttons]);
// [array of buttons] being an array of objects like:
{
"text": "Button text",
"action": function() {doSomething();},
"optional_extras": "more stuff"
}
The cool thing about writing your own stuff is that you can extend it freely to suit your needs as the project grows.
Confirm box is part of the browser not the DOM. So, its not possible to modify that. You can try custom confirm boxes like http://jqueryui.com/dialog/#modal-confirmation OR
http://onehackoranother.com/projects/jquery/boxy/

How to structure/modularize my NodeJS server-side processing?

I have some processing logic that is currently in my AngularJS front end, modularized away into services in order to keep my controllers clean. However, I need to bring some of this logic to my NodeJS backend.
For example:
function processPost(post){ // In reality I have many many functions so I would like to modularize
if(post.verified == true){
post.status = 'Safe to trust!'
}
}
Where should I put this code in my backend and how can I modularize it?
Should it be in the middleware or perhaps in my routes?
I would put it in a commonjs module and then use it in the route. This way you can use the exact same file/code on the server and client to verify the form data or whatever that function does. You'd have to load it on the client with something like systemjs or webpack. By the name of the function, I would guess you want to run that whenever the user posts a certain form, so putting it in the route, which is the code that will be called whenever they post, would make the most sense to me.
module.exports = function processPost(post){
if(post.verified == true){
post.status = 'Safe to trust!'
}
}
If you have multiple functions you'd like to export from one file you could do:
module.exports.processPost = function processPost(post){
if(post.verified == true){
post.status = 'Safe to trust!'
}
}
module.exports.processGet = function processGet(){
//Do work
}

Forcing modules to have a specific function. eg implement an interface?

Simple in java, but how do I ensure the modules that are registering with my event bus for topic notifications have the required callback method on them?
All my modules are following the revealing module pattern and as such are defined like the following
namespace = (function() {
//Private stuff
return {
method1 : method1
}
})();
I just need to ensure the module has a notify method on it which takes a single argument. The module can be responsible for unmarshalling the payload data into the format it is expecting
Thanks
I really want to help but I'm not sure I understand your terminology. I'll answer based on my limited understanding and adjust as necessary
Sounds to me like you want to make sure the object returned has a property called notify on it, which is a function that accepts one function parameter only. If this is correct, there are two places you can ensure all modules meet your requirement.
Inside the Event Bus
If you wrote the event bus, you can write a few lines of code inside it to make sure that if a module doesn't come with the 'notify' property on it, the event bus will not subscribe the module to the event. Something like this:
if( typeof module.notify !== 'function' ){
// do error handling then ...
return false;
}
External Function for Registering Modules to Event Bus
If you didn't write the event bus, you can create an external function that is responsible for ensuring the standard. Think of it as a wrapper around #1.
function registerToEventBus( module, event ){
if( typeof module.notify !== 'function' ){
// do error handling then ...
return false;
}
// register event to event bus then ...
return true;
}
Personally I'd recommend using #2
That way you wouldn't need to know a thing about the event bus itself to implement this.
You get the added benefit of being able to keep the event bus strictly for events and not complicate it by adding the module format enforcement into it.
You will be able to take the event bus as is to another project, drop it in and edit your enforcer function to meet this project's specificiations with absolutely no risk of breaking the event bus accidentally.
I hope this helps. If there's any place I misunderstood you, let me know and I'll give it my best shot to fix.

ASP.NET MVC. Check if user is authorized from 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.

Javascript functions

We are attempting to only make available certain functions to be run based on what request address is.
I was wondering how we could do this:
if(condition1)
{
$(document).ready(function() {
...
...
// condition1's function
});
}
else if(condition2)
{
$(document).ready(function() {
...
...
// condition2's function
});
else if...
I was wondering what a good pattern would work for this? since we have all of our functions in one file.
It depends on what your conditions are like...
If they're all of a similar format you could do something like
array = [
["page1", page1func],
["page2", page2func],
...
]
for(i=0; i<array.length; ++i)
{
item = array[i];
if(pageName == item[0]) $(document).ready(item[1]);
}
I like Nick's answer the best, but I might take a hash table approach, assuming the 'request address' is a known fixed value:
var request_addresses = {
'request_address_1': requestAddress1Func,
'request_address_2': requestAddress2Func
};
$(document).ready(request_addresses[the_request_address]);
Of course, request_addresses could look like this as well:
var request_addresses = {
'request_address_1': function () {
/* $(document).ready() tasks for request_address_1 */
},
'request_address_2': function () {
/* $(document).ready() tasks for request_address_2 */
}
};
I don't see any problem with that. But this might be better:
$(document).ready(function() {
if (condition1)
// condition1's function
else if (condition2)
// condition2's function
...
});
It would probably be cleaner to do the site URL checking on the server (if you can?) and include different .js files depending on the condition, e.g.
** Using ASP.NET MVC
<html>
<head>
<%
if(Request.Url.Host == "domain.com")
{ %><script type="text/javascript" src="/somejsfile1.js"></script><% }
else
{ %><script type="text/javascript" src="/somejsfile2.js"></script><% }
%>
</head>
</html>
This way, each js file would be stand-alone, and also your HTML wouldn't include lines of JS it doesn't need (i.e. code meant for "other" sites)
Maybe you could give more detail as to what exactly you are doing, but from what I can tell why wouldn't you just make a different JS file containing the necessary functions for each page instead of trying to dump all of them into one file.
I would just leave all of the functions in one file if that's the way they already are. That will save you time in rework, and save the user time with reduced latency costs and browser caching. Just don't let that file get too large. Debugging and modifying will become horrendous.
If you keep them all in one file, Add a script onn each page that calls the one(s) you want.
function funcForPage1() {...}
function funcForPage2() {...}
Then, on page1
$(funcForPage1);
etc.
Instead of doing what you're planning, consider grouping the functions in some logical manner and namespace the groups.
You'd have an object that holds objects that holds functions and call like this:
serial = myApp.common.getSerialNumber(year,month);
model = myApp.common.getModelNumber(year);
or
myApp.effects.blinkText(textId);
If you wanted to hide a function or functions per page, I suppose you could null them out by function or group after the load. But hopefully having things organized would satisfy your desire to clean up the global namespace.
I can't think of a particularly elegant way to achieve this using only JavaScript. If that's all that's available to you, then I'd at least recommend you use a switch statement or (preferably) a hash table implementation to reference your functions.
If I had to do something like this, given my development environment is fully under my control, I'd break up the JavaScript into individual files and then, having determined the request, I would use server side code to build a custom bundled JavaScript file and serve that. You can create cache copies of these files on the server and send client side caching headers too.
This article, which covers this technique as part of a series may be of interest to you.

Categories