How to validate email inside entity? - entity

I got this user entity:
class User {
id: string;
name: string;
email: string;
password: string;
....
}
My business rules says that:
One user per Email
What's the purpose of this entity, It cannot have any dependencies. How can i check if email is unique or not?
The thing i don't understand is, who calls entity and pushes data inside it for validation and who can access it?(usecase or repository).

Actually, when you need to satisfy this rule? Only when you are creating a new user. It does not make sense to check it when you've got a user from a database. Or when you are doing something with the user, like changing phonen umber, blocking and so on.
It means this behavior does not belong to User class. I would suggest to create some kind of UserFactory that creates a new user and inject there a policy (or policies).
public UserFactory(EmailCheckingPolicy: emailpolicy, AnotherPolicy: somethingElse);
public User create(UserData: userData) {
if (emailPolicy.isPass(userData.email)) ...
return User(userData.email, userData.name, ...)
}
}
You can inject UserFactory to a UseCase.

Related

DAOs and SOLID design principles

I've been reading up about SOLID design principles, currently looking at the 'Single Responsibilty Principle', but I was curious on the use case for this principle. At the company I work at, we have DAOs which have methods of read, insert & update to manage a record in the database.
Would something like this break the 'Single Responsibilty Principle'? If so, would you then need classes for each inserting, reading & updating?
Example DAO:
class UserDAO {
public function read(where: object) {
// read code
}
public function insert(user: User) {
// insert code
}
public function update(user: User) {
// update code
}
}
Single Responsibility Principle states that
A class must have only one reason to change.
Let's say we have UserDAO with methods read, save, delete, update. So, this class will only be changed when there will be changes related to User. So, it has a single reason for a change i.e User.
So, I think it doesn't violate SRP (Single Responsibility Principle) if implemented correctly.
void save(User user){
//user related logic
}
void save(User user){
// user related logic and address logic encapsulated inside address class
//eg: address.getAddress(user.getId);
}
In the above case, it doesn't violate SRP because the save method will only be changed when there is a change in User logic. The address logic is handled by Address class per se.
For eg: if save method looks like:
void save(User user){
Address address = new Address();
//Address logic
Payment payment = new Payment();
//Payment logic
}
In the above code, any changes in Address or Payment logic will make this DAO save method change as well. It violates SRP.
So, it really depends on the implementation.

When mapping Typesafe configuration to a bean class (ConfigBeanFactory) is there a way to flag mis-spelled attributes?

Our application is using a reference.conf to provide defaults for one of our POJO's that carries configuration information.
Say the Pojo is:
class Person {
String first;
String last;
// corresponding setters / getters not shown
}
The reference.conf has the defaults:
Person {
first: "joe"
last: "shmoe"
}
So if your application.conf had:
Person {
first: "mike"
}
Thus when you did this:
public static Person getInstance(Config config) {
return ConfigBeanFactory.create(config.getConfig("Person"), Person.class);
}
You'd get back a Person with first/last == mike/shmoe
Now..say I have some users who are not getting enough sleep, and one of them
misconfigures their application like this (mis-spelling 'first'):
Person {
frist: "mike"
}
The way I'm doing things now the Pojo loaded from this config has default first/last == joe/shmoe.
There is no warning about the mis-spelling ("frist").
I could write code to reflect against my Bean class and see what attributes the user provided which don't
correspond to the available setters, and then raise an error if any 'wrong' attributes are found.
But it seems like someone (maybe even the Typesafe config base library) must already have this feature.
Any pointer to a good existing way to do this very much appreciated.

Why is there a resource/operation required instead of type/value using claim based auth

