-
Notifications
You must be signed in to change notification settings - Fork 0
/
next-auth.functions.js
242 lines (231 loc) · 8.12 KB
/
next-auth.functions.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/**
* next-auth.functions.js Example
*
* This file defines functions NextAuth to look up, add and update users.
*
* It returns a Promise with the functions matching these signatures:
*
* {
* find: ({
* id,
* email,
* emailToken,
* provider,
* poviderToken
* } = {}) => {},
* update: (user) => {},
* insert: (user) => {},
* remove: (id) => {},
* serialize: (user) => {},
* deserialize: (id) => {}
* }
*
* Each function returns Promise.resolve() - or Promise.reject() on error.
*
* This specific example supports both MongoDB and NeDB, but can be refactored
* to work with any database.
*
* Environment variables for this example:
*
* MONGO_URI=mongodb://localhost:27017/my-database
* EMAIL_SERVER=smtp.gmail.com
* EMAIL_PORT=465
* EMAIL_PASSWORD=p4ssw0rd
*
* If you wish, you can put these in a `.env` to seperate your environment
* specific configuration from your code.
*/
// Load environment variables from a .env file if one exists
require('dotenv').load();
// This config file uses MongoDB for User accounts, as well as session storage.
// This config includes options for NeDB, which it defaults to if no DB URI
// is specified. NeDB is an in-memory only database intended here for testing.
const { MongoClient } = require('mongodb');
const NeDB = require('nedb');
const MongoObjectId = (process.env.MONGO_URI) ? require('mongodb').ObjectId : id => id;
// Use Node Mailer for email sign in
const nodemailer = require('nodemailer');
const nodemailerSmtpTransport = require('nodemailer-smtp-transport');
const nodemailerDirectTransport = require('nodemailer-direct-transport');
// Send email direct from localhost if no mail server configured
let nodemailerTransport = nodemailerDirectTransport();
if (process.env.EMAIL_SERVER && process.env.EMAIL_USERNAME && process.env.EMAIL_PASSWORD) {
nodemailerTransport = nodemailerSmtpTransport({
host: process.env.EMAIL_SERVER,
port: process.env.EMAIL_PORT || 25,
secure: true,
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD,
},
});
}
module.exports = () => new Promise((resolve, reject) => {
if (process.env.MONGO_URI) {
// Connect to MongoDB Database and return user connection
MongoClient.connect(process.env.MONGO_URI, (err, mongoClient) => {
if (err) {
return reject(err);
}
const dbName = process.env.MONGO_URI.split('/').pop().split('?').shift();
const db = mongoClient.db(dbName);
return resolve(db.collection('users'));
});
} else {
// If no MongoDB URI string specified, use NeDB, an in-memory work-a-like.
// NeDB is not persistant and is intended for testing only.
const collection = new NeDB({ autoload: true });
collection.loadDatabase((err) => {
if (err) {
reject(err);
}
resolve(collection);
});
}
})
.then(usersCollection => Promise.resolve({
// If a user is not found find() should return null (with no error).
find: ({
id,
email,
emailToken,
provider,
} = {}) => {
let query = {};
// Find needs to support looking up a user by ID, Email, Email Token,
// and Provider Name + Users ID for that Provider
if (id) {
query = { _id: MongoObjectId(id) };
} else if (email) {
query = { email };
} else if (emailToken) {
query = { emailToken };
} else if (provider) {
query = { [`${provider.name}.id`]: provider.id };
}
return new Promise((resolve, reject) => {
usersCollection.findOne(query, (err, user) => {
if (err) {
return reject(err);
}
return resolve(user);
});
});
},
// The user parameter contains a basic user object to be added to the DB.
// The oAuthProfile parameter is passed when signing in via oAuth.
//
// The optional oAuthProfile parameter contains all properties associated
// with the users account on the oAuth service they are signing in with.
//
// You can use this to capture profile.avatar, profile.location, etc.
insert: user => new Promise((resolve, reject) => {
usersCollection.insert(user, (err, response) => {
if (err) {
return reject(err);
}
// Mongo Client automatically adds an id to an inserted object, but
// if using a work-a-like we may need to add it from the response.
/* eslint-disable no-underscore-dangle */
if (!user._id && response._id) {
user._id = response._id; // eslint-disable-line no-param-reassign
}
/* eslint-enable */
return resolve(user);
});
}),
// The user parameter contains a basic user object to be added to the DB.
// The oAuthProfile parameter is passed when signing in via oAuth.
//
// The optional oAuthProfile parameter contains all properties associated
// with the users account on the oAuth service they are signing in with.
//
// You can use this to capture profile.avatar, profile.location, etc.
update: user => new Promise((resolve, reject) => {
// eslint-disable-next-line no-underscore-dangle
usersCollection.update({ _id: MongoObjectId(user._id) }, user, {}, (err) => {
if (err) {
return reject(err);
}
return resolve(user);
});
}),
// The remove parameter is passed the ID of a user account to delete.
//
// This method is not used in the current version of next-auth but will
// be in a future release, to provide an endpoint for account deletion.
remove: id => new Promise((resolve, reject) => {
usersCollection.remove({ _id: MongoObjectId(id) }, (err) => {
if (err) {
return reject(err);
}
return resolve(true);
});
}),
// Seralize turns the value of the ID key from a User object
serialize: (user) => {
// Supports serialization from Mongo Object *and* deserialize() object
if (user.id) {
// Handle responses from deserialize()
return Promise.resolve(user.id);
}
// eslint-disable-next-line no-underscore-dangle
if (user._id) {
// Handle responses from find(), insert(), update()
return Promise.resolve(user._id); // eslint-disable-line no-underscore-dangle
}
return Promise.reject(new Error('Unable to serialise user'));
},
// Deseralize turns a User ID into a normalized User object that is
// exported to clients. It should not return private/sensitive fields,
// only fields you want to expose via the user interface.
deserialize: id => new Promise((resolve, reject) => {
usersCollection.findOne({ _id: MongoObjectId(id) }, (err, user) => {
if (err) {
return reject(err);
}
// If user not found (e.g. account deleted) return null object
if (!user) {
return resolve(null);
}
return resolve({
// eslint-disable-next-line no-underscore-dangle
id: user._id,
babbler: user.babbler,
rating: user.rating,
avatar: user.avatar,
bio: user.bio,
name: user.name,
email: user.email,
emailVerified: user.emailVerified,
admin: user.admin || false,
});
});
}),
// Define method for sending links for signing in over email.
sendSignInEmail: ({
email = null,
url = null,
} = {}) => {
nodemailer
.createTransport(nodemailerTransport)
.sendMail({
to: email,
from: process.env.EMAIL_FROM,
subject: 'Sign in link',
text: `Use the link below to sign in:\n\n${url}\n\n`,
html: `<p>Use the link below to sign in:</p><p>${url}</p>`,
}, (err) => {
if (err) {
// eslint-disable-next-line no-console
console.error(`Error sending email to ${email}`, err);
}
});
if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line no-console
console.log(`Generated sign in link ${url} for ${email}`);
}
},
}));