- Convert imperative scala code to functional-style using
Future
- Refer to
Authentication.scala
for this refactoring. - You are not allowed to change the signature of
loginChores
, feel free to do whatever you want with other functions.
Last active
April 18, 2019 13:13
-
-
Save DhavalDalal/04f83edf5162a216752c31bacf35ca1c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class User(login: String, name: String) | |
def login(login: String, pwd: String): User = { | |
println(s"Inside system login: $login") | |
Thread.sleep(500) | |
if (login == "" || login == null || login.contains("@gmail")) throw new Exception(s"invalid id $login") | |
else if (pwd == "" || pwd == null) throw new Exception("invalid password") | |
else User(login, "Dhaval") | |
} | |
def gmailLogin(login: String, pwd: String): User = { | |
println(s"Inside gmail login: $login") | |
Thread.sleep(1000) | |
if (login.contains("@gmail")) User(login, "Dhaval") | |
else if (pwd == "" || pwd == null) throw new Exception("invalid password") | |
else throw new Exception("Not a Gmail Id!") | |
} | |
def twoFactor(user: User, pwd: Long): User = { | |
println(s"Inside twoFactor: ${user.login}") | |
Thread.sleep(500) | |
if (pwd >= 100000 && pwd <= 999999) user | |
else throw new Exception("twoFactor: Incorrect key") | |
} | |
import java.net.URL | |
def redirect(target: URL) = println(s"Going to => $target") | |
def loginChores(userid: String, pwd: String, twoFactorPwd: Long): Unit = { | |
val dashboard = new URL("https://dashboard") | |
val loginPage = new URL("https://login") | |
var user: User = null | |
try { | |
user = login(userid, pwd) | |
} catch { | |
case e: Exception => | |
println("system login failed = " + e.getMessage) | |
try { | |
user = gmailLogin(userid, pwd) | |
} catch { | |
case eg: Exception => | |
println("gmail login failed = " + eg.getMessage) | |
redirect(loginPage) | |
return | |
} | |
} | |
var target: URL = null | |
try { | |
twoFactor(user, twoFactorPwd) | |
target = dashboard | |
} catch { | |
case e: Exception => | |
println("Two factor auth failed = " + e.getMessage) | |
target = loginPage | |
} | |
redirect(target) | |
} | |
// System Login Path success | |
loginChores("[email protected]", "test", 123456) | |
// System Login Path 2-factor fails | |
loginChores("[email protected]", "test", 12345) | |
// Gmail Login Path success | |
loginChores("[email protected]", "test", 123456) | |
// Gmail Login Path 2-factor fails | |
loginChores("[email protected]", "test", 12345) | |
// System Login and Gmail Login fails | |
loginChores("", "test", 123456) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment