|
class AuthenticationFailed private(message: String = "") extends Throwable(message) { |
|
def this(message: String, cause: Throwable) = { |
|
this(message) |
|
initCause(cause) |
|
} |
|
def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) |
|
} |
|
// Companion Object |
|
object AuthenticationFailed { |
|
def apply() = new AuthenticationFailed(null: String) |
|
def apply(message: String) = new AuthenticationFailed(message) |
|
def apply(cause: Throwable) = new AuthenticationFailed(cause) |
|
def apply(message: String, cause: Throwable) = new AuthenticationFailed(message, cause) |
|
|
|
def unapply(ex: AuthenticationFailed): Option[(String, Throwable)] = Some((ex.getMessage, ex.getCause)) |
|
} |
|
|
|
def appLogin(name: String, password: String) = { |
|
if (name.equals("tester")) true |
|
else throw AuthenticationFailed(s"App. account with $name does not exist!") |
|
} |
|
|
|
def gmailLogin(name: String, password: String) = { |
|
if (name.equals("[email protected]")) true |
|
else throw AuthenticationFailed(s"Gmail account with $name does not exist!") |
|
} |
|
|
|
def fbLogin(name: String, password: String) = { |
|
if (name.equals("[email protected]")) true |
|
else throw AuthenticationFailed(s"Facebook with $name does not exist!") |
|
} |
|
|
|
// NOTE: printlns are given to help you grasp the flow very quickly, |
|
// when you run the program. They are not required to be present |
|
// when refactoring. |
|
// |
|
def authenticate(name: String, password: String): Boolean = { |
|
try { |
|
println(s"Trying Application Login...") |
|
appLogin(name, password) |
|
} catch { |
|
case AuthenticationFailed(msg, cause) => |
|
println(s"Failed App Login => $msg") |
|
try { |
|
println(s"Trying Gmail Login...") |
|
gmailLogin(name, password) |
|
} catch { |
|
case AuthenticationFailed(msg, cause) => |
|
println(s"Failed Gmail Login => $msg") |
|
try { |
|
println(s"Trying Facebook Login...") |
|
fbLogin(name, password) |
|
} catch { |
|
case AuthenticationFailed(msg, cause) => |
|
println(s"Failed Facebook Login => $msg") |
|
false |
|
} |
|
} |
|
} |
|
} |
|
|
|
println(authenticate("tester", "password")) // true |
|
println(authenticate("[email protected]", "aPassword")) // true |
|
println(authenticate("[email protected]", "psswd")) // true |
|
println(authenticate("someone", "somepassword")) // false |