I have class named User, it has fields like username, password, firstName... . is it good to place authenticate(username, password) method in it?
Ideally no, that should be the job of the controller. User class should be just a data class, which is used by the controller (the business logic class) to evaluate things like Authenticate etc.
Explanation:
You need to modularize your code(break it into components) and each component should be an independent entity but requires other components to give the whole picture of the system.
It appears by your question that you want to perform some business layer operation in your DO(data object) class. It can be done but is never recommended as it kills the idea of separation of concerns.
As for controllers, you could do something like
Have object/entity level managers, i.e, for every entity you have a manager to handle its business logic stuff. Say for a User class you have a UserManager.
Have conceptual level controllers. This means that you have controllers that handle a specific module of your system(an entire concept). For example, if you have a website that needs to authenticate users, you can have an AuthenticationController.
Now, Authentication must not necessarily map to just one table/object, though it appears that its sole target is(logically) your User table/class etc, it could be doing other stuff and accessing other entities(depending on the requirement) etc. So by having entity level managers that are used by conceptual level controllers, you could ease your development.
I would say no. Better is to have a Connection and create a user using login method with username and password:
class Connection{
public:
Connection(string connectionString);
User login(string userName, string Password);
};
That would break the MVC (Model View Controller) structure. It is best to keep these three separated for code elegance, readability, and maintainability. A quick example would be, in Java:
Model:
public class User {
private String username;
private String password;
(...)
}
Controller:
import yourmodelpackage;
public class MyController {
public static boolean authenticate(String username, String password) {
//your logic
}
}
View:
//call your authenticate() method through the controller
MyController control = new MyController();
boolean b = control.authenticate(username, password);
There are a few design patterns that maximize the use of inheritance for this structure. I'd recommend looking into the Decorator Design Pattern.
You could have a method hasPassword(string password) on the User class, if you absolutely wanted to encapsulate the verification in that class.
Related
Lets say i have a Class User with multiple properties. I'm building a REST based App so in my homepage when I request for "user details" I need only a few properties from my User and rest from other classes. How do i write the class for the object which i would return for "user details" ?
My current design retrieves the needed properties from the class to build the JSON. I hope there is a better way to handle this.
I use Play Framework 2.0 with Java
If you don't want to expose whole business class User, I'll build a second class, a DTO. This class provides only the desired data to be transfered by REST API.
User user = new User("admin");
// Set other properties
UserDetailsDTO userDetailsDTO = new UserDetails(user); //<- Transfer userDetailsDTO
Or if "user details" are important for your application, maybe you should consider to create a UserDetails class and use it inside your User class by composition.
public class User {
Long id;
String name;
String address;
UserDetails userDetails; // Composition <- Tranfer userDetails
}
Note: example where don in Java
Looks like you need a Facade: http://en.wikipedia.org/wiki/Facade_pattern.
It is a simple pattern that helps you expose methods/properties from a multiple classes.
You can store references to objects in your Facade class and expose only those things you need.
There is an option of creating a View Model object, providing proper abstraction for the information required for that JSON.
More details about it here: http://en.wikipedia.org/wiki/Model_View_ViewModel
But this is typically used in the cases where view directly used in Views of the application. So careful analysis is required in use case mentioned above, since there is already JSON being created, creation of this View Model layer is really justified.
Still experimenting with DDD and have some doubts, maybe someone would help me.
Lets say that I have 2 models:
public class Event
{
User Creator;
List<User> Members;
}
public class User {}
My problem is that I cannot see place for logic that I want to implement. I need 3 actions:
User join event
User leave event
Creator remove user from event (only Creator can remove users)
For now I just created domain service EventUserService that calls Event.RemoveUser/AddUser and ie. checks if CurrentUser (provided by UserService) is creator of event (have rights to remove other users).
Maybe that approach is ok, but I still feel that I should putt that logic into aggregation roots, ie. :
User.JoinEvent(Event) - i can add passed Event to User.Events collection (bidirectionall) base on some logic.
User.LeaveEvent(Event) - analogous to JoinEvent.
User.RemoveUserFromEvent(User,Event) - I can have CreatedEvents collection in User and for Event from that collection I can call Event.RemoveUser(User) - this way I will make sure that only creator can kick someone.
Or
Evet.RemoveUser(UserToRemove) - but how I will make sure that its called by creator ?
If first two method looks ok (at least for me), 3rd one would create Event.RemoveUser (to manage Event members collection) method that could be used to bypass logic residing in User.RemoveUserFromEvent.
So, in the end I have 2 questions:
What is your approach in situation like this where two aggregation roots works together and one operation is determine by logic residing in both of them? Maybe some kind of methoods like User.CanJoinEvent(Event) ?
What about creating "danger" point like User.RemoveUserFromEvent
Maybe someone can putt a little bit light on that for me, every help would be nice.
public class Event
{
User Creator;
List<User> Members;
}
Don't do that. You are breaking Law Of Demeter and the Event class has no control over the changes in Members or the users in that list. You should instead define methods in the Event class which is used to handle the members.
Now, if you do that change, i.e. have something like this:
public class Event
{
User Creator { get private set; }
bool IsMember(string name);
void AddMember(User user);
}
You'll suddenly have solid places to generate the events.
but how I will make sure that its called by creator ?
In .NET you can use Thread.CurrentPrinicpal to get information about the logged in user. It do however require that you implement your own IPrincipal/IIdentity.
Remember: You should ALWAYS make sure that the models are in a valid state in DDD. That usually means that all setters should be private: http://blog.gauffin.org/2012/06/protect-your-data/
I've a situation where I need to call a third party service to fetch some information. Those service could be different for different clients. I've a authenticate function in my Interface as follows.
interface IServiceProvider {
bool Authenticate(string username, string password);
}
class ABCServiceProvider : IserviceProvider
{
bool Authenticate(string username, string password) { // implementation}
}
class EFGServiceProvider : IserviceProvider
{
bool Authenticate(string username, string password) { // implementation}
}
and so on... now I've came across a service provider (let's say XYZServiceProvider) that needs some additional information (agentid) for authentication. something like this...
class XYZServiceProvider
{
bool Authenticate(string username, string password, int agentid) { // implementation}
}
Now if I provide another function for Authenticate in my interface with 3 parameters, and throw not implemented exception in all the classes except for XYZServiceProvider, wouldn't it violate Interface segregation principle? I've similar situation in some of my other part of the code aswell. Can anyone please tell me whats the best way to implement this type of scenrio? I would be really very thankful.
The best way to solve this would probably be to require agentId in the interface, and to simply ignore it in the cases of ABC and DEF where they don't need it. That way, the consuming class still wouldn't know the difference.
Actually it's the Liskov Substitution Principle that is most important if the ABC, DEF and XYZ providers are to be used interchangeably; "Given a class A that is depended upon by class X, X should be able to use a class B derived from A without knowing the difference".
The Interface Segregation Principle basically says that an interface should not contain members that any of its consumers do not need, because if the definition of those members were to change, classes that don't even use that method would have to be recompiled because the interface they depended on has changed. While this is relevant (you do have to recompile all consumers of IServiceProvider if you add an overload), you will have to do that anyway if you change Authenticate()'s signature, and of more pressing concern from a maintenance standpoint is that if you added an overload of Authenticate(), your consumers now have to know which overload they need to use. That requires your consuming classes to know the difference between implementations of a common interface, violating LSP. It's never a problem providing more information than a particular provider needs, but there would be a problem using XYZ from a usage that only provides two inputs. To avoid those problems, you would always use the three-parameter overload, so why have the two-parameter one at all?
Now, if current usages of IServiceProvider are in areas that don't have and don't care about agentId, and therefore it would be difficult to begin providing it, then I would recommend an Adapter that the concrete XYZ provider plugs into, that implements your current IServiceProvider, and makes the new provider work like the old ones by providing the agentId through some other means:
public class XYZAdapter: IServiceProvider
{
private readonly XYZServiceProvider xyzProvider;
public XYZAdapter(XYZServiceProvider provider)
{
xyzProvider = provider;
}
public void Authenticate(string username, string password)
{
xyzProvider.Authenticate(username, password, GetAgentId());
}
public int GetAgentId()
{
//Retrieve the proper agent Id. It can be provided from the class creator,
//retrieved from a known constant data source, or pulled from some factory
//method provided from this class's creator. Any way you slice it, consumers
//of this class cannot know that this information is needed.
}
}
If this is feasible, it meets both LSP and ISP; the interface doesn't have to change to support LSP, therefore preventing the scenario (recompiling and redistributing dependencies) that ISP generally tries to avoid. However it increases class count, and forces new functionality in the Adapter to correctly get the needed agentId without its dependent having to provide anything it wouldn't know about through the IServiceProvider interface.
I'm trying to embrace widespread dependency injection/IoC. As I read more and more about the benefits I can certainly appreciate them, however I am concerned that in some cases that embracing the dependency injection pattern might lead me to create flexibility at the expense of being able to limit risk by encapsulating controls on what the system is capable of doing and what mistakes I or another programmer on the project are capable of making. I suspect I'm missing something in the pattern that addresses my concerns and am hoping someone can point it out.
Here's a simplified example of what concerns me. Suppose I have a method NotifyAdmins on a Notification class and that I use this method to distribute very sensitive information to users that have been defined as administrators in the application. The information might be distributed by fax, email, IM, etc. based on user-defined settings. This method needs to retrieve a list of administrators. Historically, I would encapsulate building the set of administrators in the method with a call to an AdminSet class, or a call to a UserSet class that asks for a set of user objects that are administrators, or even via direct call(s) to the database. Then, I can call the method Notification.NotifyAdmins without fear of accidentally sending sensitive information to non-administrators.
I believe dependency injection calls for me to take an admin list as a parameter (in one form or another). This does facilitate testing, however, what's to prevent me from making a foolish mistake in calling code and passing in a set of NonAdmins? If I don't inject the set, I can only accidentally email the wrong people with mistakes in one or two fixed places. If I do inject the set aren't I exposed to making this mistake everywhere I call the method and inject the set of administrators? Am I doing something wrong? Are there facilities in the IoC frameworks that allow you to specify these kinds of constraints but still use dependency injection?
Thanks.
You need to reverse your thinking.
If you have a service/class that is supposed to mail out private information to admins only, instead of passing a list of admins to this service, instead you pass another service from which the class can retrieve the list of admins.
Yes, you still have the possibility of making a mistake, but this code:
AdminProvider provider = new AdminProvider();
Notification notify = new Notification(provider);
notify.Execute();
is harder to get wrong than this:
String[] admins = new String[] { "joenormal#hotmail.com" };
Notification notify = new Notification(admins);
notify.Execute();
In the first case, the methods and classes involved would clearly be named in such a way that it would be easy to spot a mistake.
Internally in your Execute method, the code might look like this:
List<String> admins = _AdminProvider.GetAdmins();
...
If, for some reason, the code looks like this:
List<String> admins = _AdminProvider.GetAllUserEmails();
then you have a problem, but that should be easy to spot.
No, dependency injection does not require you to pass the admin list as a parameter. I think you are slightly misunderstanding it. However, in your example, it would involve you injecting the AdminSet instance that your Notification class uses to build its admin list. This would then enable you to mock out this object to test the Notification class in isolation.
Dependencies are generally injected at the time a class is instantiated, using one of these methods: constructor injection (passing dependent class instances in the class's constructor), property injecion (setting the dependent class instances as properties) or something else (e.g. making all injectable objects implement a particular interface that allows the IOC container to call a single method that injects its dependencies. They are not generally injected into each method call as you suggest.
Other good answers have already been given, but I'd like to add this:
You can be both open for extensibility (following the Open/Closed Principle) and still protect sensitive assets. One good way is by using the Specification pattern.
In this case, you could pass in a completely arbitrary list of users, but then filter those users by an AdminSpecification so that only Administrators recieve the notification.
Perhaps your Notification class would have an API similar to this:
public class Notification
{
private readonly string message;
public Notification(string message)
{
this.message = message;
this.AdminSpecification = new AdminSpecification();
}
public ISpecification AdminSpecification { get; set; }
public void SendTo(IEnumerable users)
{
foreach(var u in users.Where(this.AdminSpecification.IsSatisfiedBy))
{
this.Notify(u);
}
}
// more members
}
You can still override the filtering behavior for testing-purposes by assigning a differet Specification, but the default value is secure, so you would be less likely to make mistakes with this API.
For even better protection, you could wrap this whole implementation behind a Facade interface.
I am looking for some best practices on how to handle the following scenario - flowing permissions from WCF service layer through to UI:
I have WCF services with methods that have been decorated with the PrincipalPermission attribute. I would like a means to allow a client to check if they have the required permissions before invoking the method.
A basic example of this could be checking whether a user can perform a specific function (say submitting an order), which can then be used to enable/disable a button within the UI.
Possible options are to add "chatty" operations like bool CanSubmitOrder() to the service, or instead have a single method OrderServicePermissions GetPermissions() which returns a message with a property CanSubmitOrder? I can then set the enabled state of a "Submit Order" button to the result.
So does anybody know of a better approach, or even a best practice?
Thanks in advance!
The whole point of having PrincipalPermission attributes on your service calls is that you don't have to check ahead of time whether or not the caller has the rights to call - if he doesn't, the WCF runtime will throw an exception.
Why not just rely on this built-in mechanism? Why not just put your service calls in a try..catch block and handle the exceptions if they do actually occur? It should be the "exceptional" case anyway, right?
I don't see any other "magic" way besides what you described. But the generally accepted practice would be to call and handle any exceptions if they occur.
Marc
Well, if you are able to evolve your applications to use Windows Identity Foundation (WIF) to secure your services you could achieve this using the DisplayToken property of the RequestSecurityTokenResponse.
http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.protocols.wstrust.requestsecuritytokenresponse.requesteddisplaytoken.aspx
Assuming your security token service supported it, the display token could contain a claim set that would allow you to flow your permissions into the UI, say to disable controls that are bound to services the user cannot call. The display token is an extension to WS-Trust that was implemented for CardSpace so it it not likely to be very widely supported outside of the Windows world.
Be aware though, that some people think the display token is bad news and violates the 1st law of identity:
http://www.francisshanahan.com
While other people think it is a reasonable and pragmatic solution to a common problem:
http://blogs.msdn.com/b/vbertocci/archive/2007/10/31/on-displaytoken.aspx
There are two general type to implement checking logic:
Share library. Example is "RIA Services + Silverlight".
Pluses: simple to implement.
Minuses: no interoperability (only .NET); required client update for every library changing.
Implement common method validation in service part.
Pluses: interoperability, no need for client update if checking logic changed
Minuses: may be to complex because it is only on you
If we use SOA it is better to use second choice, if only you are not using applications only in your company where .NET is everywhere.
Example
Let us consider common example. We have a windows/wpf form. And there are two fields: "surname" of type string, "age" of type int; and a button "Save". We need to implement some check on client side
1) for some users button "Save" is disabled;
2) surname cannot be empty and max length is 256;
3) age cannot be less than 0;
Invoking method to save is
void Save(string surname, int age);
Create second method in the service, which return object type of PermissonAnswerDTO with validation information;
PermissonAnswerDTO SaveValidate(string surname, int age);
and main validation method
// If arguments are wrong
[FaultContract(typeof(NotSupportedException))]
// If the user have permisson to invoke this method
[FaultContract(typeof(CustomNotEnoughPermission))]
PermissonAnswerDTO Validate(string methodName, object[] methodParams);
Validation.
Invoke Validate("SaveValidate", null) on window loading. If exception of type CustomNotEnoughPermission is throwed then we block "Save" button.
If user can save then invoke user's data Validate("SaveValidate", object[2]{"Surname", "-60"};. -60 is not valid so we get answer object of type PermissonAnswerDTO with information:
ParameterName: "age",
ExceptionMessage: "age cannot be less then null".
And we can gracefully show this information to user.
My thought on this is that some day Microsoft will implement this and call as new technology as it always does. Mostly Microsoft's technologies really are not so revolutionary as it is advertised. Examples are Windows Identity Foundation and Reactive Extensions.
Full example
[DataContract]
public class ParameterExceptionExplanaitonDTO
{
[DataMember]
public string ParameterName;
[DataMember]
public string ExceptionMessage;
}
[DataContract]
public class PermissonAnswerDTO
{
[DataMember]
public bool IsValid;
[DataMember]
public ParameterExceptionExplanaitonDTO[] ParameterExceptions;
}
public class Service1 : WcfContracts.IService1
{
// If arguments are wrong
[FaultContract(typeof(NotSupportedException))]
// If the user have permisson to invoke this method
[FaultContract(typeof(CustomNotEnoughPermission))]
public PermissonAnswerDTO Validate(string methodName, object[] methodParams)
{
//1) Using Reflection find the method with name = <methodName + Validate>
//2) Using Reflection cast each object in "object[] methodParams" to the required type
//3) Invoke method
}
private PermissonAnswerDTO GetUserNameValidate(int id)
{
//logic to check param
}
public string GetUserName(int id)
{
// if the user calls method we need validate parameter
GetUserNameValidate(id);
//some logic to retreive name
}
}