jeudi 6 octobre 2022

C# - Correct approach for method with various validations

I want to know what is the correct way of doing this: lets say I have a login method that receives username and password, and log ins the user or return invalid username/password or not enough permissions. What is the correct way of doing this?

Way #1: throwing exception and handling in the user interface to display the error

public void Login(string username, string password)
{
       if (SessionService.GetSession.IsLoggedIn)
       {
           throw new Exception("User is already logged in");
       }

       var user = GetByUsername(username);

       if (user == null)
       {
           throw new LoginException(LoginResultEnum.InvalidUsername);
       }

       var hashPass = EncryptionService.Hash(password);
       if (hashPass != user.password)
       {
           throw new LoginException(LoginResultEnum.InvalidPassword);
       }

       if (!user.HasPermission(PermissionTypeEnum.CanLogIn))
       {
           throw new MissingPermissionException(TipoPermisoEnum.CanLogIn);
       }

       SessionService.GetSession.Login(user);

}

Way #2: returning boolean true/false and handle the error in the UI (success or fail)

public bool Login(string username, string password)
{
       if (SessionService.GetSession.IsLoggedIn)
       {
           return false;
       }

       var user = GetByUsername(username);

       if (user == null)
       {
           return false;
       }

       var hashPass = EncryptionService.Hash(password);
       if (hashPass != user.password)
       {
           return false;
       }

       if (!user.HasPermission(PermissionTypeEnum.CanLogIn))
       {
           return false;
       }

       SessionService.GetSession.Login(user);
       return true;

}

Way #3: returning a LoginResult enum and handle in the UI

public LoginResult Login(string username, string password)
{
       if (SessionService.GetSession.IsLoggedIn)
       {
           return LoginResult.AlreadyLoggedIn;
       }

       var user = GetByUsername(username);

       if (user == null)
       {
           return LoginResult.InvalidUsername;
       }

       var hashPass = EncryptionService.Hash(password);
       if (hashPass != user.password)
       {
           return LoginResult.InvalidPassword;
       }

       if (!user.HasPermission(PermissionTypeEnum.CanLogIn))
       {
           return LoginResult.Forbidden;
       }

       SessionService.GetSession.Login(user);
       return LoginResult.OK;

}

Aucun commentaire:

Enregistrer un commentaire