1 | import { IncomingMessage } from "http";
|
2 |
|
3 | declare global {
|
4 | namespace Express {
|
5 | // eslint-disable-next-line @typescript-eslint/no-empty-interface
|
6 | interface AuthInfo {}
|
7 | // eslint-disable-next-line @typescript-eslint/no-empty-interface
|
8 | interface User {}
|
9 |
|
10 | interface Request {
|
11 | authInfo?: AuthInfo | undefined;
|
12 | user?: User | undefined;
|
13 |
|
14 | // These declarations are merged into express's Request type
|
15 | /**
|
16 | * Initiate a login session for `user`.
|
17 | *
|
18 | * Options:
|
19 | * - `session` Save login state in session, defaults to `true`.
|
20 | *
|
21 | * Examples:
|
22 | *
|
23 | * req.logIn(user, { session: false });
|
24 | *
|
25 | * req.logIn(user, function(err) {
|
26 | * if (err) { throw err; }
|
27 | * // session saved
|
28 | * });
|
29 | */
|
30 | login(user: User, done: (err: any) => void): void;
|
31 | login(user: User, options: passport.LogInOptions, done: (err: any) => void): void;
|
32 | /**
|
33 | * Initiate a login session for `user`.
|
34 | *
|
35 | * Options:
|
36 | * - `session` Save login state in session, defaults to `true`.
|
37 | *
|
38 | * Examples:
|
39 | *
|
40 | * req.logIn(user, { session: false });
|
41 | *
|
42 | * req.logIn(user, function(err) {
|
43 | * if (err) { throw err; }
|
44 | * // session saved
|
45 | * });
|
46 | */
|
47 | logIn(user: User, done: (err: any) => void): void;
|
48 | logIn(user: User, options: passport.LogInOptions, done: (err: any) => void): void;
|
49 |
|
50 | /**
|
51 | * Terminate an existing login session.
|
52 | */
|
53 | logout(options: passport.LogOutOptions, done: (err: any) => void): void;
|
54 | logout(done: (err: any) => void): void;
|
55 | /**
|
56 | * Terminate an existing login session.
|
57 | */
|
58 | logOut(options: passport.LogOutOptions, done: (err: any) => void): void;
|
59 | logOut(done: (err: any) => void): void;
|
60 |
|
61 | /**
|
62 | * Test if request is authenticated.
|
63 | */
|
64 | isAuthenticated(): this is AuthenticatedRequest;
|
65 | /**
|
66 | * Test if request is unauthenticated.
|
67 | */
|
68 | isUnauthenticated(): this is UnauthenticatedRequest;
|
69 | }
|
70 |
|
71 | interface AuthenticatedRequest extends Request {
|
72 | user: User;
|
73 | }
|
74 |
|
75 | interface UnauthenticatedRequest extends Request {
|
76 | user?: undefined;
|
77 | }
|
78 | }
|
79 | }
|
80 |
|
81 | import express = require("express");
|
82 |
|
83 | declare namespace passport {
|
84 | type DoneCallback = (err: any, user?: Express.User | false | null) => void;
|
85 | type DeserializeUserFunction = (serializedUser: unknown, req: express.Request, done: DoneCallback) => void;
|
86 | /**
|
87 | * An optional callback supplied to allow the application to override
|
88 | * the default manner in which authentication attempts are handled. The
|
89 | * callback has the following signature, where `user` will be set to the
|
90 | * authenticated user on a successful authentication attempt, or `false`
|
91 | * otherwise. An optional `info` argument will be passed, containing additional
|
92 | * details provided by the strategy's verify callback - this could be information about
|
93 | * a successful authentication or a challenge message for a failed authentication.
|
94 | * An optional `status` argument will be passed when authentication fails - this could
|
95 | * be a HTTP response code for a remote authentication failure or similar.
|
96 | *
|
97 | * app.get('/protected', function(req, res, next) {
|
98 | * passport.authenticate('local', function callback(err, user, info, status) {
|
99 | * if (err) { return next(err) }
|
100 | * if (!user) { return res.redirect('/signin') }
|
101 | * res.redirect('/account');
|
102 | * })(req, res, next);
|
103 | * });
|
104 | *
|
105 | * Note that if a callback is supplied, it becomes the application's
|
106 | * responsibility to log-in the user, establish a session, and otherwise perform
|
107 | * the desired operations.
|
108 | */
|
109 | type AuthenticateCallback = (
|
110 | err: any,
|
111 | user?: Express.User | false | null,
|
112 | info?: object | string | Array<string | undefined>,
|
113 | status?: number | Array<number | undefined>,
|
114 | ) => any;
|
115 | type AuthorizeCallback = AuthenticateCallback;
|
116 |
|
117 | interface AuthenticateOptions {
|
118 | authInfo?: boolean | undefined;
|
119 | /**
|
120 | * Assign the object provided by the verify callback to given property.
|
121 | */
|
122 | assignProperty?: string | undefined;
|
123 | /**
|
124 | * True to flash failure messages
|
125 | * or a string to use as a flash message for failures
|
126 | * (overrides any from the strategy itself).
|
127 | */
|
128 | failureFlash?: string | boolean | undefined;
|
129 | /**
|
130 | * True to store failure message in `req.session.messages`,
|
131 | * or a string to use as override message for failure.
|
132 | */
|
133 | failureMessage?: boolean | string | undefined;
|
134 | /**
|
135 | * After failed login, redirect to given URL.
|
136 | */
|
137 | failureRedirect?: string | undefined;
|
138 | failWithError?: boolean | undefined;
|
139 | keepSessionInfo?: boolean | undefined;
|
140 | /**
|
141 | * Save login state in session, defaults to `true`.
|
142 | */
|
143 | session?: boolean | undefined;
|
144 | scope?: string | string[] | undefined;
|
145 | /**
|
146 | * True to flash success messages
|
147 | * or a string to use as a flash message for success
|
148 | * (overrides any from the strategy itself).
|
149 | */
|
150 | successFlash?: string | boolean | undefined;
|
151 | /**
|
152 | * True to store success message in `req.session.messages`,
|
153 | * or a string to use as override message for success.
|
154 | */
|
155 | successMessage?: boolean | string | undefined;
|
156 | /**
|
157 | * After successful login, redirect to given URL.
|
158 | */
|
159 | successRedirect?: string | undefined;
|
160 | successReturnToOrRedirect?: string | undefined;
|
161 | state?: string | undefined;
|
162 | /**
|
163 | * Pause the request stream before deserializing the user
|
164 | * object from the session. Defaults to `false`. Should
|
165 | * be set to `true` in cases where middleware consuming the
|
166 | * request body is configured after passport and the
|
167 | * deserializeUser method is asynchronous.
|
168 | */
|
169 | pauseStream?: boolean | undefined;
|
170 | /**
|
171 | * Determines what property on `req`
|
172 | * will be set to the authenticated user object.
|
173 | * Default `'user'`.
|
174 | */
|
175 | userProperty?: string | undefined;
|
176 | passReqToCallback?: boolean | undefined;
|
177 | /**
|
178 | * **Note:** The availability of this property depends on the passport strategy you are using.
|
179 | * If not explicitly supported by the strategy or implemented by yourself, this property will be ignored.
|
180 | */
|
181 | prompt?: string | undefined;
|
182 | }
|
183 |
|
184 | interface InitializeOptions {
|
185 | /**
|
186 | * Determines what property on `req`
|
187 | * will be set to the authenticated user object.
|
188 | * Default `'user'`.
|
189 | */
|
190 | userProperty?: string;
|
191 | /**
|
192 | * When `true`, enables a compatibility layer
|
193 | * for packages that depend on `passport@0.4.x` or earlier.
|
194 | * Default `true`.
|
195 | */
|
196 | compat?: boolean;
|
197 | }
|
198 |
|
199 | interface SessionOptions {
|
200 | /**
|
201 | * Pause the request stream before deserializing the user
|
202 | * object from the session. Defaults to `false`. Should
|
203 | * be set to `true` in cases where middleware consuming the
|
204 | * request body is configured after passport and the
|
205 | * deserializeUser method is asynchronous.
|
206 | */
|
207 | pauseStream: boolean;
|
208 | }
|
209 |
|
210 | interface SessionStrategyOptions {
|
211 | /**
|
212 | * Determines what property ("key") on
|
213 | * the session data where login session data is located.
|
214 | * The login session is stored and read from `req.session[key]`.
|
215 | * Default `'passport'`.
|
216 | */
|
217 | key: string;
|
218 | }
|
219 |
|
220 | interface LogInOptions extends LogOutOptions {
|
221 | /**
|
222 | * Save login state in session, defaults to `true`.
|
223 | */
|
224 | session: boolean;
|
225 | }
|
226 |
|
227 | interface LogOutOptions {
|
228 | keepSessionInfo?: boolean;
|
229 | }
|
230 |
|
231 | interface StrategyFailure {
|
232 | message?: string;
|
233 | [key: string]: any;
|
234 | }
|
235 |
|
236 | interface Authenticator<
|
237 | InitializeRet = express.Handler,
|
238 | AuthenticateRet = any,
|
239 | AuthorizeRet = AuthenticateRet,
|
240 | AuthorizeOptions = AuthenticateOptions,
|
241 | > {
|
242 | /**
|
243 | * Register a strategy for later use when authenticating requests. The name
|
244 | * with which the strategy is registered is passed to {@link Authenticator.authenticate `authenticate()`}.
|
245 | *
|
246 | * @example <caption>Register strategy.</caption>
|
247 | * passport.use(new GoogleStrategy(...));
|
248 | *
|
249 | * @example <caption>Register strategy and override name.</caption>
|
250 | * passport.use('password', new LocalStrategy(function(username, password, cb) {
|
251 | * // ...
|
252 | * }));
|
253 | */
|
254 | use(strategy: Strategy): this;
|
255 | use(name: string, strategy: Strategy): this;
|
256 | /**
|
257 | * Deregister a strategy that was previously registered with the given name.
|
258 | *
|
259 | * In a typical application, the necessary authentication strategies are
|
260 | * registered when initializing the app and, once registered, are always
|
261 | * available. As such, it is typically not necessary to call this function.
|
262 | *
|
263 | * @example
|
264 | * passport.unuse('acme');
|
265 | */
|
266 | unuse(name: string): this;
|
267 | /**
|
268 | * Adapt this `Authenticator` to work with a specific framework.
|
269 | *
|
270 | * By default, Passport works as {@link https://github.com/senchalabs/connect#readme Connect}-style
|
271 | * middleware, which makes it compatible with {@link https://expressjs.com/ Express}.
|
272 | * For any app built using Express, there is no need to call this function.
|
273 | */
|
274 | framework<X, Y, Z>(fw: Framework<X, Y, Z>): Authenticator<X, Y, Z>;
|
275 | /**
|
276 | * Passport initialization.
|
277 | *
|
278 | * Intializes Passport for incoming requests, allowing authentication strategies
|
279 | * to be applied.
|
280 | *
|
281 | * As of v0.6.x, it is typically no longer necessary to use this middleware. It
|
282 | * exists for compatiblity with apps built using previous versions of Passport,
|
283 | * in which this middleware was necessary.
|
284 | *
|
285 | * The primary exception to the above guidance is when using strategies that
|
286 | * depend directly on `passport@0.4.x` or earlier. These earlier versions of
|
287 | * Passport monkeypatch Node.js `http.IncomingMessage` in a way that expects
|
288 | * certain Passport-specific properties to be available. This middleware
|
289 | * provides a compatibility layer for this situation.
|
290 | *
|
291 | * Options:
|
292 | * - `userProperty` Determines what property on
|
293 | * `req` will be set to the authenticated user object.
|
294 | * Default `'user'`.
|
295 | *
|
296 | * - `compat` When `true`, enables a compatibility
|
297 | * layer for packages that depend on `passport@0.4.x` or earlier.
|
298 | * Default `true`.
|
299 | *
|
300 | * Examples:
|
301 | *
|
302 | * app.use(passport.initialize());
|
303 | *
|
304 | * If sessions are being utilized, applications must set up Passport with
|
305 | * functions to serialize a user into and out of a session. For example, a
|
306 | * common pattern is to serialize just the user ID into the session (due to the
|
307 | * fact that it is desirable to store the minimum amount of data in a session).
|
308 | * When a subsequent request arrives for the session, the full User object can
|
309 | * be loaded from the database by ID.
|
310 | *
|
311 | * Note that additional middleware is required to persist login state, so we
|
312 | * must use the `connect.session()` middleware _before_ `passport.initialize()`.
|
313 | *
|
314 | * If sessions are being used, this middleware must be in use by the
|
315 | * Connect/Express application for Passport to operate. If the application is
|
316 | * entirely stateless (not using sessions), this middleware is not necessary,
|
317 | * but its use will not have any adverse impact.
|
318 | *
|
319 | * Examples:
|
320 | *
|
321 | * app.use(connect.cookieParser());
|
322 | * app.use(connect.session({ secret: 'keyboard cat' }));
|
323 | * app.use(passport.initialize());
|
324 | * app.use(passport.session());
|
325 | *
|
326 | * passport.serializeUser(function(user, done) {
|
327 | * done(null, user.id);
|
328 | * });
|
329 | *
|
330 | * passport.deserializeUser(function(id, done) {
|
331 | * User.findById(id, function (err, user) {
|
332 | * done(err, user);
|
333 | * });
|
334 | * });
|
335 | */
|
336 | initialize(options?: InitializeOptions): InitializeRet;
|
337 | /**
|
338 | * Middleware that will restore login state from a session.
|
339 | *
|
340 | * Web applications typically use sessions to maintain login state between
|
341 | * requests. For example, a user will authenticate by entering credentials into
|
342 | * a form which is submitted to the server. If the credentials are valid, a
|
343 | * login session is established by setting a cookie containing a session
|
344 | * identifier in the user's web browser. The web browser will send this cookie
|
345 | * in subsequent requests to the server, allowing a session to be maintained.
|
346 | *
|
347 | * If sessions are being utilized, and a login session has been established,
|
348 | * this middleware will populate `req.user` with the current user.
|
349 | *
|
350 | * Note that sessions are not strictly required for Passport to operate.
|
351 | * However, as a general rule, most web applications will make use of sessions.
|
352 | * An exception to this rule would be an API server, which expects each HTTP
|
353 | * request to provide credentials in an Authorization header.
|
354 | *
|
355 | * Examples:
|
356 | *
|
357 | * app.use(connect.cookieParser());
|
358 | * app.use(connect.session({ secret: 'keyboard cat' }));
|
359 | * app.use(passport.initialize());
|
360 | * app.use(passport.session());
|
361 | *
|
362 | * Options:
|
363 | * - `pauseStream` Pause the request stream before deserializing the user
|
364 | * object from the session. Defaults to `false`. Should
|
365 | * be set to `true` in cases where middleware consuming the
|
366 | * request body is configured after passport and the
|
367 | * deserializeUser method is asynchronous.
|
368 | */
|
369 | session(options?: SessionOptions): AuthenticateRet;
|
370 |
|
371 | /**
|
372 | * Authenticates requests.
|
373 | *
|
374 | * Applies the `name`ed strategy (or strategies) to the incoming request, in
|
375 | * order to authenticate the request. If authentication is successful, the user
|
376 | * will be logged in and populated at `req.user` and a session will be
|
377 | * established by default. If authentication fails, an unauthorized response
|
378 | * will be sent.
|
379 | *
|
380 | * Options:
|
381 | * - `session` Save login state in session, defaults to `true`.
|
382 | * - `successRedirect` After successful login, redirect to given URL.
|
383 | * - `successMessage` True to store success message in
|
384 | * `req.session.messages`, or a string to use as override
|
385 | * message for success.
|
386 | * - `successFlash` True to flash success messages or a string to use as a flash
|
387 | * message for success (overrides any from the strategy itself).
|
388 | * - `failureRedirect` After failed login, redirect to given URL.
|
389 | * - `failureMessage` True to store failure message in
|
390 | * `req.session.messages`, or a string to use as override
|
391 | * message for failure.
|
392 | * - `failureFlash` True to flash failure messages or a string to use as a flash
|
393 | * message for failures (overrides any from the strategy itself).
|
394 | * - `assignProperty` Assign the object provided by the verify callback to given property.
|
395 | *
|
396 | * An optional `callback` can be supplied to allow the application to override
|
397 | * the default manner in which authentication attempts are handled. The
|
398 | * callback has the following signature, where `user` will be set to the
|
399 | * authenticated user on a successful authentication attempt, or `false`
|
400 | * otherwise. An optional `info` argument will be passed, containing additional
|
401 | * details provided by the strategy's verify callback - this could be information about
|
402 | * a successful authentication or a challenge message for a failed authentication.
|
403 | * An optional `status` argument will be passed when authentication fails - this could
|
404 | * be a HTTP response code for a remote authentication failure or similar.
|
405 | *
|
406 | * app.get('/protected', function(req, res, next) {
|
407 | * passport.authenticate('local', function(err, user, info, status) {
|
408 | * if (err) { return next(err) }
|
409 | * if (!user) { return res.redirect('/signin') }
|
410 | * res.redirect('/account');
|
411 | * })(req, res, next);
|
412 | * });
|
413 | *
|
414 | * Note that if a callback is supplied, it becomes the application's
|
415 | * responsibility to log-in the user, establish a session, and otherwise perform
|
416 | * the desired operations.
|
417 | *
|
418 | * Examples:
|
419 | *
|
420 | * passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' });
|
421 | *
|
422 | * passport.authenticate('basic', { session: false });
|
423 | *
|
424 | * passport.authenticate('twitter');
|
425 | */
|
426 | authenticate(
|
427 | strategy: string | string[] | Strategy,
|
428 | callback?: AuthenticateCallback | ((...args: any[]) => any),
|
429 | ): AuthenticateRet;
|
430 | authenticate(
|
431 | strategy: string | string[] | Strategy,
|
432 | options: AuthenticateOptions,
|
433 | callback?: AuthenticateCallback | ((...args: any[]) => any),
|
434 | ): AuthenticateRet;
|
435 | /**
|
436 | * Create third-party service authorization middleware.
|
437 | *
|
438 | * Returns middleware that will authorize a connection to a third-party service.
|
439 | *
|
440 | * This middleware is identical to using {@link Authenticator.authenticate `authenticate()`}
|
441 | * middleware with the `assignProperty` option set to `'account'`. This is
|
442 | * useful when a user is already authenticated (for example, using a username
|
443 | * and password) and they want to connect their account with a third-party
|
444 | * service.
|
445 | *
|
446 | * In this scenario, the user's third-party account will be set at
|
447 | * `req.account`, and the existing `req.user` and login session data will be
|
448 | * be left unmodified. A route handler can then link the third-party account to
|
449 | * the existing local account.
|
450 | *
|
451 | * All arguments to this function behave identically to those accepted by
|
452 | * {@link Authenticator.authenticate `Authenticator.authenticate`}.
|
453 | *
|
454 | * @example
|
455 | * app.get('/oauth/callback/twitter', passport.authorize('twitter'));
|
456 | */
|
457 | authorize(strategy: string | string[], callback?: AuthorizeCallback | ((...args: any[]) => any)): AuthorizeRet;
|
458 | authorize(
|
459 | strategy: string | string[],
|
460 | options: AuthorizeOptions,
|
461 | callback?: AuthorizeCallback | ((...args: any[]) => any),
|
462 | ): AuthorizeRet;
|
463 | /**
|
464 | * Registers a function used to serialize user objects into the session.
|
465 | *
|
466 | * Examples:
|
467 | *
|
468 | * passport.serializeUser(function(user, done) {
|
469 | * done(null, user.id);
|
470 | * });
|
471 | */
|
472 | serializeUser<TID>(fn: (user: Express.User, done: (err: any, id?: TID) => void) => void): void;
|
473 | /**
|
474 | * Registers a function used to serialize user objects into the session.
|
475 | *
|
476 | * Examples:
|
477 | *
|
478 | * passport.serializeUser(function(user, done) {
|
479 | * done(null, user.id);
|
480 | * });
|
481 | */
|
482 | serializeUser<TID, TR extends IncomingMessage = express.Request>(
|
483 | fn: (req: TR, user: Express.User, done: (err: any, id?: TID) => void) => void,
|
484 | ): void;
|
485 | /**
|
486 | * Private implementation that traverses the chain of serializers,
|
487 | * attempting to serialize a user.
|
488 | */
|
489 | serializeUser<User extends Express.User = Express.User, Request extends IncomingMessage = express.Request>(
|
490 | user: User,
|
491 | req: Request,
|
492 | done: (err: any, serializedUser?: number | NonNullable<unknown>) => any,
|
493 | ): void;
|
494 | /**
|
495 | * Private implementation that traverses the chain of serializers,
|
496 | * attempting to serialize a user.
|
497 | *
|
498 | * For backwards compatibility.
|
499 | */
|
500 | serializeUser<User extends Express.User = Express.User>(
|
501 | user: User,
|
502 | done: (err: any, serializedUser?: number | NonNullable<unknown>) => any,
|
503 | ): void;
|
504 | /**
|
505 | * Registers a function used to deserialize user objects out of the session.
|
506 | *
|
507 | * Examples:
|
508 | *
|
509 | * passport.deserializeUser(function(id, done) {
|
510 | * User.findById(id, function (err, user) {
|
511 | * done(err, user);
|
512 | * });
|
513 | * });
|
514 | */
|
515 | deserializeUser<TID>(fn: (id: TID, done: (err: any, user?: Express.User | false | null) => void) => void): void;
|
516 | /**
|
517 | * Registers a function used to deserialize user objects out of the session.
|
518 | *
|
519 | * Examples:
|
520 | *
|
521 | * passport.deserializeUser(function(id, done) {
|
522 | * User.findById(id, function (err, user) {
|
523 | * done(err, user);
|
524 | * });
|
525 | * });
|
526 | */
|
527 | deserializeUser<TID, TR extends IncomingMessage = express.Request>(
|
528 | fn: (req: TR, id: TID, done: (err: any, user?: Express.User | false | null) => void) => void,
|
529 | ): void;
|
530 | /**
|
531 | * Private implementation that traverses the chain of deserializers,
|
532 | * attempting to deserialize a user.
|
533 | */
|
534 | deserializeUser<User extends Express.User = Express.User, Request extends IncomingMessage = express.Request>(
|
535 | serializedUser: NonNullable<unknown>,
|
536 | req: Request,
|
537 | done: (err: any, user?: User | false) => any,
|
538 | ): void;
|
539 | /**
|
540 | * Private implementation that traverses the chain of deserializers,
|
541 | * attempting to deserialize a user.
|
542 | *
|
543 | * For backwards compatibility.
|
544 | */
|
545 | deserializeUser<User extends Express.User = Express.User>(
|
546 | serializedUser: NonNullable<unknown>,
|
547 | done: (err: any, user?: User | false) => any,
|
548 | ): void;
|
549 | /**
|
550 | * Registers a function used to transform auth info.
|
551 | *
|
552 | * In some circumstances authorization details are contained in authentication
|
553 | * credentials or loaded as part of verification.
|
554 | *
|
555 | * For example, when using bearer tokens for API authentication, the tokens may
|
556 | * encode (either directly or indirectly in a database), details such as scope
|
557 | * of access or the client to which the token was issued.
|
558 | *
|
559 | * Such authorization details should be enforced separately from authentication.
|
560 | * Because Passport deals only with the latter, this is the responsiblity of
|
561 | * middleware or routes further along the chain. However, it is not optimal to
|
562 | * decode the same data or execute the same database query later. To avoid
|
563 | * this, Passport accepts optional `info` along with the authenticated `user`
|
564 | * in a strategy's `success()` action. This info is set at `req.authInfo`,
|
565 | * where said later middlware or routes can access it.
|
566 | *
|
567 | * Optionally, applications can register transforms to proccess this info,
|
568 | * which take effect prior to `req.authInfo` being set. This is useful, for
|
569 | * example, when the info contains a client ID. The transform can load the
|
570 | * client from the database and include the instance in the transformed info,
|
571 | * allowing the full set of client properties to be convieniently accessed.
|
572 | *
|
573 | * If no transforms are registered, `info` supplied by the strategy will be left
|
574 | * unmodified.
|
575 | *
|
576 | * Examples:
|
577 | *
|
578 | * passport.transformAuthInfo(function(info, done) {
|
579 | * Client.findById(info.clientID, function (err, client) {
|
580 | * info.client = client;
|
581 | * done(err, info);
|
582 | * });
|
583 | * });
|
584 | */
|
585 | transformAuthInfo(fn: (info: any, done: (err: any, info: any) => void) => void): void;
|
586 | /**
|
587 | * Private implementation that traverses the chain of transformers,
|
588 | * attempting to transform auth info.
|
589 | *
|
590 | * If no transformers are registered (or they all pass),
|
591 | * the default behavior is to use the un-transformed info as-is.
|
592 | */
|
593 | transformAuthInfo<InitialInfo = unknown, Request extends IncomingMessage = express.Request>(
|
594 | info: unknown,
|
595 | req: Request,
|
596 | done: (err: any, transformedAuthInfo?: InitialInfo | NonNullable<unknown>) => any,
|
597 | ): void;
|
598 | /**
|
599 | * Private implementation that traverses the chain of transformers,
|
600 | * attempting to transform auth info.
|
601 | *
|
602 | * If no transformers are registered (or they all pass),
|
603 | * the default behavior is to use the un-transformed info as-is.
|
604 | *
|
605 | * For backwards compatibility.
|
606 | */
|
607 | transformAuthInfo<InitialInfo = unknown>(
|
608 | info: unknown,
|
609 | done: (err: any, transformedAuthInfo?: InitialInfo | NonNullable<unknown>) => any,
|
610 | ): void;
|
611 | }
|
612 |
|
613 | interface PassportStatic extends Authenticator {
|
614 | /**
|
615 | * Create a new `Authenticator` object.
|
616 | */
|
617 | Authenticator: { new(): Authenticator };
|
618 | /**
|
619 | * Create a new `Authenticator` object.
|
620 | */
|
621 | Passport: PassportStatic["Authenticator"];
|
622 | /**
|
623 | * Creates an instance of `Strategy`.
|
624 | */
|
625 | Strategy: { new(): Strategy & StrategyCreatedStatic };
|
626 | strategies: {
|
627 | /**
|
628 | * Create a new `SessionStrategy` object.
|
629 | *
|
630 | * An instance of this strategy is automatically used when creating an
|
631 | * {@link Authenticator `Authenticator`}. As such, it is typically unnecessary to create an
|
632 | * instance using this constructor.
|
633 | *
|
634 | * This `Strategy` authenticates HTTP requests based on the contents
|
635 | * of session data.
|
636 | *
|
637 | * The login session must have been previously initiated, typically upon the
|
638 | * user interactively logging in using a HTML form. During session initiation,
|
639 | * the logged-in user's information is persisted to the session so that it can
|
640 | * be restored on subsequent requests.
|
641 | *
|
642 | * Note that this strategy merely restores the authentication state from the
|
643 | * session, it does not authenticate the session itself. Authenticating the
|
644 | * underlying session is assumed to have been done by the middleware
|
645 | * implementing session support. This is typically accomplished by setting a
|
646 | * signed cookie, and verifying the signature of that cookie on incoming
|
647 | * requests.
|
648 | *
|
649 | * In {@link https://expressjs.com/ Express}-based apps, session support is
|
650 | * commonly provided by {@link https://github.com/expressjs/session `express-session`}
|
651 | * or {@link https://github.com/expressjs/cookie-session `cookie-session`}.
|
652 | *
|
653 | * Options:
|
654 | *
|
655 | * - `key` Determines what property ("key") on
|
656 | * the session data where login session data is located. The login
|
657 | * session is stored and read from `req.session[key]`.
|
658 | * Default `'passport'`.
|
659 | */
|
660 | SessionStrategy: {
|
661 | new(deserializeUser: DeserializeUserFunction): SessionStrategy;
|
662 | new(options: SessionStrategyOptions, deserializeUser: DeserializeUserFunction): SessionStrategy;
|
663 | };
|
664 | };
|
665 | }
|
666 |
|
667 | interface Strategy {
|
668 | name?: string | undefined;
|
669 | /**
|
670 | * Authenticate request.
|
671 | *
|
672 | * This function must be overridden by subclasses. In abstract form, it always
|
673 | * throws an exception.
|
674 | */
|
675 | authenticate(this: StrategyCreated<this>, req: express.Request, options?: any): any;
|
676 | }
|
677 |
|
678 | interface SessionStrategy extends Strategy {
|
679 | /**
|
680 | * The name of the strategy, set to `'session'`.
|
681 | */
|
682 | readonly name: "session";
|
683 | /**
|
684 | * Authenticate request based on current session data.
|
685 | *
|
686 | * When login session data is present in the session, that data will be used to
|
687 | * restore login state across across requests by calling the deserialize user
|
688 | * function.
|
689 | *
|
690 | * If login session data is not present, the request will be passed to the next
|
691 | * middleware, rather than failing authentication - which is the behavior of
|
692 | * most other strategies. This deviation allows session authentication to be
|
693 | * performed at the application-level, rather than the individual route level,
|
694 | * while allowing both authenticated and unauthenticated requests and rendering
|
695 | * responses accordingly. Routes that require authentication will need to guard
|
696 | * that condition.
|
697 | *
|
698 | * This function is **protected**, and should _not_ be called directly. Instead,
|
699 | * use `passport.authenticate()` middleware and specify the {@link SessionStrategy.name `name`}
|
700 | * of this strategy and any options.
|
701 | *
|
702 | * Options:
|
703 | * - `pauseStream` When `true`, data events on
|
704 | * the request will be paused, and then resumed after the asynchronous
|
705 | * `deserializeUser` function has completed. This is only necessary in
|
706 | * cases where later middleware in the stack are listening for events,
|
707 | * and ensures that those events are not missed.
|
708 | * Default `false`.
|
709 | *
|
710 | * @example
|
711 | * passport.authenticate('session');
|
712 | */
|
713 | authenticate(req: IncomingMessage, options?: Pick<AuthenticateOptions, "pauseStream">): void;
|
714 | }
|
715 |
|
716 | interface StrategyCreatedStatic {
|
717 | /**
|
718 | * Authenticate `user`, with optional `info`.
|
719 | *
|
720 | * Strategies should call this function to successfully authenticate a
|
721 | * user. `user` should be an object supplied by the application after it
|
722 | * has been given an opportunity to verify credentials. `info` is an
|
723 | * optional argument containing additional user information. This is
|
724 | * useful for third-party authentication strategies to pass profile
|
725 | * details.
|
726 | */
|
727 | success(user: Express.User, info?: object): void;
|
728 | /**
|
729 | * Fail authentication, with optional `challenge` and `status`, defaulting
|
730 | * to `401`.
|
731 | *
|
732 | * Strategies should call this function to fail an authentication attempt.
|
733 | */
|
734 | fail(challenge?: StrategyFailure | string | number, status?: number): void;
|
735 | /**
|
736 | * Redirect to `url` with optional `status`, defaulting to 302.
|
737 | *
|
738 | * Strategies should call this function to redirect the user (via their
|
739 | * user agent) to a third-party website for authentication.
|
740 | */
|
741 | redirect(url: string, status?: number): void;
|
742 | /**
|
743 | * Pass without making a success or fail decision.
|
744 | *
|
745 | * Under most circumstances, Strategies should not need to call this
|
746 | * function. It exists primarily to allow previous authentication state
|
747 | * to be restored, for example from an HTTP session.
|
748 | */
|
749 | pass(): void;
|
750 | /**
|
751 | * Internal error while performing authentication.
|
752 | *
|
753 | * Strategies should call this function when an internal error occurs
|
754 | * during the process of performing authentication; for example, if the
|
755 | * user directory is not available.
|
756 | */
|
757 | error(err: any): void;
|
758 | }
|
759 |
|
760 | type StrategyCreated<T, O = T & StrategyCreatedStatic> = {
|
761 | [P in keyof O]: O[P];
|
762 | };
|
763 |
|
764 | interface Profile {
|
765 | provider: string;
|
766 | id: string;
|
767 | displayName: string;
|
768 | username?: string | undefined;
|
769 | name?:
|
770 | | {
|
771 | familyName: string;
|
772 | givenName: string;
|
773 | middleName?: string | undefined;
|
774 | }
|
775 | | undefined;
|
776 | emails?:
|
777 | | Array<{
|
778 | value: string;
|
779 | type?: string | undefined;
|
780 | }>
|
781 | | undefined;
|
782 | photos?:
|
783 | | Array<{
|
784 | value: string;
|
785 | }>
|
786 | | undefined;
|
787 | }
|
788 |
|
789 | interface Framework<InitializeRet = any, AuthenticateRet = any, AuthorizeRet = AuthenticateRet> {
|
790 | /**
|
791 | * Passport initialization.
|
792 | *
|
793 | * Intializes Passport for incoming requests, allowing authentication strategies
|
794 | * to be applied.
|
795 | *
|
796 | * If sessions are being utilized, applications must set up Passport with
|
797 | * functions to serialize a user into and out of a session. For example, a
|
798 | * common pattern is to serialize just the user ID into the session (due to the
|
799 | * fact that it is desirable to store the minimum amount of data in a session).
|
800 | * When a subsequent request arrives for the session, the full User object can
|
801 | * be loaded from the database by ID.
|
802 | *
|
803 | * Note that additional middleware is required to persist login state, so we
|
804 | * must use the `connect.session()` middleware _before_ `passport.initialize()`.
|
805 | *
|
806 | * If sessions are being used, this middleware must be in use by the
|
807 | * Connect/Express application for Passport to operate. If the application is
|
808 | * entirely stateless (not using sessions), this middleware is not necessary,
|
809 | * but its use will not have any adverse impact.
|
810 | *
|
811 | * Examples:
|
812 | *
|
813 | * app.use(connect.cookieParser());
|
814 | * app.use(connect.session({ secret: 'keyboard cat' }));
|
815 | * app.use(passport.initialize());
|
816 | * app.use(passport.session());
|
817 | *
|
818 | * passport.serializeUser(function(user, done) {
|
819 | * done(null, user.id);
|
820 | * });
|
821 | *
|
822 | * passport.deserializeUser(function(id, done) {
|
823 | * User.findById(id, function (err, user) {
|
824 | * done(err, user);
|
825 | * });
|
826 | * });
|
827 | */
|
828 | initialize(
|
829 | passport: Authenticator<InitializeRet, AuthenticateRet, AuthorizeRet>,
|
830 | options?: any,
|
831 | ): (...args: any[]) => InitializeRet;
|
832 | /**
|
833 | * Authenticates requests.
|
834 | *
|
835 | * Applies the `name`ed strategy (or strategies) to the incoming request, in
|
836 | * order to authenticate the request. If authentication is successful, the user
|
837 | * will be logged in and populated at `req.user` and a session will be
|
838 | * established by default. If authentication fails, an unauthorized response
|
839 | * will be sent.
|
840 | *
|
841 | * Options:
|
842 | * - `session` Save login state in session, defaults to `true`.
|
843 | * - `successRedirect` After successful login, redirect to given URL.
|
844 | * - `successMessage` True to store success message in
|
845 | * `req.session.messages`, or a string to use as override
|
846 | * message for success.
|
847 | * - `successFlash` True to flash success messages or a string to use as a flash
|
848 | * message for success (overrides any from the strategy itself).
|
849 | * - `failureRedirect` After failed login, redirect to given URL.
|
850 | * - `failureMessage` True to store failure message in
|
851 | * `req.session.messages`, or a string to use as override
|
852 | * message for failure.
|
853 | * - `failureFlash` True to flash failure messages or a string to use as a flash
|
854 | * message for failures (overrides any from the strategy itself).
|
855 | * - `assignProperty` Assign the object provided by the verify callback to given property.
|
856 | *
|
857 | * An optional `callback` can be supplied to allow the application to override
|
858 | * the default manner in which authentication attempts are handled. The
|
859 | * callback has the following signature, where `user` will be set to the
|
860 | * authenticated user on a successful authentication attempt, or `false`
|
861 | * otherwise. An optional `info` argument will be passed, containing additional
|
862 | * details provided by the strategy's verify callback - this could be information about
|
863 | * a successful authentication or a challenge message for a failed authentication.
|
864 | * An optional `status` argument will be passed when authentication fails - this could
|
865 | * be a HTTP response code for a remote authentication failure or similar.
|
866 | *
|
867 | * app.get('/protected', function(req, res, next) {
|
868 | * passport.authenticate('local', function(err, user, info, status) {
|
869 | * if (err) { return next(err) }
|
870 | * if (!user) { return res.redirect('/signin') }
|
871 | * res.redirect('/account');
|
872 | * })(req, res, next);
|
873 | * });
|
874 | *
|
875 | * Note that if a callback is supplied, it becomes the application's
|
876 | * responsibility to log-in the user, establish a session, and otherwise perform
|
877 | * the desired operations.
|
878 | *
|
879 | * Examples:
|
880 | *
|
881 | * passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' });
|
882 | *
|
883 | * passport.authenticate('basic', { session: false });
|
884 | *
|
885 | * passport.authenticate('twitter');
|
886 | */
|
887 | authenticate(
|
888 | passport: Authenticator<InitializeRet, AuthenticateRet, AuthorizeRet>,
|
889 | name: string,
|
890 | options?: any,
|
891 | callback?: (...args: any[]) => any,
|
892 | ): (...args: any[]) => AuthenticateRet;
|
893 | /**
|
894 | * Create third-party service authorization middleware.
|
895 | *
|
896 | * Returns middleware that will authorize a connection to a third-party service.
|
897 | *
|
898 | * This middleware is identical to using {@link Authenticator.authenticate `authenticate()`}
|
899 | * middleware with the `assignProperty` option set to `'account'`. This is
|
900 | * useful when a user is already authenticated (for example, using a username
|
901 | * and password) and they want to connect their account with a third-party
|
902 | * service.
|
903 | *
|
904 | * In this scenario, the user's third-party account will be set at
|
905 | * `req.account`, and the existing `req.user` and login session data will be
|
906 | * be left unmodified. A route handler can then link the third-party account to
|
907 | * the existing local account.
|
908 | *
|
909 | * All arguments to this function behave identically to those accepted by
|
910 | * {@link Authenticator.authenticate `Authenticator.authenticate`}.
|
911 | *
|
912 | * @example
|
913 | * app.get('/oauth/callback/twitter', passport.authorize('twitter'));
|
914 | */
|
915 | authorize?(
|
916 | passport: Authenticator<InitializeRet, AuthenticateRet, AuthorizeRet>,
|
917 | name: string,
|
918 | options?: any,
|
919 | callback?: (...args: any[]) => any,
|
920 | ): (...args: any[]) => AuthorizeRet;
|
921 | }
|
922 | }
|
923 |
|
924 | declare const passport: passport.PassportStatic;
|
925 | export = passport;
|