Better name for a method than "isThis()" - class

I have one class called OAuthLogin that supports the login of a user via OAuth. The website supports also a "traditional" login process, without OAuth. The two flows share a lot of code, where I need to differentiate them sometimes.
I have a static method OAuthLogin::isThis() that returns a boolean whether the current login flow is OAuth or not (by checking session variables and URL parameters).
I don't like the name of the method but I can't think of a better one - I guess that is a common concept, therefore there should be some kind of pattern.
I don't like OAuthLogin::isThisOAuthLogin() because is redundant.
I would like to avoid Login::isThisOAuth because I would like to keep all the code in the OAuthLogin class.
Should I go for OAuthLogin::is()? Anything better than that?
Thanks.

Your OAuthLogin class should only have one responsibility, and that is to enable a user to login using OAuth; this class should have no knowledge of the "traditional" login process. A person who sees this class name (e.g. StackOverflow users!) will assume that this class is only responsible for login functionality using OAuth.
As your two login processes share a lot of code, then you really should refactor your code so that you have a base class with the common code, and then have separate classes for OAuth and Traditional login which will both inherit from the base class. When your code executes you should then instantiate the login class that is appropriate for that user's session.
Also as your OAuthLogin class is static then how will it be able to handle many users logging-in at the same time? Hence another good reason to refactor it so that it is not static.
If you absolutely cannot refactor, then without seeing your code, it sounds as if the OAuthLogin class is really a mediator i.e. it encapsulates how a set of classes interact (in this case your login classes). So instead of using the name "OAuthLogin" you could call it "LoginMediator". You could then have the properties:
LoginMediator.isOauthLogin
and
LoginMediator.isTraditionalLogin
to distinguish between the different types of login which the mediator is using for that particular session. Though instead of using the word "Traditional" replace this with the other authentication mechanism you actually use (e.g. HTTP Basic Authentication, HTTP Digest Authentication, HTTPS Client Authentication etc.)
Note how I have chosen intention-revealing names for these properties. If a stranger was to read your code (e.g. me!) they would struggle to understand the purpose of "is()" and "isThis()" from just the method signature.
However, in the long run I really do recommend that you refactor your code so that you have classes with discrete responsibilities, as you will find that naming methods will be far easier as a result.

I would add a method to the base class which just returns the type of the login.
Class (pseudo-code)
class Login
method class
return self.class # Returns the current class.
end
end
Usage would be (also pseudo-code):
if currentLogin.class == OAuthLogin
# ..
else
# ..
end
This would let you add more types later on, without having to add type-specific methods for each login type, leaving the control flow outside of your classes.

I suggest one of:
OAuthLogin::isCurrent()
OAuthLogin::isCurrentLogin()
OAuthLogin::isCurrentFlow()
OAuthLogin::isCurrentLoginFlow()
OAuthLogin::isActive()
OAuthLogin::isActiveLogin()
OAuthLogin::isActiveFlow()
OAuthLogin::isActiveLoginFlow()

How about OAuthLogin::isUsed()?

I suggest OAUthLogin::isLoggedIn().

Related

How to create 'globally' scoped variables that are global only during one request?

When a request hits my dancer2 app I want to set up an object that is accessible by all packages involved in handling this request.
How can I make sure that this object has a scope only within this individual request and is not accessible by other requests?
Specifically this object should be filled with messages of all kinds (errors, warnings, debug messages, etc.) as execution travels through my libraries.
Obviously, those messages are request-specific and I am afraid that naively declaring a global reference to this message object is exposing it to all requests hitting the app.
I was thinking about creating an instance of this message class in the router and then passing a reference to it throughout all methods involved in handling this request.
My gut feeling tells me that I am missing something fundamentally here architecture-wise regarding dancer2, so I decided to ask you. It's my first post here, by the way, so I apologize for any shortcomings my question may have.
It looks to me like you could use a var to hold your object.
See https://metacpan.org/pod/distribution/Dancer2/lib/Dancer2/Manual.pod#var
If you need it to be accessible even from methods that aren't aware of Dancer, you could use a var and also store your object in a global variable using a weak reference.

asp.net mvc accessing class fields from a custom auth attribute

I am using a custom AuthAttribute to determine whether a user can access a controller and/or actions. The problem is I have to duplicate information and EFx connections in the attribute that already exist on the class that is being adorned.
My question is whether there is a way to access the fields on the adorned class from the custom AuthAttribute? I am trying to avoid having to re-architect the software in a way that would provide a single point of access since that would open up a different can of worms.
I believe I have found an answer that works. I welcome all comments on this solution.
Rather than have the attribute gain access to the properties and fields on the controller it adorns you can share values between them in a thread-safe way through the common HttpContext object. So if you are being extreme like I am and are trying to cut down on duplicate calls to your database in both the authattribute and the adorned controller action then pass the results forward. What that means is the authattribute will be called first and you can stash the retrieved values in the "Items" collection off the HttpContext object passed into the AuthorizeCore(..) method. You can then retrieve the same value in a THREAD-SAFE way through the HttpContext object in the controller.
example to save value within the AuthorizeCore(..) override of the AuthAttribute:
httpContext.Items.Add("fester", "bester");
example to retrieve value inside the subsequent call to the Controller/Action:
this.HttpContext.ApplicationInstance.Context.Items["fester"];
I have to warn you this is only a possible implementation that appears to work in simple testing. Personally it feels like a hack and there has to be a better way. I would also state this is in pursuit of a dubious performance benefit. It should cut down on the number of database and/or network calls by cache'ing retrieved data in the HttpContext so you don't have to repeat the calls in both the authattribute and the adorned Controller/Action. If you don't have a web site that gets a huge volume of calls then I would warn you against this.
I hope someone recommends something better on this page. I will keep an eye on how this works on my web site and let y'all know if it behaves and is truly thread-safe.

