├── .eslintrc.js ├── .gitignore ├── .npmrc ├── .prettierrc ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── commitlint.config.js ├── lib ├── index.ts ├── oauth-core.module.ts ├── oauth.constants.ts ├── oauth.controller.ts ├── oauth.interface.ts ├── oauth.module.ts ├── oauth.service.ts └── utils │ ├── apply-decorators.ts │ ├── custom-url.factory.ts │ ├── getLength.ts │ ├── github-url.factory.ts │ ├── google-url.factory.ts │ ├── index.ts │ ├── sanitize.ts │ └── service-function.factory.ts ├── nest-cli.json ├── package.json ├── test ├── app.e2e-spec.ts ├── app.module.ts ├── jest-e2e.json ├── main.ts └── utils │ ├── http-promise.ts │ ├── index.ts │ └── wait-for.ts ├── tsconfig.build.json ├── tsconfig.dev.json ├── tsconfig.json └── yarn.lock /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | sourceType: 'module', 6 | }, 7 | plugins: ['@typescript-eslint/eslint-plugin'], 8 | extends: [ 9 | 'plugin:@typescript-eslint/eslint-recommended', 10 | 'plugin:@typescript-eslint/recommended', 11 | 'prettier', 12 | 'prettier/@typescript-eslint', 13 | ], 14 | root: true, 15 | env: { 16 | node: true, 17 | jest: true, 18 | }, 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/no-explicit-any': 'off', 23 | '@typescript-eslint/camelcase': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /dist-test 4 | /node_modules 5 | 6 | # Logs 7 | logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json 36 | # compiled output 37 | /dist 38 | /node_modules 39 | 40 | # Logs 41 | logs 42 | *.log 43 | npm-debug.log* 44 | yarn-debug.log* 45 | yarn-error.log* 46 | lerna-debug.log* 47 | 48 | # OS 49 | .DS_Store 50 | 51 | # Tests 52 | /coverage 53 | /.nyc_output 54 | 55 | # IDEs and editors 56 | /.idea 57 | .project 58 | .classpath 59 | .c9/ 60 | *.launch 61 | .settings/ 62 | *.sublime-workspace 63 | 64 | # IDE - VSCode 65 | .vscode/* 66 | !.vscode/settings.json 67 | !.vscode/tasks.json 68 | !.vscode/launch.json 69 | !.vscode/extensions.json 70 | 71 | .env -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | tag-version-prefix="" 2 | message="chore(release): %s :tada:" -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "arrowParens": "always", 4 | "trailingComma": "all", 5 | "overrides": [ 6 | { 7 | "files": "*.md", 8 | "options": { 9 | "printWidth": 70, 10 | "useTabs": false, 11 | "trailingComma": "none", 12 | "proseWrap": "never" 13 | } 14 | } 15 | ] 16 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # [0.3.0](https://github.com/jmcdo29/nestjs-oauth/compare/0.2.1...0.3.0) (2020-06-24) 2 | 3 | ### Features 4 | 5 | - **custom:** adds ability for integration with GET token urls ([1d7294c](https://github.com/jmcdo29/nestjs-oauth/commit/1d7294c63cfcd91bc85997767b6ca1db4c22589b)) 6 | - **custom:** allows for basic custom oauth authority addition ([1a71219](https://github.com/jmcdo29/nestjs-oauth/commit/1a71219ed35f4f537930551fffc8aa13c3d4d9ee)) 7 | - allows for decorator usage and access to req in `provide` ([797c320](https://github.com/jmcdo29/nestjs-oauth/commit/797c320a7ec360c053c29c3ac667551cf8659d9b)) 8 | - allows for the use of all nest decorators ([304f047](https://github.com/jmcdo29/nestjs-oauth/commit/304f047eea42074b6dd4af1b9fbd820a9a5867ac)) 9 | 10 | ### BREAKING CHANGES 11 | 12 | - the `provide` method now has a different parameter type, from a simple object to a complex one. 13 | 14 | ## [0.2.1](https://github.com/jmcdo29/nestjs-oauth/compare/0.2.0...0.2.1) (2020-06-17) 15 | 16 | ### Bug Fixes 17 | 18 | - allows for the use of a function that returns an observable ([93d1418](https://github.com/jmcdo29/nestjs-oauth/commit/93d1418b84e8c68e8f4f625fe71c92cab313e939)) 19 | 20 | # [0.2.0](https://github.com/jmcdo29/nestjs-oauth/compare/0.1.0...0.2.0) (2020-06-16) 21 | 22 | ### Features 23 | 24 | - **github:** updates the github oauth login url flow ([aaa105b](https://github.com/jmcdo29/nestjs-oauth/commit/aaa105be2ac7544fcaf7925ef062584155dd7365)) 25 | - adds ability to use guards on login route and interceptors on cb ([175501c](https://github.com/jmcdo29/nestjs-oauth/commit/175501cabc14a43e6770a27d1a027eebd3c2d170)) 26 | - updates types to allow for better dev experience ([fa50bf7](https://github.com/jmcdo29/nestjs-oauth/commit/fa50bf7140bb5f326ae393121322f317ecc094af)) 27 | 28 | ### BREAKING CHANGES 29 | 30 | - The `OauthModuleOptions` have been updated in the `controller` and `service` objects. In the `controller` object, each route is now a `path` and `guards` or `interceptors` property, and the `service` now is specific to each provider. 31 | 32 | # 0.1.0 (2020-06-14) 33 | 34 | ### Bug Fixes 35 | 36 | - **google:** fixes access_type string ([cb64922](https://github.com/jmcdo29/nestjs-oauth/commit/cb64922d32ce84c5c9b26a7eff5a5b02abf3fc80)) 37 | - **module:** fix module options to only allow one controller root ([41b5d30](https://github.com/jmcdo29/nestjs-oauth/commit/41b5d30e542b6ab1e623cbef91aa5e40bebeda9f)) 38 | 39 | ### Features 40 | 41 | - **facebook:** removes facebook as a provider ([6651036](https://github.com/jmcdo29/nestjs-oauth/commit/6651036668d41d0678a29f5216ad6a1faba8cfb2)) 42 | - **github:** adds github oauth flow ([68fdc2f](https://github.com/jmcdo29/nestjs-oauth/commit/68fdc2f016d0dce02f96c9f0df4b0589934534fa)) 43 | - **google:** implements google oauth options ([e71a744](https://github.com/jmcdo29/nestjs-oauth/commit/e71a744d41a1f86894958500b7193112a7a8e4d2)) 44 | - **module:** implements initial draft of OauthModule ([2958f0a](https://github.com/jmcdo29/nestjs-oauth/commit/2958f0ae23e96a88528ea861b72daa7503e5b728)) 45 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | - Demonstrating empathy and kindness toward other people 14 | - Being respectful of differing opinions, viewpoints, and experiences 15 | - Giving and gracefully accepting constructive feedback 16 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | - Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | - The use of sexualized language or imagery, and sexual attention or advances of any kind 22 | - Trolling, insulting or derogatory comments, and personal or political attacks 23 | - Public or private harassment 24 | - Publishing others' private information, such as a physical or email address, without their explicit permission 25 | - Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Enforcement Responsibilities 28 | 29 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [me@jaymcdoniel.dev](mailto:me@jaymcdoniel.dev). All complaints will be reviewed and investigated promptly and fairly. 40 | 41 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 42 | 43 | ## Enforcement Guidelines 44 | 45 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 46 | 47 | ### 1. Correction 48 | 49 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 50 | 51 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 52 | 53 | ### 2. Warning 54 | 55 | **Community Impact**: A violation through a single incident or series of actions. 56 | 57 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 58 | 59 | ### 3. Temporary Ban 60 | 61 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 62 | 63 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 64 | 65 | ### 4. Permanent Ban 66 | 67 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 68 | 69 | **Consequence**: A permanent ban from any sort of public interaction within the community. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 74 | 75 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 76 | 77 | [homepage]: https://www.contributor-covenant.org 78 | 79 | For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 80 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | # The MIT License 2 | 3 | Copyright 2019 Jay McDoniel, contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nestjs-Oauth 2 | 3 | The NestJS Oauth module is a bit of an interesting case. Currently, only Google and GitHub are available OAuth providers, but others may come in the future. 4 | 5 | ## Installation 6 | 7 | To install the package, use either 8 | 9 | ```sh 10 | npm i nestjs-oauth 11 | ``` 12 | 13 | or 14 | 15 | ```sh 16 | yarn nestjs-oauth 17 | ``` 18 | 19 | ## Usage 20 | 21 | The `OauthModule` does a lot of magic under the hood when it comes to binding the routes to the server, all according to `controllerRoot` and each `authorities.controller.root` and `authorities.controller.callback` value. The module will also take into account the global prefix if one is set. 22 | 23 | ### OauthModuleOptions 24 | 25 | - controllerRoot: string - Sets the `@Controller()` string for the root of the controller 26 | - authorities: [`OauthModuleProviderOptions`](#oauthmoduleprovideroptions)[] - the array of options for the OAuth module to make use of 27 | 28 | ### OauthModuleProviderOptions 29 | 30 | This object dictates much of how the `OauthModule` operates under the hood. The object has the following shape 31 | 32 | - name: `'google' | 'github'` - the name of the OAuth Provider. Currently only GitHub and Google are supported. 33 | - controller: [`ControllerOptions`](#controlleroptions) - options specific to the controller class 34 | - service: [`ServiceOptions`](#serviceoptions) - options specific to the service class 35 | - provide: `(resp: {user: Record, req: Record }) => any` - a function to determine how to handle the returned user from the OAuth callout. This function can come from a class or can be a direct function. Part of the `user` parameter is the token information retrieved from the token call (the OAuth callback) and the other part is the user information retrieved from the identity endpoint provided by the OAuth authority. The Request object is also accessible for the case of wanting to set headers or cookies through packages similar to [`@nestjsplus/cookies`](https://github.com/nestjsplus/cookies). 36 | 37 | ### ControllerOptions 38 | 39 | The object that dictates how the Controller class for the `OauthModule`. Both `root` and `callback` have the same interface, and require the same values as shown below: 40 | 41 | - path: string - the location for the route to be bound 42 | - guards: Array, optional - guards to run on the route 43 | - pipes: Array, optional - pipes to run on the route 44 | - interceptors: Array, optional - interceptors to run on the route 45 | - filters: Array, optional - filters to run on the route 46 | - decorators: Array, optional - decorators to apply to the route. This is specifically added for things like `@OgmaSkip()` or `@Throttle()` though can be used with `@UsePipes()` and the rest of the Nest enhancer decorators if preferred. 47 | 48 | ### ServiceOptions 49 | 50 | - scope: string[], optional - an array of scopes to request from the authority provider. This **must** be passed as an array 51 | - clientId: string - the client id for the authority you are using 52 | - clientSecret: string - the client secret for the authority you are using 53 | - callback: string, optional - the callback url for the authority. This should match the `controller.callback` property, but should be a fully qualified URL instead of an endpoint path e.g. `http://localhost:3000/api/auth/google/callback` 54 | - prompt: string, optional - the kind of prompt to use with the oauth flow, is a prompt is supported. 55 | - state: string, optional - a state tracking token to know that the return of the OAuth call comes from the expected server. 56 | 57 | > **NOTE**: if a state token is passed as a parameter, the `OauthService` method will check the returned state parameter against provided one, and will throw an `UnauthorizedException` if the values do not match. 58 | 59 | > **NOTE**: the Oauth module will not enforce most options on you, as not all OAuth authorities require all of these options. However, if your authority requires them, make sure you add the fields 60 | 61 | > **WARNING**: If no data modification happens on the return of `provide`, there will be a breaking error of the inability to convert a circularly structured JSON. This is intended. 62 | 63 | #### Specific Providers 64 | 65 | Each specific OAuth authority has their own provider values. These follow the values expected from the provider's OAuth documentation, usually changed from snake_case to camelCase. Intellisense should provide you with the options necessary. [Otherwise, you can look here](./lib/oauth.interface.ts) 66 | 67 | ### Custom Service Options 68 | 69 | This module contains the ability to manage custom authorities that are not yet baked in as solutions. The same process is used overall, however, the service options object has a different structure to it: 70 | 71 | - loginUrl: string - the URL where the oauth flow is kicked off. This just needs to be the base URL, as this package will worry about building the rest of it for you (e.g. `https://accounts.google.com/o/oauth2/v2/auth`) 72 | - tokenUrl: string - the URL where the request is made to retrieve an access token 73 | - userUrl: string - the URL to determine the identity of the user who just logged in through the OAuth flow (e.g. `'https://www.googleapis.com/userinfo/v2/me`) 74 | - tokenHttpMethod: 'get' | 'post', optional - as some OAuth authorities allow the usage of `GET` methods when it comes to getting the token, this option is available to set that. By default, the value is `'post'`\* 75 | - loginUrlParams: [`LoginUrlParams`](#loginurlparams) - options that are to be used for the login URL. **Some of these options are reused when it comes to the token request as well. They only need to be defined here**. 76 | - tokenUrlParams: [`TokenUrlParams`](#tokenurlparams) - options to be passed to the Token URL defined above. 77 | 78 | > **Warning**: With authorities that use GET methods for the token flow, be very careful, as your client Id and client Secret will be exposed in the URL. Anyone who is sniffing HTTP traffic will be able to get a hold of these, and could end up using them elsewhere. 79 | 80 | #### LoginUrlParams 81 | 82 | - client_id: string 83 | - response_type: string - the response type for the OAuth request. Most of the time, this should be `'code'` 84 | - redirect_uri: string, optional 85 | - scope: string, optional - instead of being an array like in the other services, this time the scope is a string with space delimited values. This gets used directly in the call with no modifications, so make sure it matches what the OAuth provider expects 86 | - state: string, optional 87 | 88 | > Extra values can be added to the loginUrlParams object, so long as the OAuth authority will accept them, they should be added here. 89 | 90 | #### TokenUrlParams 91 | 92 | - grant_type: string 93 | - client_secret 94 | 95 | > The TokenUrlParams object takes the `redirect_uri` and the `client_id` from the `LoginUrlParams` object so that they do not have to be duplicated. 96 | 97 | > Extra values can be added to the tokenUrlParams object, so long as the OAuth authority will accept them, they should be added here. 98 | 99 | ## How it works 100 | 101 | All right, so here's the fun part of the package: after you register the module, a `Controller` and `Service` class will be created to match the endpoints requested in the `authorities` array. When a `GET` call is made to `controllerRoot/controller.root`, a URL will be returned. This URL is the OAuth login URL, which the user should be redirected to. The reason this module does not automatically redirect is for logging purposes as a `res.redirect` will end up causing post-controller interceptors to not fire. **This is different from how Passport operates and should be noted**. After the user follows the OAuth flow, a callback is made from the OAuth server to your server, using the `controllerRoot/controller.callback` route and the `service.callback` value. This callback has the user access token and is then used to call to the providers identity endpoint (e.g. Google calls back to `https://www.googleapis.com/userinfo/v2/me`). Once the user is obtained from the identity provider, the `provider` method is called with the `user` object returned. From here, the developer can work with the user object as necessary, doing things like communicating with a database, or creating tokens for the user. Any value can be returned from this `provide` method, so it can be a JWT, or a simple message saying the user successfully logged in. This method can be async as well. 102 | 103 | ## TODO 104 | 105 | - add more providers 106 | - e2e testing 107 | - maybe a better API 108 | 109 | ## Contributing 110 | 111 | Feel free to help contribute to this project in any way possible. You can reach out to me on Discord (PerfectOrphan31#6003), [email me](mailto:me@jaymcdoniel.dev), or raise an issue here in the repository. 112 | 113 | ## License 114 | 115 | This project is under an [MIT License](./LICENSE). 116 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { extends: ['@commitlint/config-conventional'] }; 2 | -------------------------------------------------------------------------------- /lib/index.ts: -------------------------------------------------------------------------------- 1 | export { OauthModuleOptions } from './oauth.interface'; 2 | export * from './oauth.module'; 3 | -------------------------------------------------------------------------------- /lib/oauth-core.module.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Controller, 3 | Get, 4 | HttpModule, 5 | HttpService, 6 | Module, 7 | Query, 8 | Req, 9 | } from '@nestjs/common'; 10 | import { createConfigurableDynamicRootModule } from '@golevelup/nestjs-modules'; 11 | import { 12 | loginUrl, 13 | OAUTH_MODULE_OPTIONS, 14 | service, 15 | user, 16 | } from './oauth.constants'; 17 | import { OauthController } from './oauth.controller'; 18 | import { 19 | OauthModuleOptions, 20 | OauthModuleProviderOptions, 21 | OauthCodeInterface, 22 | } from './oauth.interface'; 23 | import { OauthService } from './oauth.service'; 24 | import { 25 | applyMethodDecorator, 26 | checkOptions, 27 | sanitizeFunctionName, 28 | serviceGetUserFunction, 29 | serviceLoginFunction, 30 | } from './utils'; 31 | 32 | @Module({ 33 | imports: [HttpModule], 34 | controllers: [OauthController], 35 | }) 36 | export class OauthCoreModule extends createConfigurableDynamicRootModule< 37 | OauthCoreModule, 38 | OauthModuleOptions 39 | >(OAUTH_MODULE_OPTIONS, { 40 | providers: [ 41 | OauthService, 42 | { 43 | provide: 'REDEFINE_FUNCTIONS', 44 | useFactory: (options: OauthModuleOptions, http: HttpService) => { 45 | Controller(options.controllerRoot)(OauthController); 46 | options.authorities.forEach((option: OauthModuleProviderOptions) => { 47 | const controllerRootFunction = sanitizeFunctionName( 48 | option.controller.root.path + option.name, 49 | ); 50 | const controllerCallbackFunction = sanitizeFunctionName( 51 | option.controller.callback.path + option.name, 52 | ); 53 | const serviceLoginFuncName = sanitizeFunctionName( 54 | loginUrl + option.name, 55 | ); 56 | const serviceCallbackFuncName = sanitizeFunctionName( 57 | user + option.name, 58 | ); 59 | // CONTROLLER OVERRIDING 60 | OauthController.prototype[controllerRootFunction] = function() { 61 | return this[service][serviceLoginFuncName](); 62 | }; 63 | OauthController.prototype[controllerCallbackFunction] = function( 64 | query: OauthCodeInterface, 65 | req: any, 66 | ) { 67 | return this[service][serviceCallbackFuncName](query, req); 68 | }; 69 | // SERVICE OVERRIDING 70 | OauthService.prototype[serviceLoginFuncName] = function() { 71 | return serviceLoginFunction(option.name, option.service); 72 | }; 73 | OauthService.prototype[ 74 | serviceCallbackFuncName 75 | ] = serviceGetUserFunction( 76 | option.name, 77 | option.service, 78 | option.provide, 79 | http, 80 | ); 81 | applyMethodDecorator( 82 | Get, 83 | option.controller.root.path, 84 | OauthController, 85 | controllerRootFunction, 86 | ); 87 | checkOptions( 88 | option.controller.root, 89 | OauthController, 90 | controllerRootFunction, 91 | ); 92 | applyMethodDecorator( 93 | Get, 94 | option.controller.callback.path, 95 | OauthController, 96 | controllerCallbackFunction, 97 | ); 98 | checkOptions( 99 | option.controller.callback, 100 | OauthController, 101 | controllerCallbackFunction, 102 | ); 103 | Query()(OauthController.prototype, controllerCallbackFunction, 0); 104 | Req()(OauthController.prototype, controllerCallbackFunction, 1); 105 | }); 106 | }, 107 | inject: [OAUTH_MODULE_OPTIONS, HttpService], 108 | }, 109 | ], 110 | }) {} 111 | -------------------------------------------------------------------------------- /lib/oauth.constants.ts: -------------------------------------------------------------------------------- 1 | export const OAUTH_MODULE_OPTIONS = 'OAUTH_MODULE_OPTIONS'; 2 | export const service = 'oauthService'; 3 | export const loginUrl = 'getLoginUrl'; 4 | export const user = 'getUser'; 5 | export const github = { 6 | loginUrl: 'https://github.com/login/oauth/authorize', 7 | userUrl: 'https://api.github.com/user', 8 | tokenUrl: 'https://github.com/login/oauth/access_token', 9 | }; 10 | export const google = { 11 | loginUrl: 'https://accounts.google.com/o/oauth2/v2/auth', 12 | userUrl: 'https://www.googleapis.com/userinfo/v2/me', 13 | tokenUrl: 'https://oauth2.googleapis.com/token', 14 | }; 15 | export const JSONHeader = { 16 | 'Content-Type': 'application/json', 17 | Accept: 'application/json', 18 | }; 19 | export const oauth = { 20 | access: 'access_type', 21 | scope: 'scope', 22 | response: 'response_type', 23 | id: 'client_id', 24 | secret: 'client_secret', 25 | prompt: 'prompt', 26 | auth: 'authorization_code', 27 | redirect: 'redirect_uri', 28 | includeScopes: 'include_granted_scoped', 29 | loginHint: 'login_hint', 30 | state: 'state', 31 | }; 32 | export const code = 'code'; 33 | -------------------------------------------------------------------------------- /lib/oauth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller } from '@nestjs/common'; 2 | import { OauthService } from './oauth.service'; 3 | 4 | @Controller() 5 | export class OauthController { 6 | constructor(private readonly oauthService: OauthService) {} 7 | } 8 | -------------------------------------------------------------------------------- /lib/oauth.interface.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CanActivate, 3 | ExceptionFilter, 4 | NestInterceptor, 5 | PipeTransform, 6 | } from '@nestjs/common'; 7 | 8 | /** 9 | * G E N E R A L I N T E R F A C E S 10 | */ 11 | 12 | export interface RouteOptions { 13 | path: string; 14 | pipes?: (PipeTransform | Function)[]; 15 | guards?: (CanActivate | Function)[]; 16 | interceptors?: (NestInterceptor | Function)[]; 17 | filters?: (ExceptionFilter | Function)[]; 18 | decorators?: MethodDecorator[]; 19 | } 20 | 21 | export interface ControllerOptions { 22 | root: RouteOptions; 23 | callback: RouteOptions; 24 | } 25 | 26 | export interface ServiceOptions { 27 | scope?: string[]; 28 | clientId: string; 29 | prompt?: string; 30 | clientSecret: string; 31 | callbackUrl?: string; 32 | state?: string; 33 | } 34 | 35 | interface OauthModuleOptionsBase { 36 | controller: ControllerOptions; 37 | provide: (resp: { 38 | user: Record; 39 | req: Record; 40 | }) => any; 41 | } 42 | 43 | /** 44 | * G O O G L E I N T E R F A C E S 45 | */ 46 | 47 | export interface GoogleServiceOptions extends ServiceOptions { 48 | scope: string[]; 49 | callbackUrl: string; 50 | accessType?: string; 51 | responseType?: string; 52 | includeGrantedScopes?: boolean; 53 | loginHint?: string; 54 | } 55 | 56 | export interface GoogleUser { 57 | access_token: string; 58 | expires_in: number; 59 | refresh_token: string; 60 | scope: string[]; 61 | token_type: string; 62 | [index: string]: any; 63 | } 64 | 65 | interface GoogleOauthModuleOptions extends OauthModuleOptionsBase { 66 | name: 'google'; 67 | service: GoogleServiceOptions; 68 | provide: (resp: { user: GoogleUser; req: any }) => any; 69 | } 70 | 71 | /** 72 | * G I T H U B I N T E R F A C E S 73 | */ 74 | 75 | export interface GithubServiceOptions extends ServiceOptions { 76 | login?: string; 77 | allowSignup?: boolean; 78 | } 79 | 80 | export interface GithubUser { 81 | access_token: string; 82 | scope: string; 83 | token_type: string; 84 | [index: string]: any; 85 | } 86 | 87 | interface GithubOauthModuleOptions extends OauthModuleOptionsBase { 88 | name: 'github'; 89 | service: GithubServiceOptions; 90 | provide: (resp: { user: GithubUser; req: any }) => any; 91 | } 92 | 93 | /** 94 | * C U S T O M I N T E R F A C E 95 | */ 96 | 97 | export interface CustomServiceOptions { 98 | loginUrl: string; 99 | tokenUrl: string; 100 | userUrl: string; 101 | loginUrlParams: { 102 | client_id: string; 103 | response_type: string; 104 | redirect_uri?: string; 105 | scope?: string; 106 | state?: string; 107 | [index: string]: any; 108 | }; 109 | tokenUrlParams: { 110 | grant_type: string; 111 | client_secret: string; 112 | [index: string]: any; 113 | }; 114 | tokenHttpMethod?: 'get' | 'post'; 115 | } 116 | 117 | interface CustomOauthModuleOptions extends OauthModuleOptionsBase { 118 | name: string; 119 | service: CustomServiceOptions; 120 | } 121 | 122 | /** 123 | * M O D U L E O P T I O N S 124 | */ 125 | 126 | export type OauthModuleProviderOptions = 127 | | GoogleOauthModuleOptions 128 | | GithubOauthModuleOptions 129 | | CustomOauthModuleOptions; 130 | 131 | export interface OauthModuleOptions { 132 | authorities: OauthModuleProviderOptions[]; 133 | controllerRoot: string; 134 | } 135 | 136 | export type OauthProvider = 'google' | 'github'; 137 | 138 | export interface OauthCodeInterface { 139 | code: string; 140 | state?: string; 141 | } 142 | 143 | export interface GoogleOauthCode extends OauthCodeInterface { 144 | scope: string; 145 | authUser: string; 146 | prompt: string; 147 | } 148 | -------------------------------------------------------------------------------- /lib/oauth.module.ts: -------------------------------------------------------------------------------- 1 | import { AsyncModuleConfig } from '@golevelup/nestjs-modules'; 2 | import { Module, DynamicModule } from '@nestjs/common'; 3 | import { OauthCoreModule } from './oauth-core.module'; 4 | import { OauthModuleOptions } from './oauth.interface'; 5 | 6 | @Module({}) 7 | export class OauthModule { 8 | static forRoot(oauthOptions: OauthModuleOptions): DynamicModule { 9 | return OauthCoreModule.forRoot(OauthCoreModule, oauthOptions); 10 | } 11 | 12 | static forRootAsync(oauthAsyncOptions: AsyncModuleConfig): DynamicModule { 13 | return OauthCoreModule.forRootAsync(OauthCoreModule, oauthAsyncOptions); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /lib/oauth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class OauthService {} 5 | -------------------------------------------------------------------------------- /lib/utils/apply-decorators.ts: -------------------------------------------------------------------------------- 1 | import { 2 | UseFilters, 3 | UseGuards, 4 | UseInterceptors, 5 | UsePipes, 6 | } from '@nestjs/common'; 7 | import { RouteOptions } from '../oauth.interface'; 8 | import { getLength } from './getLength'; 9 | 10 | export function applyMethodDecorator( 11 | decorator: (...args: any) => MethodDecorator, 12 | value: any, 13 | target: Record, 14 | property: string, 15 | ) { 16 | decorator(value)( 17 | target, 18 | property, 19 | Object.getOwnPropertyDescriptor(target.prototype, property), 20 | ); 21 | } 22 | 23 | export function checkOptions( 24 | options: RouteOptions, 25 | target: Record, 26 | property: string, 27 | ) { 28 | if (getLength(options.guards)) { 29 | applyMethodDecorator(UseGuards, options.guards, target, property); 30 | } 31 | if (getLength(options.interceptors)) { 32 | applyMethodDecorator( 33 | UseInterceptors, 34 | options.interceptors, 35 | target, 36 | property, 37 | ); 38 | } 39 | if (getLength(options.pipes)) { 40 | applyMethodDecorator(UsePipes, options.pipes, target, property); 41 | } 42 | if (getLength(options.filters)) { 43 | applyMethodDecorator(UseFilters, options.filters, target, property); 44 | } 45 | if (getLength(options.decorators)) { 46 | options.decorators.forEach((decorator) => { 47 | decorator( 48 | target, 49 | property, 50 | Object.getOwnPropertyDescriptor(target.prototype, property), 51 | ); 52 | }); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /lib/utils/custom-url.factory.ts: -------------------------------------------------------------------------------- 1 | import { CustomServiceOptions } from '../oauth.interface'; 2 | 3 | export const createCustomLoginUrl = (options: CustomServiceOptions): string => { 4 | const loginParams = options.loginUrlParams; 5 | const queryString = Object.keys(loginParams).map( 6 | (key) => `${key}=${loginParams[key]}`, 7 | ); 8 | return `${options.loginUrl}?${queryString.join('&')}`; 9 | }; 10 | 11 | export const createCustomUserFunction = ( 12 | options: CustomServiceOptions, 13 | code: string, 14 | ): { 15 | url: string; 16 | userUrl: string; 17 | options: { 18 | client_id: string; 19 | client_secret: string; 20 | code: string; 21 | redirect_uri: string; 22 | state: string; 23 | }; 24 | } => { 25 | const { redirect_uri, client_id } = options.loginUrlParams; 26 | const tokenOpts = { ...options.tokenUrlParams, redirect_uri, client_id }; 27 | if (options.tokenHttpMethod === 'get') { 28 | const queryString = 29 | Object.keys(tokenOpts) 30 | .map((key) => `${key}=${tokenOpts[key]}`) 31 | .join('&') + `&code=${code}`; 32 | return { 33 | url: options.tokenUrl + `?${queryString}`, 34 | userUrl: options.userUrl, 35 | } as any; 36 | } 37 | return { 38 | url: options.tokenUrl, 39 | userUrl: options.userUrl, 40 | options: { 41 | code, 42 | ...tokenOpts, 43 | }, 44 | } as any; 45 | }; 46 | -------------------------------------------------------------------------------- /lib/utils/getLength.ts: -------------------------------------------------------------------------------- 1 | export function getLength(obj: any[]): number { 2 | return (obj && obj.length) || 0; 3 | } 4 | -------------------------------------------------------------------------------- /lib/utils/github-url.factory.ts: -------------------------------------------------------------------------------- 1 | import { github, oauth } from '../oauth.constants'; 2 | import { GithubServiceOptions } from '../oauth.interface'; 3 | 4 | export const createGithubLoginUrl = (options: GithubServiceOptions): string => { 5 | let queryString = `${oauth.id}=${options.clientId}`; 6 | if (options?.scope.length) { 7 | queryString += `&${oauth.scope}=${options.scope.join(' ')}`; 8 | } 9 | if (options.login) { 10 | queryString += `&login=${options.login}`; 11 | } 12 | if (options.callbackUrl) { 13 | queryString += `&${oauth.redirect}=${options.callbackUrl}`; 14 | } 15 | if (options.state) { 16 | queryString += `&${oauth.state}=${options.state}`; 17 | } 18 | if (options.allowSignup !== null && options.allowSignup !== undefined) { 19 | queryString += `&allow_signup=${options.allowSignup}`; 20 | } 21 | return `${github.loginUrl}?${queryString}`; 22 | }; 23 | 24 | export const createGithubUserFunction = ( 25 | options: GithubServiceOptions, 26 | code: string, 27 | ): { 28 | url: string; 29 | userUrl: string; 30 | options: { 31 | client_id: string; 32 | client_secret: string; 33 | code: string; 34 | redirect_uri: string; 35 | state: string; 36 | }; 37 | } => { 38 | return { 39 | url: github.tokenUrl, 40 | options: { 41 | client_id: options.clientId, 42 | client_secret: options.clientSecret, 43 | code, 44 | redirect_uri: options.callbackUrl, 45 | state: options.state, 46 | }, 47 | userUrl: github.userUrl, 48 | }; 49 | }; 50 | -------------------------------------------------------------------------------- /lib/utils/google-url.factory.ts: -------------------------------------------------------------------------------- 1 | import { google, oauth } from '../oauth.constants'; 2 | import { GoogleServiceOptions } from '../oauth.interface'; 3 | 4 | export const createGoogleLoginUrl = (options: GoogleServiceOptions): string => { 5 | let queryString = `${oauth.scope}=${options.scope.join(' ')}`; 6 | queryString += `&${oauth.id}=${options.clientId}`; 7 | queryString += `&${oauth.redirect}=${options.callbackUrl}`; 8 | if (options.accessType) { 9 | queryString += `&${oauth.access}=${options.accessType}`; 10 | } 11 | if (options.prompt) { 12 | queryString += `&${oauth.prompt}=${options.prompt}`; 13 | } 14 | if (options.responseType) { 15 | queryString += `&${oauth.response}=${options.responseType}`; 16 | } 17 | if ( 18 | options.includeGrantedScopes !== null && 19 | options.includeGrantedScopes !== undefined 20 | ) { 21 | queryString += `&${oauth.includeScopes}=${options.includeGrantedScopes}`; 22 | } 23 | if (options.loginHint) { 24 | queryString += `&${oauth.loginHint}=${options.loginHint}`; 25 | } 26 | if (options.state) { 27 | queryString += `&${oauth.state}=${options.state}`; 28 | } 29 | return `${google.loginUrl}?${queryString}`; 30 | }; 31 | 32 | export const createGoogleUserFunction = ( 33 | options: GoogleServiceOptions, 34 | code: string, 35 | ): { 36 | url: string; 37 | options: Record; 38 | userUrl: string; 39 | } => { 40 | return { 41 | url: google.tokenUrl, 42 | options: { 43 | client_id: options.clientId, 44 | client_secret: options.clientSecret, 45 | code, 46 | grant_type: oauth.auth, 47 | redirect_uri: options.callbackUrl, 48 | }, 49 | userUrl: google.userUrl, 50 | }; 51 | }; 52 | -------------------------------------------------------------------------------- /lib/utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from './apply-decorators'; 2 | export * from './getLength'; 3 | export * from './sanitize'; 4 | export * from './service-function.factory'; 5 | -------------------------------------------------------------------------------- /lib/utils/sanitize.ts: -------------------------------------------------------------------------------- 1 | export function sanitizeFunctionName(functionName: string): string { 2 | return functionName 3 | .split('/') 4 | .join('') 5 | .split('-') 6 | .filter(part => !!part) 7 | .map(part => { 8 | const parts = part.split(''); 9 | parts[0] = parts[0].toUpperCase(); 10 | return parts.join(''); 11 | }) 12 | .join(''); 13 | } 14 | -------------------------------------------------------------------------------- /lib/utils/service-function.factory.ts: -------------------------------------------------------------------------------- 1 | import { ForbiddenException, HttpService } from '@nestjs/common'; 2 | import { from } from 'rxjs'; 3 | import { map, switchMap } from 'rxjs/operators'; 4 | import { JSONHeader } from '../oauth.constants'; 5 | import { 6 | CustomServiceOptions, 7 | GithubServiceOptions, 8 | GoogleServiceOptions, 9 | OauthCodeInterface, 10 | ServiceOptions, 11 | } from '../oauth.interface'; 12 | import { 13 | createCustomLoginUrl, 14 | createCustomUserFunction, 15 | } from './custom-url.factory'; 16 | import { 17 | createGithubLoginUrl, 18 | createGithubUserFunction, 19 | } from './github-url.factory'; 20 | import { 21 | createGoogleLoginUrl, 22 | createGoogleUserFunction, 23 | } from './google-url.factory'; 24 | 25 | export const serviceLoginFunction = ( 26 | provider: string, 27 | options: ServiceOptions | CustomServiceOptions, 28 | ): { url: string; provider: string } => { 29 | let url: string; 30 | switch (provider) { 31 | case 'google': 32 | url = createGoogleLoginUrl(options as GoogleServiceOptions); 33 | break; 34 | case 'github': 35 | url = createGithubLoginUrl(options as GithubServiceOptions); 36 | break; 37 | default: 38 | url = createCustomLoginUrl(options as CustomServiceOptions); 39 | break; 40 | } 41 | return { url, provider }; 42 | }; 43 | 44 | export const serviceGetUserFunction = ( 45 | provider: string, 46 | options: ServiceOptions | CustomServiceOptions, 47 | service: (resp: { user: Record; req: any }) => any, 48 | http: HttpService, 49 | ): any => { 50 | let urlAndOptions: { 51 | url: string; 52 | options: Record; 53 | userUrl: string; 54 | }; 55 | const func = (oauthResp: OauthCodeInterface, req: any) => { 56 | switch (provider) { 57 | case 'google': 58 | urlAndOptions = createGoogleUserFunction( 59 | options as GoogleServiceOptions, 60 | oauthResp.code, 61 | ); 62 | break; 63 | case 'github': 64 | urlAndOptions = createGithubUserFunction( 65 | options as GithubServiceOptions, 66 | oauthResp.code, 67 | ); 68 | break; 69 | default: 70 | urlAndOptions = createCustomUserFunction( 71 | options as CustomServiceOptions, 72 | oauthResp.code, 73 | ); 74 | break; 75 | } 76 | const state = 77 | (options as ServiceOptions).state || 78 | (options as CustomServiceOptions)?.loginUrlParams.state || 79 | undefined; 80 | if (state) { 81 | if (state !== oauthResp.state) { 82 | throw new ForbiddenException( 83 | `Expected a state value of ${state} but instead got ${oauthResp.state}`, 84 | ); 85 | } 86 | } 87 | let tokenData: Record; 88 | const axiosReq = { 89 | method: 90 | (options as CustomServiceOptions).tokenHttpMethod || ('post' as const), 91 | url: urlAndOptions.url, 92 | data: urlAndOptions.options, 93 | headers: JSONHeader, 94 | }; 95 | return http.request(axiosReq).pipe( 96 | map((res) => { 97 | tokenData = res.data; 98 | return tokenData; 99 | }), 100 | switchMap((accessData) => 101 | http.get(urlAndOptions.userUrl, { 102 | headers: { 103 | Authorization: `Bearer ${accessData.access_token}`, 104 | }, 105 | }), 106 | ), 107 | map((userData) => userData.data), 108 | switchMap((user) => { 109 | const retVal = service({ user: { ...tokenData, ...user }, req }); 110 | if (retVal.pipe) { 111 | return retVal; 112 | } 113 | return from(retVal); 114 | }), 115 | ); 116 | }; 117 | return func; 118 | }; 119 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-oauth", 3 | "version": "0.3.0", 4 | "description": "An OAuth Module the mimics Passport's functionality without some of passport's wonkiness", 5 | "author": "Jay McDoniel ", 6 | "private": false, 7 | "license": "MIT", 8 | "main": "dist/index.js", 9 | "types": "dist/index.d.ts", 10 | "files": [ 11 | "dist" 12 | ], 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/jmcdo29/nestjs-oauth.git" 16 | }, 17 | "bugs": { 18 | "url": "https://github.com/jmcdo29/nestjs-oauth/issues" 19 | }, 20 | "homepage": "https://github.com/jmcdo29/nestjs-oauth#readme", 21 | "scripts": { 22 | "build": "nest build", 23 | "build:dev": "nest build --path tsconfig.dev.json", 24 | "commit": "git-cz", 25 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\" \"*.md\"", 26 | "start": "nest start", 27 | "start:dev": "yarn build:dev && node dist-test/test/main.js", 28 | "start:debug": "nest start --debug --watch", 29 | "start:prod": "node dist/main", 30 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 31 | "preversion": "yarn run format && yarn run lint && yarn build", 32 | "test": "jest", 33 | "test:watch": "jest --watch", 34 | "test:cov": "jest --coverage", 35 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 36 | "test:e2e": "jest --config ./test/jest-e2e.json", 37 | "version": "conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md" 38 | }, 39 | "dependencies": { 40 | "@golevelup/nestjs-modules": "^0.4.0" 41 | }, 42 | "devDependencies": { 43 | "@commitlint/cli": "^8.3.5", 44 | "@commitlint/config-conventional": "^8.3.4", 45 | "@nestjs/cli": "^7.0.0", 46 | "@nestjs/common": "^7.0.0", 47 | "@nestjs/core": "^7.0.0", 48 | "@nestjs/platform-express": "^7.0.0", 49 | "@nestjs/schematics": "^7.0.0", 50 | "@nestjs/testing": "^7.0.0", 51 | "@ogma/nestjs-module": "^0.1.0", 52 | "@ogma/platform-express": "^0.1.0", 53 | "@types/express": "^4.17.3", 54 | "@types/jest": "25.1.4", 55 | "@types/node": "^13.9.1", 56 | "@types/supertest": "^2.0.8", 57 | "@typescript-eslint/eslint-plugin": "^2.23.0", 58 | "@typescript-eslint/parser": "^2.23.0", 59 | "conventional-changelog-cli": "^2.0.31", 60 | "cz-conventional-changelog": "^3.1.0", 61 | "dotenv": "^8.2.0", 62 | "eslint": "^6.8.0", 63 | "eslint-config-prettier": "^6.10.0", 64 | "eslint-plugin-import": "^2.20.1", 65 | "husky": "^4.2.5", 66 | "jest": "^25.1.0", 67 | "lint-staged": "^10.2.9", 68 | "prettier": "^1.19.1", 69 | "reflect-metadata": "^0.1.13", 70 | "rimraf": "^3.0.2", 71 | "rxjs": "^6.5.4", 72 | "supertest": "^4.0.2", 73 | "ts-jest": "25.2.1", 74 | "ts-loader": "^6.2.1", 75 | "ts-node": "^8.6.2", 76 | "tsconfig-paths": "^3.9.0", 77 | "typescript": "^3.7.4" 78 | }, 79 | "peerDependencies": { 80 | "@nestjs/common": "^7.0.0", 81 | "@nestjs/core": "^7.0.0", 82 | "reflect-metadata": "^0.1.13", 83 | "rxjs": "^6.5.4" 84 | }, 85 | "jest": { 86 | "moduleFileExtensions": [ 87 | "js", 88 | "json", 89 | "ts" 90 | ], 91 | "rootDir": "src", 92 | "testRegex": ".spec.ts$", 93 | "transform": { 94 | "^.+\\.(t|j)s$": "ts-jest" 95 | }, 96 | "coverageDirectory": "../coverage", 97 | "testEnvironment": "node" 98 | }, 99 | "husky": { 100 | "hooks": { 101 | "pre-commit": "lint-staged", 102 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" 103 | } 104 | }, 105 | "lint-staged": { 106 | "*.ts": [ 107 | "prettier --write", 108 | "eslint --ext ts" 109 | ], 110 | "*.{md,html,json,js}": [ 111 | "prettier --write" 112 | ] 113 | }, 114 | "config": { 115 | "commitizen": { 116 | "path": "./node_modules/cz-conventional-changelog" 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { config } from 'dotenv'; 2 | config(); 3 | 4 | import { Test, TestingModule } from '@nestjs/testing'; 5 | import { INestApplication } from '@nestjs/common'; 6 | import { OauthModule } from '../lib'; 7 | import { waitFor, httpPromise } from './utils'; 8 | 9 | describe('AppController (e2e)', () => { 10 | let app: INestApplication; 11 | 12 | beforeAll(async () => { 13 | const moduleFixture: TestingModule = await Test.createTestingModule({ 14 | imports: [ 15 | OauthModule.forRoot({ 16 | controllerRoot: 'auth', 17 | authorities: [ 18 | { 19 | name: 'google', 20 | controller: { 21 | root: { 22 | path: 'google', 23 | }, 24 | callback: { 25 | path: '/google/callback', 26 | }, 27 | }, 28 | service: { 29 | scope: ['profile', 'email'], 30 | clientId: process.env.GOOGLE_CLIENT, 31 | callbackUrl: process.env.GOOGLE_CALLBACK, 32 | clientSecret: process.env.GOOGLE_SECRET, 33 | prompt: 'select_account', 34 | }, 35 | provide: async (user: any) => { 36 | await waitFor(3000); 37 | return user; 38 | }, 39 | }, 40 | ], 41 | }), 42 | ], 43 | }).compile(); 44 | 45 | app = moduleFixture.createNestApplication(); 46 | app.setGlobalPrefix('api'); 47 | await app.init(); 48 | await app.listen(0); 49 | }); 50 | 51 | afterAll(async () => { 52 | await app.close(); 53 | }); 54 | 55 | describe('oauth calls', () => { 56 | let baseUrl: string; 57 | 58 | beforeAll(async () => { 59 | baseUrl = await app.getUrl(); 60 | }); 61 | 62 | it('should call for the login URL', async () => { 63 | const data = await httpPromise(baseUrl + '/api/auth/google'); 64 | console.log(data); 65 | expect(true); 66 | }); 67 | }); 68 | }); 69 | -------------------------------------------------------------------------------- /test/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { OgmaModule, OgmaSkip } from '@ogma/nestjs-module'; 3 | import { ExpressParser } from '@ogma/platform-express'; 4 | import { OauthModule } from '../lib'; 5 | import { waitFor } from './utils'; 6 | 7 | async function saveUser(user: any) { 8 | await waitFor(3000); 9 | console.log(user.req); 10 | return user.user; 11 | } 12 | 13 | @Module({ 14 | imports: [ 15 | OauthModule.forRoot({ 16 | controllerRoot: 'oauth', 17 | authorities: [ 18 | { 19 | name: 'google', 20 | controller: { 21 | root: { 22 | path: 'google', 23 | }, 24 | callback: { 25 | path: '/google/callback', 26 | decorators: [OgmaSkip()], 27 | }, 28 | }, 29 | service: { 30 | scope: ['profile', 'email'], 31 | clientId: process.env.GOOGLE_CLIENT, 32 | callbackUrl: process.env.GOOGLE_CALLBACK, 33 | clientSecret: process.env.GOOGLE_SECRET, 34 | prompt: 'select_account', 35 | responseType: 'code', 36 | state: 'some google state token', 37 | }, 38 | provide: saveUser, 39 | }, 40 | { 41 | name: 'github', 42 | controller: { 43 | callback: { 44 | path: '/github/callback', 45 | }, 46 | root: { 47 | path: 'github', 48 | }, 49 | }, 50 | service: { 51 | scope: ['user', 'repo'], 52 | clientId: process.env.GITHUB_CLIENT, 53 | callbackUrl: process.env.GITHUB_CALLBACK, 54 | clientSecret: process.env.GITHUB_SECRET, 55 | prompt: 'select_account', 56 | state: 'some github state token', 57 | }, 58 | provide: (response) => { 59 | console.log(response.req); 60 | return response.user; 61 | }, 62 | }, 63 | { 64 | name: 'customGoogle', 65 | controller: { 66 | root: { 67 | path: 'custom-google', 68 | }, 69 | callback: { 70 | path: 'custom-google/callback', 71 | decorators: [OgmaSkip()], 72 | }, 73 | }, 74 | service: { 75 | loginUrl: 'https://accounts.google.com/o/oauth2/v2/auth', 76 | tokenUrl: 'https://oauth2.googleapis.com/token', 77 | userUrl: 'https://www.googleapis.com/userinfo/v2/me', 78 | loginUrlParams: { 79 | client_id: process.env.GOOGLE_CLIENT, 80 | redirect_uri: process.env.GOOGLE_CUSTOM_CALLBACK, 81 | scope: 'email profile', 82 | prompt: 'select_account', 83 | response_type: 'code', 84 | }, 85 | tokenHttpMethod: 'post', 86 | tokenUrlParams: { 87 | client_secret: process.env.GOOGLE_SECRET, 88 | grant_type: 'authorization_code', 89 | }, 90 | }, 91 | provide: saveUser, 92 | }, 93 | ], 94 | }), 95 | OgmaModule.forRoot({ 96 | service: { 97 | color: true, 98 | json: false, 99 | application: 'Oauth', 100 | }, 101 | interceptor: { 102 | http: ExpressParser, 103 | }, 104 | }), 105 | ], 106 | }) 107 | export class AppModule {} 108 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /test/main.ts: -------------------------------------------------------------------------------- 1 | import { config } from 'dotenv'; 2 | config(); 3 | import { NestFactory } from '@nestjs/core'; 4 | import { OauthModule } from '../lib'; 5 | import { waitFor } from './utils'; 6 | import { AppModule } from './app.module'; 7 | 8 | class SaveUserClass { 9 | async saveUser(user: any) { 10 | await waitFor(3000); 11 | return user; 12 | } 13 | } 14 | 15 | const bootstrap = async () => { 16 | const saveUSerClass = new SaveUserClass(); 17 | const app = await NestFactory.create(AppModule); 18 | app.setGlobalPrefix('api'); 19 | await app.listen(3333); 20 | }; 21 | 22 | bootstrap(); 23 | -------------------------------------------------------------------------------- /test/utils/http-promise.ts: -------------------------------------------------------------------------------- 1 | import { request, RequestOptions } from 'http'; 2 | 3 | export const httpPromise = (url: string, options?: RequestOptions) => 4 | new Promise((resolve, reject) => { 5 | const req = request(url, options || {}, (res) => { 6 | let data = ''; 7 | res.on('data', (chunk) => (data += chunk)); 8 | res.on('end', () => resolve(data)); 9 | res.on('error', (err) => reject(err)); 10 | }); 11 | req.end(); 12 | }); 13 | -------------------------------------------------------------------------------- /test/utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from './http-promise'; 2 | export * from './wait-for'; 3 | -------------------------------------------------------------------------------- /test/utils/wait-for.ts: -------------------------------------------------------------------------------- 1 | export const waitFor = (time: number): Promise => { 2 | return new Promise((resolve) => { 3 | setTimeout(() => { 4 | resolve(); 5 | }, time); 6 | }); 7 | }; 8 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.dev.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "dist-test" 5 | }, 6 | "include": ["test"], 7 | "exclude": ["node_modules", "dist", "**/*spec.ts"] 8 | } 9 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "target": "es2017", 9 | "sourceMap": true, 10 | "outDir": "./dist", 11 | "baseUrl": "./", 12 | "incremental": true 13 | }, 14 | "exclude": ["node_modules", "dist"] 15 | } 16 | --------------------------------------------------------------------------------