{"_id":"@brainhubeu/hadron-oauth","_rev":"22-d9a692f3f10a5c7d71dc7d3afc612fa5","name":"@brainhubeu/hadron-oauth","dist-tags":{"latest":"1.0.2"},"versions":{"1.0.2":{"name":"@brainhubeu/hadron-oauth","version":"1.0.2","keywords":["hadron","hadron-oauth"],"author":{"name":"Brainhub"},"license":"MIT","_id":"@brainhubeu/hadron-oauth@1.0.2","maintainers":[{"name":"brainhub-adam","email":"adam@brainhub.pl"},{"name":"caderek","email":"maciej.caderek@gmail.com"},{"name":"drymek","email":"marcin@dryka.pl"},{"name":"dyoda","email":"lukasz.pluszczewski@gmail.com"},{"name":"szulcd2","email":"szulcd2@gmail.com"},{"name":"szymon.morawski","email":"szymon.morawski@brainhub.pl"}],"dist":{"shasum":"484a406ea842f40585aeeb0f0d060e528ad0f6a0","tarball":"https://registry.npmjs.org/@brainhubeu/hadron-oauth/-/hadron-oauth-1.0.2.tgz","fileCount":40,"integrity":"sha512-of7QV46tsp8BykVJmRTxohAEo8VoF6oMIDAPdBpHfJWriO8dnmnZ8dn+Mr2yJHPrPnAddHPbj9odmQWQTAEYNw==","signatures":[{"sig":"MEQCIBmluBUXG8wv8UVCcrpo9Qhi5bzYGAPn3633cq7w9XLpAiAOEzSeRlTR34G8Aj5Bo231vKjdR8WBKFnFkMbZfY3ZiQ==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":71546,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbR3lYCRA9TVsSAnZWagAAc4kP/3Jh6ShKvEvbkRPvsP1q\n/lpQFVX3ibTXglIgC21ZjJvzujPjiVl6AAStum+iry+OPMoKShIeF2dEuHeI\n9OiD9d/0BPobyyKassfN11Cj8I+XcLlmtRGc82llzl0d+tMRWmUr/ugBy0nV\nhhBmGnUZadMyStchBfzlL2ajECNjS86wilc0lwC0LwZdGKVCzaOnx1cnE4MF\nevCsCtWQgDuKMVXkZGnJ5KN0WVR+UuxpQnkYXZABZnkNAKp2k6YuPNFIwPkA\nYgnSxCeLpYtG6N11uHkqyTM2NHcI2m1XpGrg9Ib0RRvon0P6p6EvrQ1VVpKH\nzXqD/ccb5TUAa2/MvdvMaBcwkslmMLHrF8cxvfBz5EkEPbD4XlNEDJGpZRBp\nMCVHDyN9nmcYZboOf7rCxom10mZ43TvkynvWlEn2qRUVhjlxpjEf2VyorswK\neH/r7xWE/yXlBsm2hCY33ewzP/Tx6HCb3t9WSwpoVUoe8tAtiBRT/Jz+a2Q1\nHB7F45+1jbyu/tdSOKJPoRFrTpguJ1tBctc/cDyTsxUFuBlTUqdILhUXml1/\ne0NfSFa9Srw3OJTqejx1AiqZMMkYJBsOxbfZSKWmXP7/UhDEnePmNX3/USNb\nmcEymkC0uFqU4SAAamGrv+vwXxWPOeojpGFRFXrFMbG2gOnx+bN2EV2ebD94\nvlAx\r\n=9XtB\r\n-----END PGP SIGNATURE-----\r\n"},"main":"dist/index.js","scripts":{"test":"mocha -r ts-node/register src/__tests__/*","prepare":"tsc"},"_npmUser":{"name":"szymon.morawski","email":"szymon.morawski@brainhub.pl"},"_npmVersion":"5.5.1","description":"Hadron module for authorisation from OAuth2 providers.","directories":{},"_nodeVersion":"8.6.0","dependencies":{"node-fetch":"2.1.2","@types/node-fetch":"2.1.1"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"chai":"4.1.2","nock":"9.3.3","mocha":"5.2.0","ts-node":"6.1.1","@types/nock":"9.1.3","eslint-config-brainhub":"1.8.1"},"_npmOperationalInternal":{"tmp":"tmp/hadron-oauth_1.0.2_1531410776261_0.9862112868250632","host":"s3://npm-registry-packages"}}},"time":{"created":"2018-07-12T15:52:56.019Z","modified":"2024-10-25T13:04:55.143Z","1.0.2":"2018-07-12T15:52:56.333Z"},"author":{"name":"Brainhub"},"license":"MIT","keywords":["hadron","hadron-oauth"],"description":"Hadron module for authorisation from OAuth2 providers.","maintainers":[{"email":"angjeziorska@gmail.com","name":"angjez"},{"email":"mateusz.jarzebowski.bownik@gmail.com","name":"matt-jb"},{"email":"filip.kublin@brainhub.pl","name":"fkublin"},{"email":"cypherq@gmail.com","name":"benedyktdryl"},{"email":"dariusz.luber@gmail.com","name":"dluber"},{"email":"devops@brainhub.pl","name":"brainhubeu-devops"},{"email":"anna.lach@brainhub.pl","name":"annalach"},{"email":"szymon.morawski@brainhub.pl","name":"szymon.morawski"},{"email":"lukasz.pluszczewski@gmail.com","name":"dyoda"},{"email":"dev@brainhub.pl","name":"brainhubeu-ci"},{"email":"robert_hebel@icloud.com","name":"roberthebel"}],"readme":"## Installation\n\n`npm install --save @brainhubeu/hadron-oauth`\n\n## Overview\n\n`hadron-oauth` is a Hadron utility package to simplify working with OAuth providers, such as Google and Facebook. It provides several utility functions that you can use to make writing OAuth2 authentication quicker and more streamlined.\n\n## Tutorial\n\n### Understanding OAuth flow\n\nThe plan for our authentication flow is as follows:\n\n* The client makes a `GET` request to `/auth/{provider}` to begin the process of authentication.\n* The server redirects the client to a provider consent site.\n* The client receives an auth code.\n* The client makes a `POST` request to `/auth/{provider}/token` to exchange the auth code for an access token.\n\nWe can then use the access token to make further request to the provider's API in order to fetch data about the user (such as their name or email).\n\n### Configuration\n\nWe will need to provide certain information to `hadron-oauth` before we can proceed with the auth process. This information exists in Hadron's config file.\n\n```js\n// oauth.js\nmodule.exports = {\n  google: {\n    clientID: 'keyboard-cat',\n    clientSecret: 'shhh',\n    scope: ['https://www.googleapis.com/auth/userinfo.profile'],\n    redirectUri: 'http://localhost:8081/',\n  },\n};\n```\n\nThe `clientID` and `clientSecret` fields need to be the same as these given to you by your provider (such as the Google API Console). The `redirectUri` must be exactly the same as the one given to your provider.\n\n`scope` is an array of strings defining the scopes your app requires from the user. See the [Google scopes](https://developers.google.com/identity/protocols/googlescopes) and [Facebook scopes](https://developers.facebook.com/docs/facebook-login/permissions/) for details. These can be used later to retrieve relevant data from your provider's APIs about the user.\n\nIn this case, we'll also pretend that there is a front-end dev server at `http://localhost:8081`, however we can just as well redirect the calls back to our own server.\n\nIt's recommended that you exclude this file from your version control or supply the specific config fields through environment variables as this file contains sensitive information.\n\n### Registration\n\nNow that our config is created, we need to create our Hadron app entry point.\n\n```js\n// index.js\nconst hadron = require('@brainhubeu/hadron-core').default;\nconst hadronExpress = require('@brainhubeu/hadron-express');\nconst hadronOauth = require('@brainhubeu/hadron-oauth');\n\nconst express = require('express');\nconst oauthConfig = require('./oauth.js');\n\nconst app = express();\n\nconst config = {\n  oauth: oauthConfig,\n  routes: {\n    root: {\n      path: '/',\n      methods: ['GET'],\n      callback: () => 'Hello!',\n    },\n  },\n};\n\nhadron(app, [hadronExpress, hadronOauth], config).then(() => {\n  app.listen(8080, () => {\n    console.log('Hadron/Express listening on 8080.');\n  });\n});\n```\n\nWe now have access to the OAuth methods through the container.\n\n### Auth code route\n\nLet's create a separate file to store the logic for our route endpoints. We'll first create a route to redirect to the consent screen.\n\n```js\n// routes.js\nconst routes = {\n  googleAuthRequest: {\n    path: '/auth/google',\n    methods: ['GET'],\n    callback: (req, { oauth }) => ({\n      redirect: oauth.google.redirect(),\n    }),\n  },\n};\n\nmodule.exports = routes;\n```\n\n```js\n// index.js\nconst oauthRoutes = require('./routes');\n// ...\nconst config = {\n  routes: {\n    root: {\n      // ...\n    },\n    ...oauthRoutes,\n  },\n};\n```\n\nNow, whenever a client calls the `/auth/google` endpoint, he or she will be redirected to the Google auth consent page.\n\n### Handling the auth code\n\nNow, we'll delve into the client side here for a minute, because we need to send the auth code that the client receives back to the server.\n\nIn the `oauth.js` config file we defined a redirect to our front-end dev server. We now need to send the authorization code from that server back to our app.\n\nWe can do it like this:\n\n```js\n// client side javascript\nconst url = new URL(window.location);\nconst params = new URLSearchParams(url.search);\nconst code = params.get('code');\n\nif (!code) return;\n\nfetch('http://localhost:8080/auth/google/token', {\n  method: 'POST',\n  headers: { 'content-type': 'application/json' },\n  body: JSON.stringify({ code }),\n}).then((res) => {\n  // ...\n});\n```\n\n### Exchanging the code for an access token.\n\nWe'll define another route to exchange the auth code for an access token.\n\n```js\n// routes.js\nconst routes = {\n  googleAuthRequest: {\n    // ...\n  },\n  googleTokenRequest: {\n    path: '/auth/google/token',\n    methods: ['POST'],\n    callback: (req, { oauth }) => {\n      oauth.google.token(req.body.code).then((res) => {\n        console.log(res.access_token);\n        // do things with the token...\n      });\n    },\n  },\n};\n\nmodule.exports = routes;\n```\n\nNow that we have the access token we can implement other features, such as our own authentication. We can also call the Google API in the name of the user to pull any relevant information we need.\n\n## Reference\n\n### Config\n\n#### `google.`\n\n* `clientID: string` - your app id as provided by the [Google API Console](https://console.cloud.google.com/apis/credentials).\n* `clientSecret: string` - your app secret from the Google API Console\n* `scope: string[]` - an array of strings listing the [scope URLs](https://developers.google.com/identity/protocols/googlescopes) you need for your app.\n* `redirectUri: string` - redirect URI for your app, must be exactly the same as the one you chose in Google API Console.\n* `authUrl: ?string` - an optional parameter to provide a different auth URL to Google (for instance if the current one was to stop working). Defaults to `https://accounts.google.com/o/oauth2/v2/auth`.\n* `tokenUrl: ?string` - an optional parameter to provide a different token exchange Google API endpoint. Defaults to `https://www.googleapis.com/oauth2/v4/token`.\n* `responseType: ?string` - if Google was to support a different kind of OAuth authentication flow, we could specify the response type here. Currently, it only supports `code` and so it defaults to that.\n* `grantType: ?string` - similarly to the point above, if Google was to support a different kind of OAuth authentication flow, we could specify the grant type here. Defaults to `authorization_code`.\n\n#### `facebook.`\n\n* `clientID: string` - your app id as provided by the [App Dashboard](https://developers.facebook.com/apps/).\n* `clientSecret: string` - your app secret from the App Dashboard.\n* `scope: string[]` - an array of strings listing [Facebook API scopes](https://developers.facebook.com/docs/facebook-login/permissions/).\n* `redirectUri: string` - the redirect URI for your app, must be the same as in the App Dashboard.\n* `authUrl: ?string` - see above, defaults to `https://www.facebook.com/v3.0/dialog/oauth`.\n* `tokenUrl: ?string` - see above, defaults to `https://graph.facebook.com/v3.0/oauth/access_token`\n* `responseType` - see above, defaults to `code`.\n\n#### `github.`\n\n* `clientID: string` - your app id as provided in the [Github Developer Settings](https://github.com/settings/developers).\n* `clientSecert: string` - your app secret from the Developer Settings.\n* `scope: string[]` - an array of strings listing [Github API scopes](https://developer.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n* `redirectUri: string` - the redirect URI for your app, must be the same as in the Developer Settings.\n* `authUrl: ?string` - see above, defaults to `https://github.com/login/oauth/authorize`.\n* `tokenUrl: ?string` - see above, defaults to `https://github.com/login/oauth/access_token`\n* `allowSignup: ?boolean` - determines whether the user will be able to sign up to Github while authorizing the app, defaults to `true`.\n\n### Methods\n\n#### `oauth.google.`\n\n* `redirect() => string` - parses the config options and returns a redirect URL to the user consent screen.\n* `token(code: string) => Promise` - exchanges the auth code in the first argument for an access token. Returns a promise which resolves to the response from Google.\n\n#### `oauth.facebook.`\n\n* `redirect(state: ?string) => string` - parses the config and returns a redirect URL to the user consent screen. You can provide a state string to secure your app against CSRF ([see here for details](https://developers.facebook.com/docs/facebook-login/security/#stateparam)).\n* `token(code: string) => Promise` - exchanges the auth code in the first argument for an access token. Returns a promise which resolves to the repsonse from Facebook.\n\n#### `oauth.github.`\n\n* `redirect(state: ?string) => string` - parses the config and returns a redirect URL to the user consent screen. You can provide a state string to secure your app against CSRF.\n* `token(code: string, state: ?string) => Promise` - exchanges the auth code in the first argument for an access token. Returns a promise which resolves to the repsonse from Facebook.\n","readmeFilename":"README.md"}