Global exception handling for REST calls in Ember-CLI

In my ember-cli app I use a token based approach to communicate with a secured REST interface on the server side. As tokens expire after some time, I would like to realize the following behaviour:
As soon as the client tries to access the REST service with an expired token, I would like the user to be redirected to the login screen.
Right now I use the 'catch' function on the store's find method while fetching data in the route's model callback. This works quite well. As a matter of fact, there are more REST invocations than the ones that refer to the model store.
What would be the best practice to deal with this situation? In what place should I implement the (exception) handling? As this seems to be a crosscutting concern, I'd like to implement it in a central place.
I prefer to follow an optimistic approach, thus not checking the validity of the token on each and every transition. It will be sufficient if the redirect will take place the moment the application tries to communicate with the REST interface (ie as soon as it gets the error message from the server).
Thanks
You may want to consider the global jquery hooks so you can respond to an Auth fail uniformly. See:
http://api.jquery.com/category/ajax/global-ajax-event-handlers/
It's up to you if you want to set window.location or lookup your application controller and use transitionToRoute() for switching to the login route. Make sure that if you use Ember functions to put your code in an Ember.run.once() from your jquery hook function so it occurs on the Ember run loop.
You could also consider using Ember SimpleAuth (which kind of locks you into its paradigm) or even better and a safer long term priposal IMO, doing it from scratch by first following these tutorials:
- http://coderberry.me/blog/2013/07/08/authentication-with-emberjs-part-1/
- http://coderberry.me/blog/2013/07/08/authentication-with-emberjs-part-2/
And then this which is newer and incorporates the above tutorials:
- http://webcloud.info/blog/2014/04/07/emberjs-authentication-the-right-way-javascript-version/

Cross-Activity references using GWT with Gin

