summaryrefslogtreecommitdiffstats
path: root/logic/net/LoginTask.cpp
blob: 5de8efa9d522288ff7a30751982b281a66c0eb86 (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/* Copyright 2013 MultiMC Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "LoginTask.h"
#include "MultiMC.h"
#include <settingsobject.h>

#include <QStringList>

#include <QNetworkReply>
#include <QNetworkRequest>

#include <QUrl>
#include <QUrlQuery>
#include <QJsonParseError>
#include <QJsonObject>

LoginTask::LoginTask(const UserInfo &uInfo, QObject *parent) : Task(parent), uInfo(uInfo)
{
}

void LoginTask::executeTask()
{
	yggdrasilLogin();
}

void LoginTask::legacyLogin()
{
	setStatus(tr("Logging in..."));
	auto worker = MMC->qnam();
	connect(worker.get(), SIGNAL(finished(QNetworkReply *)), this,
			SLOT(processLegacyReply(QNetworkReply *)));

	QUrl loginURL("https://login.minecraft.net/");
	QNetworkRequest netRequest(loginURL);
	netRequest.setHeader(QNetworkRequest::ContentTypeHeader,
						 "application/x-www-form-urlencoded");

	QUrlQuery params;
	params.addQueryItem("user", uInfo.username);
	params.addQueryItem("password", uInfo.password);
	params.addQueryItem("version", "13");

	netReply = worker->post(netRequest, params.query(QUrl::EncodeSpaces).toUtf8());
}

void LoginTask::processLegacyReply(QNetworkReply *reply)
{
	if (netReply != reply)
		return;
	// Check for errors.
	switch (reply->error())
	{
	case QNetworkReply::NoError:
	{
		// Check the response code.
		int responseCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

		if (responseCode == 200)
		{
			parseLegacyReply(reply->readAll());
		}
		else if (responseCode == 503)
		{
			emitFailed(tr("The login servers are currently unavailable. Check "
						  "http://help.mojang.com/ for more info."));
		}
		else
		{
			emitFailed(tr("Login failed: Unknown HTTP error %1 occurred.")
						   .arg(QString::number(responseCode)));
		}
		break;
	}

	case QNetworkReply::OperationCanceledError:
		emitFailed(tr("Login canceled."));
		break;

	default:
		emitFailed(tr("Login failed: %1").arg(reply->errorString()));
		break;
	}
}

void LoginTask::parseLegacyReply(QByteArray data)
{
	QString responseStr = QString::fromUtf8(data);

	QStringList strings = responseStr.split(":");
	if (strings.count() >= 4)
	{
		// strings[1] is the download ticket. It isn't used anymore.
		QString username = strings[2];
		QString sessionID = strings[3];
		/*
		struct LoginResponse
		{
			QString username;
			QString session_id;
			QString player_name;
			QString player_id;
			QString client_id;
		};
		*/
		result = {username, sessionID, username, QString()};
		emitSucceeded();
	}
	else
	{
		if (responseStr.toLower() == "bad login")
			emitFailed(tr("Invalid username or password."));
		else if (responseStr.toLower() == "old version")
			emitFailed(tr("Launcher outdated, please update."));
		else
			emitFailed(tr("Login failed: %1").arg(responseStr));
	}
}


void LoginTask::yggdrasilLogin()
{
	setStatus(tr("Logging in..."));
	auto worker = MMC->qnam();
	connect(worker.get(), SIGNAL(finished(QNetworkReply *)), this,
			SLOT(processYggdrasilReply(QNetworkReply *)));

	/*
	{
		// agent def. version might be incremented at some point
		"agent":{"name":"Minecraft","version":1},
		"username": "mojang account name",
		"password": "mojang account password",
		// client token is optional. but we supply one anyway
		"clientToken": "client identifier"
	}
	*/

	QUrl loginURL("https://authserver.mojang.com/authenticate");
	QNetworkRequest netRequest(loginURL);
	netRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

	auto settings = MMC->settings();
	QString clientToken = settings->get("YggdrasilClientToken").toString();
	// escape the {}
	clientToken.remove('{');
	clientToken.remove('}');
	// create the request
	QString requestConstent;
	requestConstent += "{";
	requestConstent += "    \"agent\":{\"name\":\"Minecraft\",\"version\":1},\n";
	requestConstent += "    \"username\":\"" + uInfo.username + "\",\n";
	requestConstent += "    \"password\":\"" + uInfo.password + "\",\n";
	requestConstent += "    \"clientToken\":\"" + clientToken + "\"\n";
	requestConstent += "}";
	netReply = worker->post(netRequest, requestConstent.toUtf8());
}

void LoginTask::processYggdrasilReply(QNetworkReply *reply)
{
	if (netReply != reply)
		return;
	// Check for errors.
	switch (reply->error())
	{
	case QNetworkReply::NoError:
	{
		// Check the response code.
		int responseCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

		if (responseCode == 200)
		{
			parseYggdrasilReply(reply->readAll());
		}
		else if (responseCode == 503)
		{
			emitFailed(tr("The login servers are currently unavailable. Check "
						  "http://help.mojang.com/ for more info."));
		}
		else
		{
			emitFailed(tr("Login failed: Unknown HTTP error %1 occurred.")
						   .arg(QString::number(responseCode)));
		}
		break;
	}

	case QNetworkReply::OperationCanceledError:
		emitFailed(tr("Login canceled."));
		break;

	default:
		emitFailed(tr("Login failed: %1").arg(reply->errorString()));
		break;
	}
}

/*
{
  "accessToken": "random access token",  // hexadecimal
  "clientToken": "client identifier",    // identical to the one received
  "availableProfiles": [                 // only present if the agent field was received
    {
      "id": "profile identifier",        // hexadecimal
      "name": "player name"
    }
  ],
  "selectedProfile": {                   // only present if the agent field was received
    "id": "profile identifier",
    "name": "player name"
  }
}
*/
void LoginTask::parseYggdrasilReply(QByteArray data)
{
	QJsonParseError jsonError;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);
	if (jsonError.error != QJsonParseError::NoError)
	{
		emitFailed(tr("Login failed: %1").arg(jsonError.errorString()));
		return;
	}

	if (!jsonDoc.isObject())
	{
		emitFailed(tr("Login failed: BAD FORMAT #1"));
		return;
	}

	QJsonObject root = jsonDoc.object();

	QString accessToken = root.value("accessToken").toString();
	QString clientToken = root.value("clientToken").toString();
	QString playerID;
	QString playerName;
	auto selectedProfile = root.value("selectedProfile");
	if(selectedProfile.isObject())
	{
		auto selectedProfileO = selectedProfile.toObject();
		playerID = selectedProfileO.value("id").toString();
		playerName = selectedProfileO.value("name").toString();
	}
	QString sessionID = "token:" + accessToken + ":" + playerID;
	/*
	struct LoginResponse
	{
		QString username;
		QString session_id;
		QString player_name;
		QString player_id;
		QString client_id;
	};
	*/
	
	result = {uInfo.username, sessionID, playerName, playerID};
	emitSucceeded();
}