User permission in MVC design pattern - model-view-controller

Large systems is using by many users, therefore they can log into the system and then they have extra permissions. Permissions are different, such as permission to view detailed information about other users or permissions to perform different actions. Good practice in software development is using design patterns. One of them is MVC (Model-View-Controller). So, my question is: in which layer of the model should have been checking the permissions ? Is that application logic should validate user permissions or perhaps in view layer some options should be hidden/locked/etc ?

The authentication and authorization is not part of MVC design pattern itself. Nor it is directly a responsibility of any of the basic MVC building blocks.
A solution that you can explore would be to place the access control in a decorator.
You create a Container instance, in which you can inject an object (it might be either some controller, view or maybe a service from model layer) and some authorization manager-thing. Then you call a method on this container as if it was the original object. If call gets cleared with access manager, then you execute the method. Otherwise you raise an exception.
Unfortunately code example is in PHP, because that's my "native" language
$something = new SomeThing;
$data = $something->getSensitiveData(); // will simply return all the information
$accessCheck = new AccessManager( .. some dependencies .. );
$something = new Container( $something, $accessCheck );
try
{
$data = $something->getSesitiveData();
// will return all information if you pass the authorization.
}
catch ( AccessDeniedException $e )
{
// do something
}
This approach has several benefits:
The access management is centralized
You can inject any instance in such container
Will not cause OCP violation
Let's you defer the addition of authorization while developing
The "wrapping" in such decorator would happen usually at within the factory which creates your instance.
As to which part of MVC triad you should be wrapping. Well ... usually it is enough to wrap the controller (especially when working with MVC in context of Web). But, depending on how you structure the rest of you codebase, it might be reasonable to add this kind of authorization checks also for services (group of classes/instances in model layer).
The thing is, this approach has no restrictions on granularity. You can add this type of access control on any object. Even if you have not access to the source code of that object.

Related

where should put input validation in Domain Driven Design?

