-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
226 lines (192 loc) · 8.38 KB
/
server.js
File metadata and controls
226 lines (192 loc) · 8.38 KB
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
import * as dotenv from "dotenv";
dotenv.config();
import express from "express";
import fetch from "node-fetch";
import https from "https";
import { v4 as uuidv4 } from "uuid";
import PlayFab from "./node_modules/playfab-sdk/Scripts/PlayFab/PlayFab.js";
import PlayFabClient from "./node_modules/playfab-sdk/Scripts/PlayFab/PlayFabClient.js";
const app = express();
app.use(express.json());
const GOOGLE_OAUTH_URL = process.env.GOOGLE_OAUTH_URL;
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
// TODO: replace the callback URLs from your Google Cloud Console App Settings
const GOOGLE_CALLBACK_URL = "http%3A//dev.alteredverse.sg:5000/google/callback";
const GOOGLE_CALLBACK_URL_NOT_SAFE = "http://dev.alteredverse.sg:5000/google/callback";
const PLAYFAB_LOGIN_STATUS_URL = "http://dev.alteredverse.sg:5000/playfab/login/status";
// const GOOGLE_OAUTH_SCOPES = [
// "https%3A//www.googleapis.com/auth/userinfo.email",
// "https%3A//www.googleapis.com/auth/userinfo.profile"
// ];
const GOOGLE_OAUTH_SCOPES = [
"https%3A//www.googleapis.com/auth/userinfo.profile"
];
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
const GOOGLE_ACCESS_TOKEN_URL = process.env.GOOGLE_ACCESS_TOKEN_URL;
const PLAYFAB_APP_TITLE_ID = process.env.PLAYFAB_APP_TITLE_ID;
const PORT = process.env.PORT || 3000;
//====================================================//
// GLOBALS //
//====================================================//
//var PlayFab = require("./node_modules/playfab-sdk/Scripts/PlayFab/PlayFab");
//var PlayFabClient = require("./node_modules/playfab-sdk/Scripts/PlayFab/PlayFabClient");
var IdTokenMap = new Map();
var playFabResMsg = "Playfab Login Complete";
//====================================================//
// HOME //
//====================================================//
app.get("/", async (req, res) => {
res.send("Playfab HOME");
});
//====================================================//
// UUID //
//====================================================//
app.get("/uuid", async(req, res)=>{
res.json({uuid:uuidv4()});
});
//====================================================//
// LOGIN with Custom ID //
//====================================================//
function DoExampleLoginWithCustomID() {
PlayFab.settings.titleId = "C0466";
var loginRequest = {
// Currently, you need to look up the correct format for this object in the API reference for LoginWithCustomID. The Request Headers and Request Body are included as keys and values in the request object.
TitleId: PlayFab.settings.titleId,
CustomId: "GettingStartedGuide",
CreateAccount: true
};
// For functions in the Node SDK, the first parameter will be the request object and the second parameter will be the callback function. The callback function executes after the request returns.
PlayFabClient.LoginWithCustomID(loginRequest, LoginWithCustomIDCallback);
}
function LoginWithCustomIDCallback(error, result) {
if (result !== null) {
console.log("\nCongratulations, you made your first successful API call!");
} else if (error !== null) {
console.log("Something went wrong with your first API call.");
console.log("Here's some debug information:");
console.log(CompilePlayfabErrorReport(error));
}
}
app.get("/login/customid", async (req, res) => {
DoExampleLoginWithCustomID();
res.send("LOGIN with Custom ID Complete");
});
//====================================================//
// LOGIN with Google //
//====================================================//
function LoginWithGoogleCallback(error, result) {
//console.log(`\nLoginWithGoogleCallback::result:${ JSON.stringify(result) }`);
if (result !== null) {
console.log("\nCongratulations, you have successfully logged-in account to Playfab!");
playFabResMsg = "\nCongratulations, you have successfully logged-in account to Playfab!";
} else if (error !== null) {
console.log("\nSomething went wrong with your first API call.");
console.log("Here's some debug information:");
console.log(CompilePlayfabErrorReport(error));
playFabResMsg = "\nSomething went wrong with your first API call.";
}
}
app.get("/playfab/login/status", async (req, res) => {
console.log(`handled redirection for playfab login with msg:${playFabResMsg}`);
res.send(playFabResMsg);
});
app.get("/google/callback", async (req, res) => {
const { code } = req.query;
const data = {
code,
client_id: GOOGLE_CLIENT_ID,
client_secret: GOOGLE_CLIENT_SECRET,
redirect_uri: GOOGLE_CALLBACK_URL_NOT_SAFE,
grant_type: "authorization_code",
};
const response = await fetch(GOOGLE_ACCESS_TOKEN_URL, {
method: "POST",
body: JSON.stringify(data),
});
const access_token_data = await response.json();
let access_token = access_token_data.access_token;
IdTokenMap.set(req.query.state, access_token);
const { id_token } = access_token_data;
const token_info_response = await fetch(
`${process.env.GOOGLE_TOKEN_INFO_URL}?id_token=${id_token}`
);
PlayFab.settings.titleId = PLAYFAB_APP_TITLE_ID;
var loginRequest = {
TitleId: PlayFab.settings.titleId,
CreateAccount: true,
AccessToken: access_token
};
PlayFabClient.LoginWithGoogleAccount( loginRequest, LoginWithGoogleCallback );
//res.send(`Google Login Callback`);
//res.send(msg);
res.redirect(PLAYFAB_LOGIN_STATUS_URL);
});
app.get("/login/google", async (req, res) => {
let uuid = req.query.uuid;
const state = uuid; // TODO: replace with uuid
const scopes = GOOGLE_OAUTH_SCOPES.join(" ");
// const GOOGLE_OAUTH_CONSENT_SCREEN_URL = `${GOOGLE_OAUTH_URL}?client_id=${GOOGLE_CLIENT_ID}&redirect_uri=${GOOGLE_CALLBACK_URL}&access_type=offline&response_type=code&state=${state}&scope=${scopes}`;
const GOOGLE_OAUTH_CONSENT_SCREEN_URL = `${GOOGLE_OAUTH_URL}?client_id=${GOOGLE_CLIENT_ID}&redirect_uri=${GOOGLE_CALLBACK_URL}&access_type=offline&response_type=code&state=${state}&scope=${scopes}&include_granted_scopes=true`;
res.redirect(GOOGLE_OAUTH_CONSENT_SCREEN_URL);
//res.send("LOGIN with Google Complete");
});
//====================================================//
// REVOKE //
//====================================================//
// reference: https://developers.google.com/identity/protocols/oauth2/web-server#tokenrevoke
// or let the user go to this URL https://myaccount.google.com/connections?filters=3,4&hl=en&pli=1
// and revoke the access to your Google Cloud Application
app.get("/revoke", async (req, res)=>{
let uuid = req.query.uuid;
let msg;
// let postData = "token=" + access_token;
let postData = "token=" + IdTokenMap.get(uuid);
let postOptions = {
host: 'oauth2.googleapis.com',
port: '443',
path: '/revoke',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const postReq = https.request(postOptions, function (r) {
r.setEncoding('utf8');
r.on('data', d => {
msg = d;
});
});
postReq.on('error', error => {
msg = error;
console.log(error)
});
// Post the request with data
postReq.write(postData);
postReq.end();
IdTokenMap.delete(uuid);
console.log("\nIdTokenMap.size:"+IdTokenMap.size);
res.send("REVOKED");
});
//====================================================//
// UTILS //
//====================================================//
// This is a utility function we haven't put into the core SDK yet. Feel free to use it.
function CompilePlayfabErrorReport(error) {
if (error == null)
return "";
var fullErrors = error.errorMessage;
for (var paramName in error.errorDetails)
for (var msgIdx in error.errorDetails[paramName])
fullErrors += "\n" + paramName + ": " + error.errorDetails[paramName][msgIdx];
return fullErrors;
}
//====================================================//
// INITIALIZATION //
//====================================================//
const start = async (port) => {
app.listen(port, () => {
console.log(`Server running on port: http://localhost:${port}`);
});
};
start(PORT);