MVC Security problems in my application - Best strategy for separating logic? - asp.net-mvc-3

I feel like the biggest idiot - I thought only ActionResults were sent back to the client. For this reason, I had a load of "helper" methods in my controller.
I just tried accessing them via a URL and I swear I almost went crazy when I saw they can be reached! ... Luckily, no one else has discovered this yet.
One such method I have, that I call over and over again is :
public User GetCurrentUser()
{
User user = db.Users.SingleOrDefault(x => x.UserName == User.Identity.Name);
return user;
}
I have just created a folder called "Logic" inside my Models folder and I am attempting to separate the code - I was just wondering what the best strategy is for calling code, namespaces and more?
In the above example, I am using User.Identity.Name which only inherits from Controller. If I add this, I am back to stage one!
Thanks to Darin Dimitrov, I now know about the [NonAction] Attribute - which, adding to these methods does exactly what I need/fixes the security problem, however, many of these Methods are used in different controllers and I know it would be best if I can separate the logic from the controllers. I am just not sure what the best way to go about it is.
Can anyone point me in the right direction before I start pulling all my hair out!?

You may take a look at the [Authorize] attribute.
UPDATE:
Or you could use the [NonAction] attribute or make the method private. But the best practice in this case would be to simply move this logic out of your controller. A controller should contain only controller actions. Other logic should be placed in its respective layers.

Related

How to handle conditional rendering of views related to same controller's action?

I am developing a simple CRMish application. Let's say I can create tasks and clients. Both can be created independently, but they can also be created in a process. I have a views called create.blade.php for these two actions.
When you are creating a task for example, at some point you have a button choose a customer / create a customer which opens a modal dialog (so you can pick a customer and assign it to a task in one step :)). And here it starts to get muddy. I want my form part from create.blade.php to be rendered in modal dialog and to do so I need to fetch this hitting my create action, which normally returns full form that extends master.blade.php.
How would you handle this kind of design problem? For now it would be a little, innocent switch or if before return view() in my create action but I know that it will look like spaghetti carbonara at some point.
My ideas are as follows:
ifs/switch as long as it's readable and it's only about returning
different views (but you know it will include logic, different
variables etc. at some point..)
move ifs/switch logic to some request class and call return
view($request->getView()) so my controller will be a little bit
cleaner and follow SRP
create different classes for "ajax" requests, and "normal" requests.
same as above but because the logic of fetching some data used in
form etc. are common for both of the scenarios I can create a base
abstract class of TaskController and than extend this for "normal"
request and "ajax" request scenario. This is most advanced idea, but
I think i follow SRP as well as I remove code duplication cause
fetching common data will be placed in abstract class
Do you have any other ideas of how to handle this?
I have ended up with a little conditional in my create.blade.php view.
#extends((( Request::ajax()) ? 'layouts.modal' : 'layouts.master' ))
According to #Kristo I wont overengineer, and stick with this simple & readable solution.
UPDATE
I have created a little extension, as I decided that I will not load my modals via Ajax but simply inject them on compile time. Here is the code :)
https://github.com/3amprogrammer/modal-blade-extension

Why do we even use a model class in Spring MVC?

I have gone through a number of videos and tutorials for understanding the difference between Model And Controller.
So what i understood is like controller is the medium between our view and Model , it captures the action performed on the UI and calls the appropriate model class, receives back the model object from the model class and send it to the view given by the view resolver.
Now my question is why do we make the controller to send the request to a model , why do we even need a different class(model). Can't we do the same thing in controller itself ?
It is easier to test and maintain / change / exchange.
The general idea behind MVC is so that you have different modules of your app each with their own function. This way you get less coupling and higher cohesion - coupling refers to classes connected so tightly that, if you decide to change one single variable in one single class you would have to go through your code and check everywhere for exceptions/bugs etc. Cohesion on the other hand refers to having smaller portions of code in separate classes, which depend on nothing else, thus when you change them you can be sure nothing else breaks.
Of course, this can not be explained in a few lines. The best thing you can do is to start writing code, some basic app and see the how it goes.
Really what you say you can do, but it is a bad practice, the MVC is made to separate the layers of development, thus to make it neater develop for all, it must meet a standard for good understanding and management not only but you Developer ...

what is the best structure for a project in codeigniter and how to use it?

