This repository has been archived by the owner on Dec 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
index.js
207 lines (207 loc) · 9.11 KB
/
index.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
"use strict";
const url = require("url");
const path = require("path");
const crypto = require("crypto");
const builder = require("botbuilder");
const passport = require("passport");
const dialogs_1 = require("./dialogs");
exports.AuthDialog = dialogs_1.AuthDialog;
const resumption_1 = require("./resumption");
exports.CookieResumption = resumption_1.CookieResumption;
const consts_1 = require("./consts");
const defaultOptions = {
basePath: "botauth",
resumption: null,
secret: null,
baseUrl: null,
session: false
};
class BotAuthenticator {
constructor(server, bot, options) {
this.server = server;
this.bot = bot;
this.options = options;
if (!bot) {
throw new Error("BotAuthenticator constructor failed because 'bot' argument was null/undefined");
}
if (!server) {
throw new Error("BotAuthenticator constructor failed because 'server' argument was null/undefined");
}
this.options = Object.assign({}, defaultOptions, options);
if (!this.options.baseUrl) {
throw new Error("options.baseUrl can not be null");
}
else {
let parsedUrl = url.parse(this.options.baseUrl);
if (parsedUrl.protocol !== "https:" || !parsedUrl.slashes || !parsedUrl.hostname) {
throw new Error("options.baseUrl must be a valid url and start with 'https://'.");
}
}
if (!this.options.secret) {
throw new Error("options.secret can not be null");
}
if (!this.options.resumption) {
this.options.resumption = new resumption_1.CookieResumption(15 * 60, this.options.secret);
}
this.server.use(passport.initialize());
if (this.options.session) {
this.server.use(passport.session());
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((userId, done) => {
done(null, userId);
});
}
this.server.get(`/${this.options.basePath}/:providerId`, this.options.resumption.persistHandler(), this.passport_redirect());
this.server.get(`/${this.options.basePath}/:providerId/callback`, this.passport_callback(), this.options.resumption.restoreHandler(), this.credential_callback());
this.server.post(`/${this.options.basePath}/:providerId/callback`, this.passport_callback(), this.options.resumption.restoreHandler(), this.credential_callback());
this.bot.set("persistConversationData", true);
this.bot.set("persistUserData", true);
let lib = new builder.Library(consts_1.DIALOG_LIBRARY);
lib.localePath(path.join(__dirname, "../locale/"));
lib.dialog(consts_1.DIALOG_ID, new dialogs_1.AuthDialog({ secret: this.options.secret }));
this.bot.library(lib);
}
provider(name, factory) {
let s = factory({
callbackURL: this.callbackUrl(name)
});
if (!s) {
throw new Error("The 'factory' method passed to BotAuthenticator.provider must return an instance of an authentication Strategy.");
}
passport.use(name, s);
return this;
}
authenticate(providerId, options) {
let authSteps = [
(session, args, skip) => {
let user = this.profile(session, providerId);
if (user) {
skip({ response: (args || {}).response, resumed: builder.ResumeReason.forward });
}
else {
let cxt = new Buffer(JSON.stringify(session.message.address)).toString("base64");
session.beginDialog(consts_1.DIALOG_FULLNAME, {
providerId: providerId,
buttonUrl: this.authUrl(providerId, cxt),
originalArgs: args.response
});
}
},
(session, args, skip) => {
if (args) {
if (args.resumed === builder.ResumeReason.completed || args.resumed === builder.ResumeReason.forward) {
skip({ response: args.response, resumed: builder.ResumeReason.forward });
return;
}
else if (args.resumed === builder.ResumeReason.back || args.resumed === builder.ResumeReason.canceled || args.resumed === builder.ResumeReason.notCompleted) {
session.endDialogWithResult({ response: false, resumed: args.resumed });
return;
}
}
}
];
return authSteps;
}
profile(session, providerId) {
if (session && session.userData && session.userData.botauth && session.userData.botauth.user && session.userData.botauth.user.hasOwnProperty(providerId)) {
let encryptedProfile = session.userData.botauth.user[providerId];
let decipher = crypto.createDecipher("aes192", this.options.secret);
let json = decipher.update(encryptedProfile, "base64", "utf8") + decipher.final("utf8");
return JSON.parse(json);
}
else {
return null;
}
}
logout(session, providerId) {
if (session && session.userData && session.userData.botauth && session.userData.botauth.user && session.userData.botauth.user.hasOwnProperty(providerId)) {
delete session.userData.botauth.user[providerId];
session.save();
}
}
callbackUrl(providerName) {
return `${this.options.baseUrl}/${this.options.basePath}/${providerName}/callback`;
}
authUrl(providerName, state) {
return `${this.options.baseUrl}/${this.options.basePath}/${providerName}?state=${encodeURIComponent(state)}`;
}
passport_redirect() {
let session = this.options.session;
return (req, res, next) => {
let providerId = req.params.providerId;
return passport.authenticate(providerId, { session: session })(req, res, next);
};
}
passport_callback() {
let session = this.options.session;
return (req, res, next) => {
let providerId = req.params.providerId;
return passport.authenticate(providerId, { session: session })(req, res, next);
};
}
credential_callback() {
let bot = this.bot;
let options = this.options;
return (req, res, next) => {
let providerId = req.params.providerId;
let user = req.user;
if (!user) {
res.status(403);
res.send("verify function yielded no user");
res.end();
return;
}
let addr = JSON.parse(new Buffer(req.locals.resumption, "base64").toString("utf8"));
if (!addr) {
res.status(403);
res.send("resumption token has expired or is invalid");
res.end();
return next();
}
let magic = crypto.randomBytes(3).toString("hex");
let response = {
providerId: providerId,
user: user,
timestamp: new Date()
};
let cipher = crypto.createCipher("aes192", magic + options.secret);
let encryptedResponse = cipher.update(JSON.stringify(response), "utf8", "base64") + cipher.final("base64");
let botStorage = bot.get("storage");
let botContext = { persistConversationData: true, persistUserData: false, address: addr, conversationId: addr.conversation.id };
botStorage.getData(botContext, (err, data) => {
if (err) {
console.error(err);
res.status(403);
res.send("failed to get bot state");
res.end();
return;
}
let magicKey = crypto.createHmac("sha256", options.secret).update(magic).digest("hex");
data.conversationData.botauth = data.conversationData.botauth || {};
data.conversationData.botauth.responses = data.conversationData.botauth.responses || {};
data.conversationData.botauth.responses[magicKey] = encryptedResponse;
botStorage.saveData(botContext, data, (err) => {
if (err) {
res.status(403);
res.send("saving credential failed");
res.end();
}
else {
if (this.options.successRedirect) {
res.status(302);
res.header("Location", `${options.successRedirect}#${encodeURIComponent(magic)}`);
res.send("redirecting...");
res.end();
}
else {
res.end(`You're almost done. To complete your authentication, put "${magic}" in our chat.`);
}
}
});
});
};
}
}
exports.BotAuthenticator = BotAuthenticator;