mercredi 22 avril 2020

using best practice for chain responsibility in asp core

i have senario for login user. i write this code for check user if validate return success message .

i using the chain responsibility pattern for this validation but it seems ugly beacuse i need to more new in this class .

now i want to write clean and best practice for using this pattern .

how can i do this ????

 public abstract class ValidateUser
{
    protected readonly ValidateUser _validateUser;
    public ValidateUser(ValidateUser validateUser)
    {
        _validateUser = validateUser;
    }
    public abstract UserContext ValidateUserLogin(UserContext request);
}

CheckIsActive :

 public class CheckIsActive : ValidateUser
{
    public CheckIsActive(ValidateUser validateUser) : base(validateUser)
    {
    }

    public override UserContext ValidateUserLogin(UserContext request)
    {
        if (request.Context.IsActive)
        {
            return _validateUser.ValidateUserLogin(request);
        }
        return new UserContext
        {
            Message = "User Not Active"
        };
    }
}

CheckPhoneConfirmed :

public class CheckPhoneConfirmed : ValidateUser
{
    public CheckPhoneConfirmed(ValidateUser validateUser) : base(validateUser)
    {
    }

    public override UserContext ValidateUserLogin(UserContext request)
    {
        if (request.Context.ConfirmPhoneNumber)
        {
            return _validateUser.ValidateUserLogin(request);
        }
        return new UserContext
        {
            Message="Phone Number Not confirmed"
        };
    }
}

CheckIsLockedAccount :

 public  class CheckIsLockedAccount : ValidateUser
{
    public CheckIsLockedAccount(ValidateUser validateUser) : base(validateUser)
    {
    }

    public override UserContext ValidateUserLogin(UserContext request)
    {
        if (!request.Context.IsLockedEnd)
        {
            return new UserContext
            {
                Context=request.Context
            };
        }
        return new UserContext
        {
            Message = $"Yuor Account Deactive From To Date {request.Context.LockedEnd}"
        };
    }
}

and i use this Validate by this way :

var validate = new CheckIsActive(new CheckPhoneConfirmed(new CheckIsLockedAccount(null)));
                var validateUserContext = validate.ValidateUserLogin(new UserContext
                {
                    Context = findUSer.Result,
                    Message = null
                });

Aucun commentaire:

Enregistrer un commentaire