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