I have a GWT MVP application using Activities and Places. This is inspired by Mauro Bertapelle's sample (in this thread), apparently based on some of Thomas Broyer's work.
Here's the problem: I have LoginActivity make an RPC call, which for a successful login, returns a User. This user has a role (e.g., admin, regular user, guest). Several Views and Activities, including a NavigatorView, depend on this role for what they show or do. How do I get this User instance to the other Activities?
I do not have a ClientFactory; injection (Gin) is used for instantiating the Views in the ActivityProviders which provide my Activities/Presenters, and the ActivityProviders are injected into my ActivityMapper. So this may reduce to a Gin question: how do I get the user reference where it's needed? This seems to be similar to this SO question about global references in MVP.
Consider me a Gin newbie, this is my first attempt at using it. I'm guessing there is a "Gin way" to make this happen, but I don't know Gin well enough to know the best way to do this (if Gin should be used at all).
Much thanks.
Edit 1: Despite my best efforts searching SO for a similar question, I just found this question which is pretty much identical to mine (is the SO algorithm for finding "Related" links better than the search?). I'm thinking that the Gin answer by David is on the right track.
I don't think that an EventBus solution is possible. I'm following the Google guidelines which involve instantiating Activity at every Place change, so a single Event by itself will not suffice.
Something that I'm using on the server-side with Guice, and would work just as well on the client-side, is to bind to a custom Provider. In your case though, you'd have to make the provider a singleton and push the value into it from your RPC callback (rather than pulling it from some context).
You'd first need a specific provider:
#Singleton
public class CurrentUserProvider implements Provider<User> {
private User currentUser;
public User get() { return currentUser; }
public void setCurrentValue(User currentUser) {
this.currentUser = currentUser;
}
}
You'd bind User to the provider: bind(User.class).toProvider(CurrentUserProvider.class)
In your RPC callback you'd inject a CurrentUserProvider so you can setCurrentValue but everywhere else you'd inject Provider<User> to keep CurrentUserProvider as an implementation detail. For very short-lived objects, you could directly inject a User value rather than a Provider<User>.
If you need to notify objects of the value change, you could dispatch an event on the global event bus.
Alternately, you could always use the concrete CurrentUserProvider type (which wouldn't have to implement Provider anymore) and possibly make it a HasValueChangeHandlers so you could register listeners on it rather than on the event bus (but you'd have to clean-up after yourself in your activities' onStop and onCancel to avoid memory leaks, whereas it's taken care of automatically if you register handlers on the event bus in onStart).
(if you ask me, I'd rather go away with authenticating from within the app whenever possible)
I had similar requirements on a recent project.
When I get a reply from login (or logout) RPC I send a custom AuthenticationEvent on EventBus. All activities that are interested in this listen for this event. AuthenticationEvent has a reference to AppUser object which is null if user just logged out. AppUser contains all necessary data (privileges, groups, etc..) so that activities can inspect it and act upon it.
About global references: you can have a class with static methods providing data that you need. This class internally holds singleton references to needed instances. In my example I have static method AppUtils.getCurrentUser(). Internally it holds a reference to AppUser and also listens to AuthenticationEvent to set/reset this field.
As a side note: don't rely on client side to enforce access restrictions - you should separate your RPC servlets into two groups: public and private. Public can be accessed by anybody (this is basically login/logout RPC and some other public info RPC), while private RPC requires user to be authenticated. Access restrictions can be set per path/servlet: http://code.google.com/appengine/docs/java/config/webxml.html#Security_and_Authentication
Update:
As you noted, class with static methods is not advisable in this setup, because it is not replaceable and this prevents testing (which is the whole point of using GIN).
The solution is to inject a utility class holding globals (AppUtils) into activities that need the globals. AppUtils should be declared singleton in GIN configuration as one instance is enough for the whole app.
To use Provider or not is just a question if you want to delay the initialization of dependencies (AppUtil is dependency). Since AppUtils is a singleton for the whole app it makes no sense to have it lazy initialized.
Sometimes you will have a situation where you have multiple Activities shown on screen (in my case it was MenuBar and InfoBar). In this case, when user logs in you will need a way to notify them of the change. Use EventBus.

Should I use singleton - Http Connection to the server - Iphone App design

So I've been reading about the pros and cons about using Singleton, and I have a scenario which I'm not sure if I should use one, and I thought consulting you guys.
I'm writing an Iphone app which once in a while have to communicate to the server (HTTP) information about the user logged in.
This web service is getting called from different parts of my application.
What I actually need are 2 type of classes:
Responsible for communication with the server - responsible for http setting,the url,header,parameters and etc.
2.classes for each type of web service api - for exmpale UpdateUserInfo Class or SendResults Class. This c
The 2nd class would use the 1st , and all through the app I would need many calles to the 2nd classes.
Should I use Singleton to any of theses ? What is the best way to design it ?
Thanks guys!
Edit:
Example for the 1st class(Let's call it DataDownloader) method would be :
(NSData *) downloadDataWithRequest:(NSURLRequest *)
{
ASIHTTPRequest *dlRequest = [[ASIHTTPRequest alloc] initWithURL:[request URL]];
[dlRequest setTimeOutSeconds:20];
if(retryNum < 1)
retryNum = 1;
[dlRequest setNumberOfTimesToRetryOnTimeout:retryNum];
// and more of the same
}
ASIHTTPRequest is something we're using as an HTTP wrapper.
Now I wouldn't want to call this sequence of function each time I want to send the server an HTTP request, So the option would be to put that inside a dedicated class and create a new instance, or using a singletion.
What I can do for example is Using something like that :
[[UpdateUserInfo sharedInstance] updateInfo:info]
Which can be implemented by setting up a NSURLRequest using the param info , and calling
[[DataDownloader sharedInstance] downloadDataWithRequest:InfoUrlRequest]
Now, assuming the http request are asynchronous , I still can spawn multiple at the same time.
I hope it's clearer now.
What do you think is the best way to design it ?
I wouldn't see the singleton pattern as being a useful solution to the problem you're trying to solve. It's really designed as a technique to control access to a single/finite resource, which isn't meaningfully the case from what I can tell.
For example, is there any reason why you wouldn't permit a user to carry out two network related activities at the same time?
Incidentally, out of interest have you looked at Cocoa classes such as NSURLConnection? I'm not sure you'd need a lower level class to manage the server communications as you're envisaging - this class might suffice. (Had to tell without knowing more about what you're trying to achieve.)
Also don't forget ASIHTTPRequest. It's a full featured network library
http://allseeing-i.com/ASIHTTPRequest/
I usually (and that's personal preference) have one singleton that controls the network management (a singleton and facade pattern in one) as to not having more than the 5 allowed connections. Could be possible for you as well. That would be a singleton for part of your task 1.
But as BobC has already pointed out, ASIHTTPRequest should do everything you need.
Don't reinvent the wheel!
I use the singleton pattern to control access to a web-based API that uses ASIHTTPRequest, and it works very well. ASI uses NSOperationQueues for asynchronous requests, so you don't need to worry about requests clobbering each other.
Because I don't know the order that requests are returned, I sometimes allow my public API methods to supply userInfo dictionaries so my callbacks have some context when they fire.
I would use the Service Locator pattern to obtain each of the services needed in your application. There are a couple different ways to create the service locator. I prefer configuration at initialization over configuration during runtime.
http://en.wikipedia.org/wiki/Service_locator_pattern