This repository has been archived by the owner on May 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LogIn.scala
59 lines (50 loc) · 1.6 KB
/
LogIn.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.gu.automation.support
import com.gu.automation.api.AuthApi
import org.openqa.selenium.{Cookie, WebDriver}
import scala.concurrent.duration._
import scala.concurrent.Await
;
/**
* Example: if your local.conf contains:
*
* userName: {
* loginEmail: "asdf@theguardian.com"
* loginPassword: passw0rd
* }
*
* You would do this code:
*
* LogIn(Some("userName"))
* ExamplePage.goto()
*
*/
object LogIn {
def getCookieDomain(url: String) =
"""http(s?)://([^.]*(\.))?([^/]+).*$""".r.replaceAllIn(url, "$3$4")
def apply()(implicit driver: WebDriver) = {
apply(None, driver)
}
def apply(user: String)(implicit driver: WebDriver) = {
apply(Some(user), driver)
}
private def apply(user: Option[String], driver: WebDriver) = {
val idApiRoot = Config().getIdApiRoot()
val loginEmail = Config().getLoginEmail(user)
val loginPassword = Config().getLoginPassword(user)
val baseUrl = Config().getTestBaseUrl()
val loginDomain = getCookieDomain(baseUrl)
driver.get(baseUrl) // have to be on the right url to add the cookies
val future = AuthApi(idApiRoot).authenticate(loginEmail, loginPassword)
val accessToken = Await.result(future, 10.seconds)
val cookies = accessToken match {
case Right(cookies) => cookies
case Left(error) => throw new RuntimeException(s"authenticate $loginEmail failed: $error")
}
cookies.foreach {
case (key, value) =>
val isSecure = key.startsWith("SC_")
val cookie = new Cookie(key, value, loginDomain, "/", null, isSecure, isSecure)
driver.manage().addCookie(cookie)
}
}
}