I have some weeks since im using CI, but now I've found some problems about the structure of my project, I would like someone to give me some clues because I am kinda stuck, the problem is this:
I have my project MVC, so, I am dividing it into files (each per functionality) for example, there is a file with all the functions corresponding at login, and other with all related at post (it's an example), but now I am on a moment where I need to use login or posting into another part of the project, reading I found out i cannot call a controller from another, I can use the helper but still I will need to use a model, so I have to take that code and paste it into the controller where I'm calling the model and so on (and it's not good), I found out I can use modules, still I don't want to go over them until someone could give me an experience of this, i wouldnt like to change the project, is any way I could run all those controllers (i know i can use run:: I'm not sure if i can send parameters in it), any ideas please?
Thanks in advance.
Fair warning, this type of question will get shot down by many SO moderators, but I'll give you some tips regardless:
Controller actions are single-use. If you find yourself with duplicate code in multiple controllers (or, needing to call a controller function from another controller), that's a sure sign you should move that code to a model or library.
Models are object-specific, not action-specific. I wouldn't have a model dedicated to logins, unless you have multiple types of logins (most apps/sites just have member logins, but you might have administrators, etc. that are stored in a different table from the rest). Instead, have a User_model class, and make function login($email, $password) a method of that class.
Controller-to-model interaction should be very concise. If you find yourself with 30 lines of code passing data back and forth between the same controller and model, you might be trying to do too much with that one controller action.
Keep your models fat, controllers skinny, and views dumb.

Codeigniter Inter Controller Communication

I am new to MVC, CodeIginter. Instead of getting things easy, it needs lot of code to be written for a simple application. These are might be happening becouse I am new. So I have few confusions about this thing. Any kind of help is appreciated.
1) Methods are written in one controller can not be accessed in another controller classes. I have to write a new function for the same functionality.
2) To create website administration panel (back-end) in none mvc panel, we usually create it in a new folder. Is this thing possible in CodeIgniter? If not what about the admin (back-end)??
Let's try to clear some of your doubts about this.
1) Calling a controller's method from another controller is not possible, and it's whtouth meaning by the way.
A controller is supposed to get an action from the URL (which is routed by CI to the right controller for the task) and, based on that, decide which Model and which model's method needs be called to elaborate the data requested.
The model, then, hands back the result of this elaboration to the controller, which , in turns, decides to which view pass this results.
The view, eventually, is structured to get those datas and display them.
SO, as you can see, calling a controllers' method from another controller is nonsense, it would be like going to a page and finding another one instead; if you want to pass to another controller the request...well, there's the redirect for that.
If you find out you have the same functionalities in several moment, think twice:
What is a funcionality? Do you mean somehtin like "display posts" in controller "archive" and "display posts" in controller "news" ? they're hardly the same functionality; they can maybe share views, or models, but that's it.
For functions that doesn't relate to URLs, but involve some further elaboration (which might be wrong to do in Models) and are nonetheless called in a controller, you have library instead. Think at the "form_validation" library, which is called in a controller's method, but has its own peculiar (and encapsulated) functionalies. Ora a "session" library, or an "authentication" library
2) To create an admin panel the easiest thing is: create an "admin" controller (which is accesible then to www.mysite.com/index.php/admin), and put all the administration actions there, in its methods: create_page(), edit_page(), manage_users(), whatever.
In order to avoid people accessing it freely you need to build an authentication system, which, in its simplest and barabone strucutre, might be a check of wheter a session is set or not (maybe a check done at __construct() time).
But you can find nice Auth libraries out there already made, such as Ion Auth or Tank Auth (the 2 most popular to my knowledge)
Hope things are a bit clearer now. See also Interstellar_Coder's comment at this answer if you're interested in the modular HMVC approach.
1) Methods are written in one controller can not be accessed in another controller classes. I have to write a new function for the same functionality.
What's the functionality about? Perhaps you should write a library/helper instead, controller's logic should be limited to request flow or something else but not too complicated. For that, put the functionality in the model, or if more general, in library/helper.
2) To create website administration panel (back-end) in none mvc panel, we usually create it in a new folder. Is this thing possible in CodeIgniter? If not what about the admin (back-end)??
I don't get it, could you elaborate more?

In MVC, where is the correct place to put authorization code?

In MVC, where is the correct place to put authorization code?
The controller?
The Model?
In the view?
All over the place?
I vote for putting it where it makes sense. Most of my authorization stuff is handled via decorating controller actions (or even some controllers) with the AuthorizeAttribute -- or an attribute derived from it. In a few cases -- like my menus -- I've resorted to putting the authorization check in the view code itself, rather than calculating it in each controller and passing flags down in ViewData. There are a few instances where certain aspects of the model are only available to particular roles and in those cases I've resorted to extending the model with methods that can take the current user and roles and do the check there.
I think authorization is a cross-cutting concern. Should be in one place - an aspect that can be declaratively applied where it's needed.
The Controller!
Your View should only handle user interface and display
Your Model should represent the data in your system.
Your Controller should handle the logic of how the system works.
Authorising a user involves taking the credentials provided from the View, checking them against some sort of authorisation list in the model and then performing a check.
This is done in the controller:
Get user credentials from View
if(compare with user list in model returns match)
authorise users
else
refuse access
If you have to choose between M, V or c, the C is the correct place. But, I recommend an architecture where your app is all contained in libraries and the UI is just a thin veneer. You end up calling down the stack from the Controller, but the code is not in the controller.
In MVC, the Model is just a model, or a "dumb data object", if you will. It is designed to hold state, and should not dictate behavior. The View is for the user to interact with and is also "dumb"; the view handles UI. The controller is where behavior sits, or is the entry point into behavior in the case where the app logic is in libraries. Make sense?
Model.
Controller is just for switching through different ways. View is just for... viewing.
So you should make all authorization codes in the Model layer. Ideally, everything will work just fine. If not, then the controller will take the user to the proper login box.

Resources