Our old software architecture used role based validation. We now want to use claims based authorization. As a matter of fact, I think we always used something modelling claims, even if we used role base technology.
The lowest level are Privileges. A privilege may be "invoke the user service adding a user" or short "UserService.Add". Privileges can be assigned to groups. Users can be members of groups. In the end, through group membership, a user can have a list of privileges.
The old system used a combination of UserNamePasswordValidator, IAuthorizationPolicy and CodeAccessSecurityAttribute to have attributes that were written above the service method and on call of the service method, the validity would be checked. If the user didn't have the required privilege, access would be denied. Worked great.
[CompanyRoleRequired(SecurityAction.Demand, Role = "Common.Connect")]
[CompanyRoleRequired(SecurityAction.Demand, Role = "SomeServiceName.Save")]
public void Save(IEnumerable<Data> data)
{
// code
}
Now I'd like to use claims based authorization. Keeping the model above, I would create either a claim for each former privilege, or maybe a claim for each service with valid values of it's operations. For example, instead of "UserService.Add" I could add a claim "UserService" and people with the former privilege would get the claim with the value "Add". I would like to offer the service developers the same ease of access checking, so I'd like the required claims to be annotated above the service method. Microsoft already provides a ClaimsPrincipalPermissionAttribute for this.
Instead of implementing IAuthorizationPolicy, I implemented ClaimsAuthorizationManager.
Question 1) The authorization manager gets called twice. Once with the soap url and once with my attribute. I've googled a lot and it seems to be by design. I don't have a problem differentiating between the calls and checking only my calls, but maybe I didn't see something. Is there an option or an easy way to not get called on soap calls with the urls and only getting called for the attributes?
Question 2) The access check offers the ability to check if the pricipal has a claim. Obviously, a claim has a type/name and a value. I would have expected the attribute to offer such an interface. However, the attribute wants to know about the resource and operation. The access check function I need to overwrite also needs to check resources and operations. Why is that? Do I need to map resource/operation to claims in my AuthorizationManager? And if I don't see any need for it, would it be ok to just put the expected type and value of the claim in the attribute as resource and operation and map them 1:1 in the authorization manager? Or do I miss out on some important security feature if I do this?
Q1) That's unfortunately the case - and since both the "automatic" calls and the attribute/.CheckAccess use the same claim types you cannot easily distinguish between the two. I wrote about that here: http://leastprivilege.com/2011/04/30/what-i-dont-like-about-wifs-claims-based-authorization/
Q2) You are missing the concept here. The idea is to NOT check for specific claims - but to rather annotate the code with "what you are doing". The person that writes the business code typically does not know exactly who is allowed to call it (or which claims are exactly needed). You only tell the authZ poliy that you are about to add a customer (as an example). The authorization manager's job is to figure out if the principal is authorized to do that (by whatever means). Separation of concerns. See here: http://leastprivilege.com/2011/04/30/what-i-like-about-wifs-claims-based-authorization/
Not sure if this is going to be helpful to you but ClaimsAuthorizationManager has method that can be overridden (LoadCustomConfiguration) that you can use to load your policy from XML file. That policy might be designed in a way to allow mapping between resources and actions and roles. I've built in-code access control list instead that looks like this:
public interface IAccessControlList
{
List<CustomAccessRule> Rules { get; }
}
public class CustomAccessRule
{
public string Operation { get; set; }
public List<string> Roles { get; set; }
public CustomAccessRule(string operation, params string[] roles)
{
Operation = operation;
Roles = roles.ToList();
}
}
My claims authorization manager looks like this:
public class CustomClaimsAuthorizationManager : ClaimsAuthorizationManager
{
private IAccessControlList _accessControlList;
public CustomClaimsAuthorizationManager(IAccessControlList accessControlList)
{
_accessControlList = accessControlList;
}
public override bool CheckAccess(AuthorizationContext context)
{
string operation = context.Action.First().Value.Split('/').Last();
CustomAccessRule rule = _accessControlList.Rules.FirstOrDefault(x => x.Operation == operation);
if (rule == null) return true;
if (context.Principal.Identities.First().IsInRoles(rule.Roles)) return true;
throw new MessageSecurityException(string.Format("Username {0} does not have access to operation {1}.", context.Principal.Identities.First().Name, operation));
}
}
And here is an example of one access control list implementation for one service:
public class SampleServiceACL : IAccessControlList
{
public List<CustomAccessRule> Rules { get; private set; }
public SampleServiceACL()
{
Rules = new List<CustomAccessRule>();
Rules.Add(new CustomAccessRule("OpenAccount", "Manager", "Owner"));
Rules.Add(new CustomAccessRule("CloseAccount", "Manager", "Owner"));
Rules.Add(new CustomAccessRule("SendEmail", "User", "Manager", "Owner"));
}
}
And I'm applying this at service host base level by using:
protected override void OnOpening()
{
base.OnOpening();
IdentityConfiguration identityConfiguration = new IdentityConfiguration();
identityConfiguration.SecurityTokenHandlers.Clear();
identityConfiguration.ClaimsAuthorizationManager = new CustomClaimsAuthorizationManager(new SampleServiceACL());
this.Credentials.IdentityConfiguration = identityConfiguration;
...
}
As a result, I'm not using attributes at all, all authorization logic is centralized in claims authorization manager over ACL.
Now if you don't like this approach, and you're still in pursuit of attribute that will check for specific claims, you can then derive from CodeAccessSecurityAttribute and actually implement that logic. What is given by MS out of the box is good, but it does not mean you should stick to it by any means. Also logic for checking the claims can be implemented as an extension to identity, i.e.:
public static class IdentityExtensions
{
public static bool IsInRoles(this ClaimsIdentity id, List<string> roles)
{
foreach (string role in roles)
if (id.HasClaim(ClaimTypes.Role, role)) return true;
return false;
}
}
So you might build extensions, custom attribute, and then use extensions in the attribute to perform your validation logic.
Again, this is just something that I've already done. Might not be what you're looking for but it's one type of custom solution.