I was wondering where exactly we should put input validations(imagine an API call send input to apply free times of a user). Is it right to inject validation class in service Layer and call validate method inside service? or it's better to put it in the infrastructure layer or even in Domain model? I just wanted to see a sample code that's implement validation of input for an API in Domain-driven design approach? what if I use CQRS architecture?
I use in my DDD/CQRS project following approach, structure of a project is API layer, Domain layer, Data Access layer, all input data from UI or from User are validated before, command are created and dispatched, to update the state of Domain, and we validate input data two times one is on the UI, (Angular app), and second one in Web API layer, if the data are valid the CQRS command are created and dispatched after that you can have Business logic validation. For validation you can use FastValidator or FluentValidation
UPDATE: Here is the simple example we have API for Create Batch Entity.
[HttpPost]
[Route("create")]
public IHttpActionResult Create([FromBody] BatchEditModel model)
{
var createCommand = model.Map<BatchEditModel, CreateBatchCommand>();
var result = (OperationResult<int>) _commandDispatcher.Dispatch(createCommand);
return Result(result);
}
As you can see as user input data will be BatchEditModel.
so we have BatchEditModelValidator which contains input data validation:
public class BatchEditModelValidator : AbstractValidator<BatchEditModel>
{
public BatchEditModelValidator()
{
RuleFor(x => x.Number).NotEmpty()
.WithMessage(ValidatorMessages.MustBeSpecified);
RuleFor(x => x.ClientId).GreaterThan(0)
.WithMessage(ValidatorMessages.MustBeSpecified);
RuleFor(x => x.EntryAssigneeId).GreaterThan(0)
.WithMessage(ValidatorMessages.MustBeSpecified);
RuleFor(x => x.ReviewAssigneeId).GreaterThan(0)
.WithMessage(ValidatorMessages.MustBeSpecified);
RuleFor(x => x.Description).NotEmpty()
.WithMessage(ValidatorMessages.MustBeSpecified);
}
}
this Validator will be executed before BatchEditModel will be mapped to CreateBatchCommand
and in CreateBatchCommandHandler we have Business logic validation CheckUniqueNumber
public OperationResult Handle(CreateBatchCommand command)
{
var result = new OperationResult<int>();
if (CheckUniqueNumber(result, command.ClientId, command.Number))
{
if (result.IsValid)
{
var batch = _batchFactory.Create(command);
_batchRepository.Add(batch);
_batchRepository.Save();
result.Value = batch.Id;
}
}
return result;
}
My approach is putting validation in the domain model, I validate the functionality of aggregates, entities, value objects, etc.
Then you can validate application services too, and user interface too. But those validations are a plus, a validation enhancement from the user point of view, as validation is faster.
Why this duplication of validations at different layers? Well, because if you just rely on UI or application service validations, it maybe possible that if they don't work well for whatever reason, and you don't validate the domain model, you are executing domain functionality without validating it.
Also, I would point out that not all the validations can be done at UI or at application layer, because you may have to access domain.
Finally, doing CQRS or not is independent on where you decide to put the validations. It's just that if you do CQRS, then validations at application layer are easier to do, as you can put them in decorators that wrap commands and queries.
Hope my explanation helps.
where should put input validation [in Domain Driven Design]?
This is largely unrelated to DDD, but: the closest possible to the input source.
You aren't going to wait until invalid data has crossed 4 layers to discard it.
Input validation precisely means you don't need anything else (e.g. loading other data) to check it, so you might as well do it as soon as you can. Of course, caveats apply, like any validation that can be circumvented must be double checked - client side javascript for instance.
what if I use CQRS architecture?
I wouldn't expect CQRS to change things very much.
Usually, by the time you are invoking a method in a domain entity, your inputs should have already been converted from their domain agnostic form into value objects.
Value objects are expected to be constructed in a valid state, and often include a check of a constraint within the constructor/factory method that produces it. However, in Java and similar languages, the implementation of the constructor usually throws (because constructors don't have any other way of reporting a problem).
Often what clients want instead is a clear understanding of all of the constraints violated by the input data, rather than just the first one. So you may need to pull the constraints out as first class citizens in the model, as predicates that can be checked.
You should validate in your app service before attempting to modify your domain. Validation should be towards the edges of your app (but not in the UI) so invalid or incomplete requests aren't even getting into your domain model.
I consider it two levels of validation because you will validate the request before attempting some behavior on the model then the model should again verify for internal consistency, since it can never be persisted in an invalid state.

What is a better pattern for implementing these features in ASP.NET MVC3?

We have a few features that follow very similar patterns:
User submits email address
User receives email with secret code
User redeems secret code to perform secure action
For example, our sign-up / registration feature follows this pattern. User submits email address, receives email, then uses secret code to create password & user account. Another example is password reset. User submits email address, receives email, then uses secret code to change password and access user account.
Pattern #1
We could have 1 controller that manages each feature individually. So, for example, a SignUpController that handles all related actions (sending email, redeeming code, and creating password). Then we could have a PasswordResetController that also handles sending the email, redeeming the code, and changing the password.
Pattern #2
An alternative would be to have the actions split across controllers. In this pattern, we would have a SendEmailController that would send emails for both features, a CodeRedemptionController that would handle code redemptions for both features, and a PasswordController that would handle password operations for both features.
Which is a better approach and why? Our main goals are to achieve high code simplicity, clarity / discoverability, and DRYness. I can see advantages and disadvantages with both patterns.
Pattern #1 advantages
All code pertaining to the feature is kept in one place. Passing data from one action to another using TempData dictionary is easier to understand, and the flow of the feature is described by a single controller.
Pattern #1 disadvantages
Dependency injection. Each feature controller would need dependencies injected for email sender, account manager (MembershipProvider interface wrapper), as well as various repositories. When using constructor injection, the constructor would have a lot of arguments.
The advantages and disadvantages of Pattern #2 would be the opposite. We could simplify dependencies for the controllers, but the features would be spread across multiple controllers, blurring the clarity of what features the app as a whole is trying to achieve.
I would use a single account controller to manage all of the related user management functions. This controller would be the user's access point to handle these types of features.
Then I would separate the separate logic you mentioned into different model classes that would be called by that controller as needed. Examples:
/models/EmailManager.cs
/models/PasswordManager.cs
/models/SecretCodeGenerator.cs
/models/AccountManager.cs
This would allow you to have a consolidated url syntax. It would keep you from having many controllers with only 1 method. And it would keep you from having a lot of model type logic in the controllers.
www.mydomain.com/account/signup/
www.mydomain.com/account/confirm/
www.mydomain.com/account/resetpassword/
(with custom routes, you could even remove the /account/ part if you wish)
However, I might be tempted to create a custom controller to handle redeeming of secret codes. (redeemController) This way you could control access to much of the accountController to authorized/existing users only, whereas the redeem controller (depending on your design) may be open to anonymous for new customers.
Finally, having most of the logic in the model classes makes them much more test friendly.

Castle.Windsor, ASP.NET MVC, Handling Null Resolution of Injection

Using Castle.Windsor in ASP.NET MVC (3.0) is there any way I can appropriately handle if one of my dependencies resolves null? For instance, say I have a IMembershipService.
class ServiceInstaller
{
// ...
void Install( // .. )
{
container.Register(
Component
.For<IMembershipService>()
.ImplementedBy<MembershipService>()
.LifeStyle.PerWebRequest
);
}
}
Okay, this works great. Now, perhaps not all of my site requires a user to be logged in. Let's assume that maybe my web host's database server crashes for a few hours. In that event, things that looked into the database, or tried to call on my ISession might return null.
What can I do in this case? I can write if(membershipService == null) a hundred times over, but that seems pretty dumb. Is there a built-in solution to say "Hey, if we have an error, do this..?"
I think that the service should never be null. If the database is down, the service should be returned nevertheless, but its methods should throw an exception, return null or some default value, depending on the semantic of the service.
Ciel, i had this problem just recently and found your question while looking for the answer.
Basically you should be using a typed factory to resolve your components at runtime in your wrapping component. The factory should return a default object if there is no match regarding the component you're looking for, default object that would implement whatever behavior is needed.
In the case of your IMembershipService, implement a NotCheckingMembershipService class inheriting the interface and doing nothing and make it the default for the components that won't need it. More specific membership services can be linked to specific controllers.
To do so you must create a generic "catch-all" implementation
public class NotCheckingMembershipService<T>: IMembershipService<T> where T: Controller
{
}
And register it as the default component for an open IMembershipService
_container.Register(
Component.For(typeof(IMembershipService<>))
.ImplementedBy(typeof(NotCheckingMembershipService<>))
.IsDefault());
Then simply register your custom membership services where needed. Resolution won't fail and you will always be able to call the interface.

What exactly is the model in MVC

I'm slightly confused about what exactly the Model is limited to. I understand that it works with data from a database and such. Can it be used for anything else though? Take for example an authentication system that sends out an activation email to a user when they register. Where would be the most suitable place to put the code for the email? Would a model be appropriate... or is it better put in a view, controller, etc?
Think of it like this. You're designing your application, and you know according to the roadmap that version 1 will have nothing but a text based command line interface. version 2 will have a web based interface, and version 3 will use some kind of gui api, such as the windows api, or cocoa, or some kind of cross platform toolkit. It doesn't matter.
The program will probably have to go across to different platforms too, so they will have different email subsystems they will need to work with.
The model is the portion of the program that does not change across these different versions. It forms the logical core that does the actual work of whatever special thing that the program does.
You can think of the controller as a message translator. it has interfaces on two sides, one faces towards the model, and one faces towards the view. When you make your different versions, the main activity will be rewriting the view, and altering one side of the controller to interface with the view.
You can put other platform/version specific things into the controller as well.
In essense, the job of the controller is to help you decouple the domain logic that's in the model, from whatever platform specific junk you dump into the view, or in other modules.
So to figure out whether something goes in the model or not, ask yourself the question "If I had to rewrite this application to work on platform X, would I have to rewrite that part?" If the answer is yes, keep it out of the model. If the answer is no, it may go into the model, if it's part of the essential logic of the program.
This answer might not be orthodox, but it's the only way I've ever found to think of the MVC paradigm that doesn't make my brain melt out of my ear from the meaningless theoretical mumbo jumbo that discussions about MVC are so full of.
Great question. I've asked this same question many times in my early MVC days. It's a difficult question to answer succintly, but I'll do my best.
The model does generally represent the "data" of your application. This does not limit you to a database however. Your data could be an XML file, a web resource, or many other things. The model is what encapsulates and provides access to this data. In an OOP language, this is typically represented as an object, or a collection of objects.
I'll use the following simple example throughout this answer, I will refer to this type of object as an Entity:
<?php
class Person
{
protected $_id;
protected $_firstName;
protected $_lastName;
protected $_phoneNumber;
}
In the simplest of applications, say a phone book application, this Entity would represent a Person in the phone book. Your View/Controller (VC) code would use this Entity, and collections of these Entities to represent entries in your phone book. You may be wondering, "OK. So, how do I go about creating/populating these Entities?". A common MVC newbie mistake is to simply start writing data access logic directly in their controller methods to create, read, update, and delete (CRUD) these. This is rarely a good idea. The CRUD responsibilities for these Entities should reside in your Model. I must stress though: the Model is not just a representation of your data. All of the CRUD duties are part of your Model layer.
Data Access Logic
Two of the simpler patterns used to handle the CRUD are Table Data Gateway and Row Data Gateway. One common practice, which is generally "not a good idea", is to simply have your Entity objects extend your TDG or RDG directly. In simple cases, this works fine, but it bloats your Entities with unnecessary code that has nothing to do with the business logic of your application.
Another pattern, Active Record, puts all of this data access logic in the Entity by design. This is very convenient, and can help immensely with rapid development. This pattern is used extensively in Ruby on Rails.
My personal pattern of choice, and the most complex, is the Data Mapper. This provides a strict separation of data access logic and Entities. This makes for lean business-logic exclusive Entities. It's common for a Data Mapper implementation to use a TDG,RDG, or even Active Record pattern to provide the data access logic for the mapper object. It's a very good idea to implement an Identity Map to be used by your Data Mapper, to reduce the number of queries you are doing to your storage medium.
Domain Model
The Domain Model is an object model of your domain that incorporates behavior and data. In our simple phone book application this would be a very boring single Person class. We might need to add more objects to our domain though, such as Employer or Address Entities. These would become part of the Domain Model.
The Domain Model is perfect for pairing with the Data Mapper pattern. Your Controllers would simply use the Mapper(s) to CRUD the Entities needed by the View. This keeps your Controllers, Views, and Entities completely agnostic to the storage medium. This also allows for differing Mappers for the same Entity. For example, you could have a Person_Db_Mapper object and a Person_Xml_Mapper object; the Person_Db_Mapper would use your local DB as a data source to build Entities, and Person_Xml_Mapper could use an XML file that someone uploaded, or that you fetched with a remote SOAP/XML-RPC call.
Service Layer
The Service Layer pattern defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation. I think of it as an API to my Domain Model.
When using the Service Layer pattern, you're encapsulating the data access pattern (Active Record, TDG, RDG, Data Mapper) and the Domain Model into a convenient single access point. This Service Layer is used directly by your Controllers, and if well-implemented provides a convenient place to hook in other API interfaces such as XML-RPC/SOAP.
The Service Layer is also the appropriate place to put application logic. If you're wondering what the difference between application and business logic is, I will explain.
Business logic is your domain logic, the logic and behaviors required by your Domain Model to appropriately represent the domain. Here are some business logic examples:
Every Person must have an Address
No Person can have a phone number longer than 10 digits
When deleting a Person their Address should be deleted
Application logic is the logic that doesn't fit inside your Domain. It's typically things your application requires that don't make sense to put in the business logic. Some examples:
When a Person is deleted email the system administrator
Only show a maximum of 5 Persons per page
It doesn't make sense to add the logic to send email to our Domain Model. We'd end up coupling our Domain Model to whatever mailing class we're using. Nor would we want to limit our Data Mapper to fetch only 5 records at a time. Having this logic in the Service Layer allows our potentially different APIs to have their own logic. e.g. Web may only fetch 5, but XML-RPC may fetch 100.
In closing, a Service ayer is not always needed, and can be overkill for simple cases. Application logic would typically be put directly in your Controller or, less desirably, In your Domain Model (ew).
Resources
Every serious developer should have these books in his library:
Design Patterns: Elements of Reusable Object-Oriented Software
Patterns of Enterprise Application Architecture
Domain-Driven Design: Tackling Complexity in the Heart of Software
The model is how you represent the data of the application. It is the state of the application, the data which would influence the output (edit: visual presentation) of the application, and variables that can be tweaked by the controller.
To answer your question specifically
The content of the email, the person to send the email to are the model.
The code that sends the email (and verify the email/registration in the first place) and determine the content of the email is in the controller. The controller could also generate the content of the email - perhaps you have an email template in the model, and the controller could replace placeholder with the correct values from its processing.
The view is basically "An authentication email has been sent to your account" or "Your email address is not valid". So the controller looks at the model and determine the output for the view.
Think of it like this
The model is the domain-specific representation of the data on which the application operates.
The Controller processes and responds to events (typically user actions) and may invoke changes on the model.
So, I would say you want to put the code for the e-mail in the controller.
MVC is typically meant for UI design. I think, in your case a simple Observer pattern would be ideal. Your model could notify a listener registerd with it that a user has been registered. This listener would then send out the email.
The model is the representation of your data-storage backend. This can be a database, a file-system, webservices, ...
Typically the model performs translation of the relational structures of your database to the object-oriented structure of your application.
In the example above: You would have a controller with a register action. The model holds the information the user enters during the registration process and takes care that the data is correctly saved in the data backend.
The activation email should be send as a result of a successful save operation by the controller.
Pseudo Code:
public class RegisterModel {
private String username;
private String email;
// ...
}
public class RegisterAction extends ApplicationController {
public void register(UserData data) {
// fill the model
RegisterModel model = new RegisterModel();
model.setUsername(data.getUsername());
// fill properties ...
// save the model - a DAO approach would be better
boolean result = model.save();
if(result)
sendActivationEmail(data);
}
}
More info to the MVC concept can be found here:
It should be noted that MVC is not a design pattern that fits well for every kind of application. In your case, sending the email is an operation that simply has no perfect place in the MVC pattern. If you are using a framework that forces you to use MVC, put it into the controller, as other people have said.

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