Question

Problem:

I am using a Domain Driven Design architecture and I have a domain model called User as follows:

public class User{
    public User(string username){
        this.Username = username;
    }

    public string Username{get;set;}            
}

and I would like to include a GetPassword() function to the domain.

My research:

I know that

  • storing a password in the domain is a bad practice
  • entity should not have any persistence logic to retrieve the password from db

I was thinking in retrieving the password from the UserService with a function like:

public class UserService{
   public string GetPassword(string username){
       //logic to retrieve db from persistence layer.
   }
}

However, it does not seem as clean and as natural as this

user.GetPassword();

I thought on an extension class but I had to import the class every time I needed the password. Also, i read about decorator but I still do not understand the drawbacks or the gains.

Is there another way to achieve this? If the decorator pattern is the solution could you help me fit that into this specific problem?

PD: Excuse my grammar mistakes, I am not a native English speaker.

Was it helpful?

Solution

This might sound naive, but the way to don't violate SoC is not doing it. Don't integrate the password with User because it belongs to another domain. Security.

In security, the counterpart of User could be (and often is) Account. Account and User are correlated. Account hold reference to the password or a set of Credentials. It depends on the security protocols supported. Credentials could be entities of the security domain too, not a mere set of strings.

The relationship between Account and User usually is 1-to-1, unless we allow shared accounts. We access the credentials (password) through this relationship. Basically, given a user, we look for the account and then the credentials. We can do this from the SecurityService rather than UserService, all theSecurityService need is the user's identifier.

Regarding validations, if we have to validate credentials by comparison, we do it at DB level, not in memory. It's not necessary. If it's too late for you, try making credentials not accessible from other domains.

Licensed under: CC-BY-SA with attribution
scroll top