CWebUser and CUserIdentity

I'm building an authentication module for my application and I don't quite understand the relation between CWebUser and CUserIdentity.
To set the user id to Yii::app()->user->id I have to do that in my UserIdentity class and create a method:
public function getId() {
return $this->_id;
}
But to set isAdmin to Yii::app()->user->isAdmin I have to create a method in my WebUser class:
function getIsAdmin() {
$user = $this->loadUser(Yii::app()->user->id);
return intval($user->user_level_id) == AccountModule::USER_LEVEL_ADMIN;
}
Why can't I just create the methods the UserIdentity class? What is the division of labour here?
The UserIdentity (UI) class is like an ID card, where as the WebUser class is the actual person plus everything you know about them.
The UI class gives you authentication via database, webservices, textfile, whatever. It lets you know what the key attributes are and allows you to manipulate them. The user however can give you more information about what they're allowed to do, there names, granular permissions and such.
OK, end metaphor
The UI class holds the key information, so when asking for the users ID it will refer to the User Identity class to get the Identifier for the user.
Anything that isn't related to identifying or authenticating a user is in the WebUser class
Clear it up at all?
Your example
You gave the getId function as an example, but that can be created on WebUser to override the default, which is to pull from the state.
So not sure what you mean here.
I like how the accepted answer used real life examples to make it easier to understand. However, I also like how Chris explained it here with example.
User information is stored in an instance of the CWebUser class and
this is created on application initialisation (ie: when the User first
connects with the website), irrespective of whether the user is logged
in or not. By default, the user is set to “ Guest”. Authentication is
managed by a class called CUserIdentity and this class checks that the
user is known and a valid user. How this validation occurs will depend
on your application, perhaps against a database, or login with
facebook, or against an ldap server etc...
And what is the benefit of using all those classes? I can do everything just by User model. If I set scenario "login", password will be checked during validation. If validation is OK, I can set to session my own variable like this:
$model = new User("login");
$model->attributes = $_POST["User"];
if ($model->validate())
{
Yii::app()->session["currentUser"] = $model;
}
else
{
// .. show error
unset(Yii::app()->session["currentUser"]);
}
In User model I have then static methods to check this variable
public static function isGuest()
{
return isset(Yii::app()->session["currentUser"]);
}
public static function getCurrent()
{
return Yii::app()->session["currentUser"];
}
And I can call it very shortly:
User::isGuest();
$model = User::getCurrent();
// instead of writing this:
Yii::app()->user->isGuest;
So why should I use so complicated hierarchy of classes that is suggested by Yii? I never understood it.

Symfony2: User entity class which implements UserInterface: Use email instead of username

I am trying to work with the symfony2 login. I have my entity class connected to the database. In my table, I have only the user's email, which is the username. Should I use the getUsername() method knowing that I don't have a real username.
When I try to delete this method, I am geting a fatal error message :
Fatal error: Class MDPI\BackendBundle\Entity\Users contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Symfony\Component\Security\Core\User\UserInterface::getUsername) in /home/milos/workspace/mdpi-login2/src/MDPI/BackendBundle/Entity/Users.php on line 768
Should I use
getUsername()
{
return this->email;
}
Or is there a nicer way of doing this ???
Thank you.
Using the native Symfony SecurityBundle, you just have to specify the entity field you use as login string, in app/config/security.yml :
security:
encoders:
MDPI\BackendBundle\Entity\User: plaintext
providers:
entity:
entity: { class: MDPI\BackendBundle\Entity\User, property: email }
firewalls:
...