Skip to content

Commit

Permalink
Fixed problems with token refreshing, can now save uuid in cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
drusin committed Dec 27, 2017
1 parent 96c1f8b commit dc6489e
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 23 deletions.
38 changes: 24 additions & 14 deletions src/main/java/dawid/connect_router/Controller.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ public class Controller {
private boolean retrying = false;

@RequestMapping(path = "/login", method = RequestMethod.GET)
public RedirectView login() {
public RedirectView login(@RequestParam("uuid") UUID uuid) {
if (!ConnectRouterApplication.getUuid().equals(uuid)) {
return null;
}
String url = "https://accounts.spotify.com/authorize?client_id="
+ clientId
+ "&response_type=code"
Expand All @@ -63,18 +66,23 @@ public RedirectView redirect(@RequestParam("code") String code) throws Exception
tokenRepository.delete(0);
}
tokenRepository.save(token);
System.out.println("Logged in succesfully!");
retrying = false;
return new RedirectView("/redirected.html?Logged in succesfully");
} catch (IOException e) {
System.err.println("Login failed");
return new RedirectView("/redirected.html?Something went wrong, try again");
}
}

public RedirectView reauthenticate() throws Exception {
public void reauthenticate() throws Exception {
System.out.println("Trying to refresh the token!");
String refreshToken = tokenRepository.findOne(0).getRefreshToken();
MultipartBody multipartBody = Unirest.post("https://accounts.spotify.com/api/token")
.field("client_id", clientId)
.field("client_secret", clientSecret)
.field("grant_type", "refresh_token")
.field("refresh_token", tokenRepository.findOne(0).getRefreshToken());
.field("refresh_token", refreshToken);
HttpResponse<String> stringHttpResponse = multipartBody
.asString();
ObjectMapper objectMapper = new ObjectMapper();
Expand All @@ -83,28 +91,30 @@ public RedirectView reauthenticate() throws Exception {
if (tokenRepository.findOne(0) != null) {
tokenRepository.delete(0);
}
token.setRefreshToken(refreshToken);
tokenRepository.save(token);
return new RedirectView("/redirected.html?Logged in succesfully");
System.out.println("Refreshed token successfully!");
} catch (IOException e) {
return new RedirectView("/redirected.html?Something went wrong, try again");
System.err.println("Could not refresh token");
}
}

@RequestMapping(path = "/devices", method = RequestMethod.GET)
public String devices(@RequestParam("uuid") String uuid) throws Exception {
if (!ConnectRouterApplication.getUuid().toString().equals(uuid)) {
public String devices(@RequestParam("uuid") UUID uuid) throws Exception {
if (!ConnectRouterApplication.getUuid().equals(uuid)) {
return null;
}
HttpResponse<JsonNode> request = Unirest.get("https://api.spotify.com/v1/me/player/devices")
.header("Authorization", "Bearer " + tokenRepository.findOne(0).getAccessToken())
.asJson();
if (request.getStatus() != 200) {
if (!retrying) {
if (request.getStatus() == 401 && !retrying) {
retrying = true;
reauthenticate();
devices(uuid);
return devices(uuid);
}
return "Cannot authenticate, try logging in again!";
System.err.println("Error trying to get devices: " + request.getStatus() + " " + request.getStatusText() + " " + request.getBody());
return "Cannot get devices " + request.getStatus() + " " + request.getStatusText() + " " + request.getBody();
}
retrying = false;
return request.getBody().toString();
Expand All @@ -120,18 +130,18 @@ public String transferPlayback(@RequestParam("uuid") UUID uuid, @RequestBody Ali
.body("{\"device_ids\": [\"" + aliasRepository.findOne(alias.alias.trim()).deviceId + "\"]}")
.asString();
if (request.getStatus() != 204) {
if (!retrying) {
if (request.getStatus() == 401 && !retrying) {
retrying = true;
reauthenticate();
transferPlayback(uuid, alias);
return transferPlayback(uuid, alias);
}
return "Cannot authenticate, try logging in again!";
System.err.println("Error trying to transfer playback: " + request.getStatus() + " " + request.getStatusText() + " " + request.getBody());
return "Cannot transfer playback " + request.getStatus() + " " + request.getStatusText() + " " + request.getBody();
}
retrying = false;
return Integer.toString(request.getStatus());
}


@RequestMapping(path = "/alias", method = RequestMethod.PUT)
public void setAlias(@RequestParam("uuid") UUID uuid, @RequestBody AliasDeviceMapping alias) {
if (!uuid.equals(ConnectRouterApplication.getUuid())) {
Expand Down
23 changes: 23 additions & 0 deletions src/main/resources/static/cookie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const uuidInput = document.getElementById("uuid");
const rememberUuid = document.getElementById("remember-uuid");

uuidInput.oninput = doRemember;
rememberUuid.onchange = doRemember;

function doRemember() {
if (rememberUuid.checked) {
document.cookie = "uuid=" + uuidInput.value + "; expires=" + new Date(new Date().getFullYear + 5).toUTCString() + ", path=/";
}
else {
document.cookie = "uuid=; expires=Thu, 01 Jan 1970 00:00:00 UTC, path=/";
}
}

function uuid() {
return "?uuid=" + uuidInput.value;
}

if (document.cookie.indexOf("uuid=") != -1) {
uuidInput.value = document.cookie.split("=")[1];
rememberUuid.checked = true;
}
7 changes: 6 additions & 1 deletion src/main/resources/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
<title>Login to Spotify</title>
</head>
<body>
<a href="/login">Login to spotify</a>
<div>UUID: <input type="text" id="uuid"><input type="checkbox" id="remember-uuid" name="remember-check"><label for="remember-uuid">Store UUID in cookie for further use?</label></div>
<a id="login">Login to spotify</a>
<script src="cookie.js"></script>
<script>
document.getElementById("login").href = "/login" + uuid();
</script>
</body>
</html>

4 changes: 3 additions & 1 deletion src/main/resources/static/setup.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
<title>Setup</title>
</head>
<body>
<div>UUID: <input type="text" id="uuid"><button id="reload">Reload</button></div>
<div>UUID: <input type="text" id="uuid"><input type="checkbox" id="remember-uuid" name="remember-check"><label for="remember-uuid">Store UUID in cookie for further use?</label></div>
<button id="reload">Reload</button>
<table>
<tr>
<th>Device name</th>
Expand All @@ -21,6 +22,7 @@
</table>

<script src="jquery-3.2.1.min.js"></script>
<script src="cookie.js"></script>
<script src="setup.js"></script>
</body>
</html>
9 changes: 2 additions & 7 deletions src/main/resources/static/setup.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
const table = document.getElementsByTagName("table")[0];
const template = document.getElementById("template-row");
const uuidInput = document.getElementById("uuid");

function uuid() {
return "?uuid=" + uuidInput.value;
}

function saveAlias(id, alias) {
$.ajax({
Expand Down Expand Up @@ -34,8 +29,8 @@ function play(alias) {

function displayDevices() {
const oldRows = document.getElementsByClassName("row");
for (let i = 0; i < oldRows.length; i++) {
table.removeChild(oldRows[i]);
while (oldRows.length > 0) {
table.removeChild(oldRows[0]);
}
$.get("/devices" + uuid()).done(response => {
JSON.parse(response).devices.forEach(device => {
Expand Down

0 comments on commit dc6489e

Please sign in to comment.