UNPKG

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