generated from Real-Dev-Squad/website-template
-
Notifications
You must be signed in to change notification settings - Fork 203
/
auth.js
219 lines (199 loc) · 6.68 KB
/
auth.js
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
const passport = require("passport");
const users = require("../models/users");
const QrCodeAuthModel = require("../models/qrCodeAuth");
const authService = require("../services/authService");
const dataAccess = require("../services/dataAccessLayer");
const {
SOMETHING_WENT_WRONG,
DATA_ADDED_SUCCESSFULLY,
USER_DOES_NOT_EXIST_ERROR,
} = require("../constants/errorMessages");
/**
* Makes authentication call to GitHub statergy
*
* @param req {Object} - Express request object
* @param res {Object} - Express response object
* @param next {Function} - Express middleware function
*/
const githubAuthLogin = (req, res, next) => {
let { sourceUtm, redirectURL } = req.query;
const isMobileApp = sourceUtm === "rds-mobile-app";
if (isMobileApp) {
const newUrl = new URL(redirectURL);
newUrl.searchParams.set("isMobileApp", true);
redirectURL = newUrl.toString();
}
return passport.authenticate("github", {
scope: ["user:email"],
state: redirectURL,
})(req, res, next);
};
/**
* Fetches the user info from GitHub and authenticates User
*
* @param req {Object} - Express request object
* @param res {Object} - Express response object
* @param next {Function} - Express middleware function
*/
const githubAuthCallback = (req, res, next) => {
let userData;
let isMobileApp = false;
const rdsUiUrl = new URL(config.get("services.rdsUi.baseUrl"));
let authRedirectionUrl = rdsUiUrl;
if ("state" in req.query) {
try {
const redirectUrl = new URL(req.query.state);
if (redirectUrl.searchParams.get("isMobileApp") === "true") {
isMobileApp = true;
redirectUrl.searchParams.delete("isMobileApp");
}
if (`.${redirectUrl.hostname}`.endsWith(`.${rdsUiUrl.hostname}`)) {
// Matching *.realdevsquad.com
authRedirectionUrl = redirectUrl;
} else {
logger.error(`Malicious redirect URL provided URL: ${redirectUrl}, Will redirect to RDS`);
}
} catch (error) {
logger.error("Invalid redirect URL provided", error);
}
}
try {
return passport.authenticate("github", { session: false }, async (err, accessToken, user) => {
if (err) {
logger.error(err);
return res.boom.unauthorized("User cannot be authenticated");
}
userData = {
github_id: user.username,
github_display_name: user.displayName,
github_created_at: Number(new Date(user._json.created_at).getTime()),
github_user_id: user.id,
created_at: Date.now(),
updated_at: Date.now(),
};
const { userId, incompleteUserDetails } = await users.addOrUpdate(userData);
const token = authService.generateAuthToken({ userId });
// respond with a cookie
res.cookie(config.get("userToken.cookieName"), token, {
domain: rdsUiUrl.hostname,
expires: new Date(Date.now() + config.get("userToken.ttl") * 1000),
httpOnly: true,
secure: true,
sameSite: "lax",
});
if (incompleteUserDetails) authRedirectionUrl = "https://my.realdevsquad.com/new-signup";
if (isMobileApp) {
const newUrl = new URL(authRedirectionUrl);
newUrl.searchParams.set("token", token);
authRedirectionUrl = newUrl.toString();
}
return res.redirect(authRedirectionUrl);
})(req, res, next);
} catch (err) {
logger.error(err);
return res.boom.unauthorized("User cannot be authenticated");
}
};
const signout = (req, res) => {
const cookieName = config.get("userToken.cookieName");
const rdsUiUrl = new URL(config.get("services.rdsUi.baseUrl"));
res.clearCookie(cookieName, {
domain: rdsUiUrl.hostname,
httpOnly: true,
secure: true,
sameSite: "lax",
});
return res.json({
message: "Signout successful",
});
};
/**
* Stores user-device data inside the DB for mobile auth
*
* @param req {Object} - Express request object
* @param res {Object} - Express response object
*/
const storeUserDeviceInfo = async (req, res) => {
try {
const userJson = {
user_id: req.body.user_id,
device_info: req.body.device_info,
device_id: req.body.device_id,
authorization_status: "NOT_INIT",
};
const userInfoData = await dataAccess.retrieveUsers({ id: userJson.user_id });
if (!userInfoData.userExists) {
return res.boom.notFound(USER_DOES_NOT_EXIST_ERROR);
}
const userInfo = await QrCodeAuthModel.storeUserDeviceInfo(userJson);
return res.status(201).json({
...userInfo,
message: DATA_ADDED_SUCCESSFULLY,
});
} catch (err) {
logger.error(`Error while storing user device info : ${err}`);
return res.boom.badImplementation(SOMETHING_WENT_WRONG);
}
};
const updateAuthStatus = async (req, res) => {
try {
const userId = req.userData.id;
const authStatus = req.params.authorization_status;
let token;
if (authStatus === "AUTHORIZED") {
token = authService.generateAuthToken({ userId });
}
const result = await QrCodeAuthModel.updateStatus(userId, authStatus, token);
if (!result.userExists) {
return res.boom.notFound("Document not found!");
}
return res.json({
message: `Authentication document for user ${userId} updated successfully`,
data: { ...result.data },
});
} catch (error) {
logger.error(`Error while fetching user: ${error}`);
return res.boom.badImplementation(SOMETHING_WENT_WRONG);
}
};
const fetchUserDeviceInfo = async (req, res) => {
try {
const { device_id: deviceId } = req.query;
const userDeviceInfoData = await QrCodeAuthModel.retrieveUserDeviceInfo({ deviceId });
if (!userDeviceInfoData.userExists) {
return res.boom.notFound(`User with id ${deviceId} does not exist.`);
}
return res.json({
message: "Authentication document retrieved successfully.",
data: { ...userDeviceInfoData.data },
});
} catch (error) {
logger.error(`Error while fetching user: ${error}`);
return res.boom.badImplementation(SOMETHING_WENT_WRONG);
}
};
const fetchDeviceDetails = async (req, res) => {
try {
const userId = req.userData.id;
const userDeviceInfoData = await QrCodeAuthModel.retrieveUserDeviceInfo({ userId });
if (!userDeviceInfoData.userExists) {
return res.boom.notFound(`User with id ${userId} does not exist.`);
}
return res.json({
message: "Authentication document Exists",
data: { device_info: userDeviceInfoData.data?.device_info },
});
} catch (error) {
logger.error(`Error while fetching user device info: ${error}`);
return res.boom.badImplementation(SOMETHING_WENT_WRONG);
}
};
module.exports = {
githubAuthLogin,
githubAuthCallback,
signout,
storeUserDeviceInfo,
updateAuthStatus,
fetchUserDeviceInfo,
fetchDeviceDetails,
};