Perhaps not the simplest solution to implement, but you could look into using Aspect Oriented Programming. You could then annotate each method which requires user login. This makes the code clean and readable.
[ConfirmUser(ErrorMethod=... RequireUsername=false, RequirePassword=true )]
public void ViewData()
{
// your code
}
The AOP framework would weave in the required code to handle the user confirmation in your method.
Or do the same thing inside the methods manually:
public void ViewData()
{
ConfirmUser();
// your code
}
public void ConfirmUser()
{
if( !DoLoginPage() ) throw new SecurityException("Incorrect credentials");
}
You could have ConfirmUser return a bool instead of an exception. That's another discussion, and depends on your application. If you deny operations in lower code layers, an exception is the way to go. A try/catch makes you put the error handling at the bottom of the function, while a returning bool requires and if statement at the top.
public void ViewData()
{
try
{
ConfirmUser();
// your code
}
catch( SecurityException )
{
//handle error
}
}
vs
public void ViewData()
{
if( !ConfirmUser() )
{
//handle error
return;
}
// your code
}
You could implement both ConfirmUser and ConfirmPassword, or have both in the same method with a parameter, perhaps an enum to say what you need to verify.
[Flags]
public enum Requires
{
Username,
Password
}
public bool ConfirmUser( Requires requiresField )
{
}