Skip to content

Instantly share code, notes, and snippets.

@mimi89999
Created September 14, 2018 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mimi89999/e4a49232fdfc7425d3412abea000a720 to your computer and use it in GitHub Desktop.
Save mimi89999/e4a49232fdfc7425d3412abea000a720 to your computer and use it in GitHub Desktop.
import java.util.regex.Pattern
import java.net.CookieManager
import java.net.CookiePolicy
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.JavaNetCookieJar
import okhttp3.RequestBody
import okhttp3.MediaType
import org.json.JSONObject
fun login(username: String, password: String): String {
val jsonMediaType = MediaType.parse("application/json; charset=utf-8")
val patternCSRF = Pattern.compile("<meta name=\"csrf-token\" content=\"(.*?)\">")
val cookieManager = CookieManager()
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)
val client = OkHttpClient.Builder()
.cookieJar(JavaNetCookieJar(cookieManager))
.followRedirects(false)
.build()
val cookieRequest = Request.Builder()
.url("https://portal.librus.pl/oauth2/authorize?" +
"client_id=wmSyUMo8llDAs4y9tJVYY92oyZ6h4lAt7KCuy0Gv&" +
"redirect_uri=http://localhost/bar&response_type=code")
.build()
client.newCall(cookieRequest).execute()
val csrfRequest = Request.Builder()
.url("https://portal.librus.pl/rodzina/login")
.build()
val response = client.newCall(csrfRequest).execute()
val matcher = patternCSRF.matcher(response.body()!!.string())
matcher.find()
val csrf = matcher.group(1)
val loginFormBodyJson = JSONObject()
.put("email", username)
.put("password", password)
val loginFormBody = RequestBody.create(jsonMediaType, loginFormBodyJson.toString())
val portalLoginRequest = Request.Builder()
.addHeader("X-CSRF-TOKEN", csrf)
.url("https://portal.librus.pl/rodzina/login/action")
.post(loginFormBody)
.build()
client.newCall(portalLoginRequest).execute()
val codeRequest = Request.Builder()
.url("https://portal.librus.pl/oauth2/authorize?" +
"client_id=wmSyUMo8llDAs4y9tJVYY92oyZ6h4lAt7KCuy0Gv&" +
"redirect_uri=http://localhost/bar&response_type=code")
.build()
val codeResponse = client.newCall(codeRequest).execute()
return codeResponse.header("Location")!!.split("code=")[1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment