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

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.

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.

Better name for a method than "isThis()"

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().

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.

How does one communicate between view controllers in a UINavigation type application?

I have a UINavigation based application that gathers information on various screens and eventually makes a web service request using all the parameters collected.
So I have A,B,C,D view controllers. A gets the name & number, it then pushes B onto the screen with some basic info ETC ETC until it gets to D where I actually fire off the web service.
The poor method I have been using is to duplicate class fields from A onwards. Meaning if I collect name, and number, then I make those the fields of B, which then adds a few fields, and then C has class fields of both A & B which seems like a poor programing practice.
What can I do to get access to class A's fields in class D? I have gotten certain ideas but not sure how valid they are.
1). Use NSNotification (Is this overkill?) If so how do I pass fields?
2). DO I just retain all 5 view controllers and just get the info at the end? (seems very inefficient)
3). Should I just instantiate a NSObject class called Payload and just set its fields every time I bounce from one view controller to the next? (If so do I create it in class A? What if user navigates back to class A, will it then get reset ETC ETC)
As you can tell I have tried to find a solution and I am fairly new to it. Some detailed suggestions would be highly appreciated.
Depending on situation, there are several ways that seem appropriate.
Get to know MVC Design Pattern
Classes are not data storage. If class doesn't have interface to interact with represented object, excluding accessors, you're doing it wrong.
3.
I have a UINavigation based
application that gathers information
on various screens and eventually
makes a web service request using all
the parameters collected.
So, your web request is based on parameters gathered from various views. Why not create an
model of said request? MyRequest or something like that :) Or several more specific variants, sharing common parent class? This generator holds logic, gathers data and parameters as you advance trough views and provides NSUrlRequest at the end to WebView or maybe different kind of object which is NSURLRequest delegate and conforms to UITableViewDataSource/Delegate protocols to be used to display downloaded data.
I'd go for 3) and yes you should create it at the beginning (Class A).
But maybe user go back to Class A to change the value on purpose so resetting it doesn't seem to be a problem.
Why not use a singleton object and pass it around?
The advantages of this method are:
There's only one instance whose
reference is being passed around
between viewcontrollers
Changes you
make are reflected the next time you
access this object from another view
controller
And to answer one of your questions, NSNotification allows us to pass objects along....
Here's a good example on singleton objects in iOS by Matt Galloway. It's the one I always refer to:
http://www.galloway.me.uk/tutorials/singleton-classes/

Wicket, page stack, and memory usage

A Wicket application serializes and caches all pages to support stateful components, as well as for supporting the back button, among other possible reasons. I have an application which uses setResponsePage to navigate from screen to screen. Over a pretty short amount of time the session gets rather large because all of the prior pages are stored in the session. For the most part, I only need the session to contain the current page, for obvious reasons, and perhaps the last 2 or 3 pages to allow easy navigation using the browser's back button.
Can I force a page to expire after I have navigated away from it and I know that I don't want to use to back button to that version of the page? More generally what is the recommended way to deal with session growth in Wicket?
http://apache-wicket.1842946.n4.nabble.com/Wicket-Session-grows-too-big-real-fast-td1875816.html
If you use loads of domain objects on your page, which are eventually tightly coupled to other domain objects, be sure to avoid serialization for these!
Have a look at
LoadableDetachableModel for wrapping domaing objects
DataView and IDataProvider for displaying list of domain objects
Thou shalt not stuff domain objects into instance variables of components.
Thou shalt not make domain object references final in order to use them in anonymous subclasses.
Thou shalt not pass a mere List of domain objects to a ListView.
Perhaps, when subclassing WbeRequestCycle in your Application class, you might gain control of a page's lifetime in the pagemap... haven't tried it, though
In order to avoid Session choke due to continuous stacking of byte-stream due to serialization in a session and memory usage piling , you can use detachable models by using hooks to arrange for their own storage and restoration at the beginning of each request cycle , this way you have complete control over models containing byte-stream of pages not required in the session or navigable through 'Back' button.