-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathAuth.ts
More file actions
276 lines (250 loc) · 9.14 KB
/
Copy pathAuth.ts
File metadata and controls
276 lines (250 loc) · 9.14 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
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
270
271
272
273
274
275
276
import CommandError from './CommandError';
import Logger from './Logger';
import inquirer from 'inquirer';
import ConfigStore, { CONFIG_KEYS } from './Config';
import open from 'open';
import express from 'express';
var cors = require('cors');
const port = 7071;
import { getLocalBaseUrl } from '../helper/serve.utils';
import Debug from './Debug';
import Env from './Env';
const SERVER_TIMER = 1000 * 60 * 2; // 2 min
import { OutputFormatter, successBox } from '../helper/formatter';
import OrganizationService from './api/services/organization.service';
import { getOrganizationDisplayName } from '../helper/utils';
import chalk from 'chalk';
function checkTokenExpired(auth_token) {
const { expiry_time } = auth_token;
const currentTimestamp = Math.floor(Date.now() / 1000);
if (currentTimestamp > expiry_time) {
return true;
} else {
return false;
}
}
export const getApp = async () => {
const app = express();
app.use(cors());
app.use(express.json());
app.post('/token', async (req, res) => {
try {
if (Auth.wantToChangeOrganization)
ConfigStore.delete(CONFIG_KEYS.AUTH_TOKEN);
const expiryTimestamp =
Math.floor(Date.now() / 1000) + req.body.auth_token.expires_in;
req.body.auth_token.expiry_time = expiryTimestamp;
if(Auth.newDomainToUpdate){
if(Auth.newDomainToUpdate === 'api.fynd.com'){
Env.setEnv(Auth.newDomainToUpdate);
}
else{
await Env.setNewEnvs(Auth.newDomainToUpdate);
}
}
ConfigStore.set(CONFIG_KEYS.AUTH_TOKEN, req.body.auth_token);
ConfigStore.set(CONFIG_KEYS.ORGANIZATION, req.body.organization);
const organization_detail =
await OrganizationService.getOrganizationDetails();
ConfigStore.set(
CONFIG_KEYS.ORGANIZATION_DETAIL,
organization_detail.data,
);
Auth.stopSever();
Logger.info(
`Logged in successfully in organization ${getOrganizationDisplayName()}`,
);
res.status(200).json({ message: 'success' });
} catch (err) {
Debug(err);
Auth.stopSever();
res.status(500).json({ message: 'failed' });
}
});
return { app };
};
function startTimer(){
Debug("Server timer starts")
Auth.timer_id = setTimeout(() => {
Auth.stopSever(() => {
console.log(chalk.red(`Timeout: Please run ${chalk.blue('fdk login')} command again.`));
})
}, SERVER_TIMER)
}
function resetTimer(){
if (Auth.timer_id) {
Debug("Server timer stoped")
clearTimeout(Auth.timer_id)
Auth.timer_id = null;
}
}
export const startServer = async () => {
if (Auth.server) return Auth.server;
const { app } = await getApp();
const serverIn = require('http').createServer(app);
// handle errors thrown while start listening
serverIn.on('error', (error) => {
Debug(error);
if (error.code === 'EADDRINUSE') {
console.error(chalk.red(`Port ${port} is already in use.`));
} else {
console.error(chalk.red('An unexpected error occurred:'), error);
}
});
Auth.server = serverIn.listen(port);
// resolve promise only if server starts listening
// we will open partner panel only if server is listening
return new Promise(resolve => {
serverIn.on('listening', () => {
Debug(`Server started listening on ${port}`);
resolve(Auth.server);
});
}).then(server => {
// once server start listening, start server timer
startTimer();
return server
})
};
export default class Auth {
static server = null;
static timer_id;
static wantToChangeOrganization = false;
static newDomainToUpdate = null;
constructor() {}
public static async login(options) {
let env: string;
if(options.host){
env = await Env.verifyAndSanitizeEnvValue(options.host);
}
else{
env = 'api.fynd.com';
}
let current_env = Env.getEnvValue();
if(current_env !== env){
// update new domain after login
Auth.newDomainToUpdate = env;
// Logout user from current domain
Auth.updateConfigStoreForLogout();
}
const isLoggedIn = Auth.isAlreadyLoggedIn();
if (isLoggedIn) {
Logger.info(
`Current logged in organization: ${getOrganizationDisplayName()}`,
);
const questions = [
{
type: 'list',
name: 'confirmChangeOrg',
message:
'You are already logged In. Do you wish to change the organization?',
choices: ['Yes', 'No'],
},
];
await inquirer.prompt(questions).then(async (answers) => {
if (answers.confirmChangeOrg === 'No') {
Auth.wantToChangeOrganization = false;
return;
} else {
Auth.wantToChangeOrganization = true;
await startServer();
}
});
} else
await startServer();
try {
let domain = null;
let partnerDomain = env.replace('api', 'partners');
domain = `https://${partnerDomain}`;
try {
if (Auth.wantToChangeOrganization || !isLoggedIn) {
await open(
`${domain}/organizations/?fdk-cli=true&callback=${encodeURIComponent(
`${getLocalBaseUrl()}:${port}`,
)}`,
);
console.log(
`Open link on browser: ${OutputFormatter.link(`${domain}/organizations/?fdk-cli=true&callback=${encodeURIComponent(
`${getLocalBaseUrl()}:${port}`,
)}`)}`,
);
}
} catch (err) {
console.log(
`Open link on browser: ${OutputFormatter.link(`${domain}/organizations/?fdk-cli=true&callback=${encodeURIComponent(
`${getLocalBaseUrl()}:${port}`,
)}`)}`,
);
}
} catch (error) {
throw new CommandError(error.message, error.code);
}
}
public static async logout(options) {
try {
if(!Auth.isAlreadyLoggedIn()){
Logger.info('No active user found. You are already logged out.');
return;
}
let shouldLogout = options.skipConfirm;
if(!shouldLogout){
const questions = [
{
type: 'list',
name: 'confirmLogout',
message: 'Are you sure you want to logout? [Yes/No]',
choices: ['Yes', 'No'],
},
];
const answer = await inquirer.prompt(questions)
shouldLogout = answer.confirmLogout === 'Yes';
}
if(shouldLogout){
Auth.updateConfigStoreForLogout();
Logger.info(`User logged out successfully.`);
}
} catch (error) {
Debug(`An error occurred during logout: ${error}`);
throw new CommandError(error.message, error.code);
}
}
private static updateConfigStoreForLogout(){
const currentEnv = ConfigStore.get(
CONFIG_KEYS.CURRENT_ENV_VALUE,
);
const extras = ConfigStore.get(CONFIG_KEYS.EXTRAS);
ConfigStore.clear();
ConfigStore.set(CONFIG_KEYS.CURRENT_ENV_VALUE, currentEnv);
ConfigStore.set(CONFIG_KEYS.EXTRAS, extras);
}
public static getUserInfo() {
try {
const { current_user: user } = ConfigStore.get(
CONFIG_KEYS.AUTH_TOKEN,
);
const activeEmail =
user.emails.find((e) => e.active && e.primary)?.email ||
'Primary email missing';
const text = `Name: ${user.first_name} ${
user.last_name
}\nEmail: ${activeEmail}\nOrganization: ${getOrganizationDisplayName()}`;
Logger.info(successBox({ text }));
} catch (error) {
throw new CommandError(error.message, error.code);
}
}
private static isAlreadyLoggedIn = () => {
const auth_token = ConfigStore.get(CONFIG_KEYS.AUTH_TOKEN);
if (auth_token && auth_token.access_token) {
const isTokenExpired = checkTokenExpired(auth_token);
if (!isTokenExpired) return true;
else return false;
} else return false;
};
static stopSever = async (cb = null) => {
resetTimer();
Auth.server?.close?.(() => {
Debug("Server closed");
cb?.();
});
};
}