@simpleview/sv-auth-client 5.0.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/changelog.md +5 -1
  2. package/package.json +2 -1
  3. package/readme.md +205 -344
package/changelog.md CHANGED
@@ -1,9 +1,13 @@
1
1
  # sv-auth-client changelog
2
2
 
3
+ ## 5.0.0
4
+
5
+ * BREAKING - Directivevs have been changed to export schemaTransformers for GraphQL v16. GraphQL is now a peerDependency with a minimum version.
6
+
3
7
  ## 4.0.0
4
8
 
5
9
  * BREAKING - All directives exported by sv-auth-client have been refactored to have a simpler usage pattern and support new features. To use the latest sv-auth-client you'll likely have to make some small tweaks in how you import those Directives into your project. See the readme for the proper install instructions for the directives.
6
10
  * All directives are now exported by factory functions - `getDirectiveCheckPerm` and `getDirectiveGetUser`
7
11
  * DirectiveCheckPerm - Now supports bindings for returning the state of the users `object_bindings`.
8
12
  * Adds `user.canIds(perm, node_type)` for getting the valid IDs for perm/node_type endpoint.
9
- * Adds `canIds(perm, node_type, bindings)` utility function for getting the valid IDs for a perm/node_type.
13
+ * Adds `canIds(perm, node_type, bindings)` utility function for getting the valid IDs for a perm/node_type.
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@simpleview/sv-auth-client",
3
- "version": "5.0.0",
3
+ "version": "5.0.1",
4
4
  "description": "Client for communicating with sv-auth",
5
5
  "author": "Owen Allen <owenallenaz@gmail.com>",
6
6
  "dependencies": {
7
7
  "@graphql-tools/utils": "8.9.0",
8
8
  "@simpleview/sv-graphql-client": ">=2.0.3",
9
9
  "@simpleview/express-async-handler": "1.0.2",
10
+ "axios": "0.24.0",
10
11
  "graphql-tag": "2.12.6",
11
12
  "jsonwebtoken": "8.5.1"
12
13
  },
package/readme.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # sv-auth-client
2
2
 
3
- Client for communicating with sv-auth. This npm package contains classes and helpers for communicating with the sv-auth graphQL system.
3
+ Client for communicating with sv-auth. This npm package contains classes and helpers for communicating with the sv-auth GraphQL system.
4
4
 
5
5
  Use cases include:
6
6
  * Registering permissions on the auth system for your product.
@@ -10,17 +10,35 @@ Use cases include:
10
10
 
11
11
  [Changelog](changelog.md) - See the latest changes to sv-auth-client.
12
12
 
13
+ ## OS Support
14
+
15
+ The expectation is that this application will be installed in Linux using [sv-kubernetes](https://github.com/simpleviewinc/sv-kubernetes/).
16
+
17
+ ## Prerequisites
18
+
19
+ * [sv-graphql-client](https://github.com/simpleviewinc/sv-graphql-client/)
20
+
13
21
  ## Installation
14
22
 
15
- ```
23
+ Using npm:
24
+ ```bash
16
25
  npm install @simpleview/sv-auth-client
17
26
  ```
18
27
 
28
+ Using yarn:
29
+ ```bash
30
+ yarn install @simpleview/sv-redirects-client
31
+ ```
32
+
33
+ ## Update
34
+
35
+ To update to the latest version, just rerun the install command.
36
+
19
37
  ## Setup
20
38
 
21
39
  For integrating your project with auth, please see the [Setup Instructions](setup.md).
22
40
 
23
- # Package API
41
+ ## Implementation & Usage
24
42
 
25
43
  * [AuthClient](#AuthClient)
26
44
  * [canIds](#canIds)
@@ -28,23 +46,23 @@ For integrating your project with auth, please see the [Setup Instructions](setu
28
46
  * [DirectiveCheckPerm](#DirectiveCheckPerm)
29
47
  * [User](#User)
30
48
 
31
- ## AuthClient
49
+ ### AuthClient
32
50
 
33
51
  The `AuthClient` class is for communicating with the authentication system which provides some caching and ease of use for working with `User` objects.
34
52
 
35
53
  * args
36
- * graphUrl - The URL of graphQL server that you wish to communicate with. Most implementations should likely point to the live graphQL endpoint at https://graphql.simpleviewinc.com/.
54
+ * graphUrl - The URL of the GraphQL server that you wish to communicate with. Most implementations should likely point to the live GraphQL endpoint at https://graphql.simpleviewinc.com/.
37
55
  * cacheDuration - The duration of how long cache entries should remain in the AuthClient cache. Defaults to 1 hour, generally you should not pass this setting unless unit testing.
38
56
 
39
- ### AuthClient.getUser
57
+ #### AuthClient.getUser
40
58
 
41
59
  This method wraps the call to `auth.users_current` in a caching layer to ensure that it's performant and is properly updating if a user's permissions have changed.
42
60
 
43
61
  Generally you will want to make this call very early in your GraphQL stack in order to make the user available on context for all calls to access.
44
62
 
45
63
  * args
46
- * token - string - The jwt token retrieved from the the auth system.
47
- * acct_id - string - The acct_id that you need to retrieve the user for.
64
+ * token - string - The jwt token retrieved from the auth system.
65
+ * acct_id - string - The acct_id the user is accessing.
48
66
  * headers - object - HTTP headers, x-sv-permissionjson can be used for overwriting user permissions in unit tests.
49
67
 
50
68
  Returns `auth_user`.
@@ -56,11 +74,11 @@ const user = authClient.getUser({
56
74
  });
57
75
  ```
58
76
 
59
- ### AuthClient.close
77
+ #### AuthClient.close
60
78
 
61
79
  If you are finished with an AuthClient instance, call `authClient.close()` in order to shut it down. Generally this is only needed in unit tests, otherwise there is an internal `setInterval` which will keep the process open.
62
80
 
63
- ## getTokenFromHeaders
81
+ ### getTokenFromHeaders
64
82
 
65
83
  Extracts the token from the `authorization` header.
66
84
 
@@ -76,7 +94,7 @@ const server = new ApolloServer({
76
94
  });
77
95
  ```
78
96
 
79
- ## AdminPrefix
97
+ ### AdminPrefix
80
98
 
81
99
  `AdminPrefix` can be loaded into the `sv-graphql-client` `GraphServer` to use as a client library for accessing `admin` in GraphQL.
82
100
 
@@ -86,7 +104,7 @@ const { GraphServer } = require("@simpleview/sv-graphql-client");
86
104
  const graphServer = new GraphServer({ graphUrl : GRAPH_URL, prefixes : [AdminPrefix] });
87
105
  ```
88
106
 
89
- ## AuthPrefix
107
+ ### AuthPrefix
90
108
 
91
109
  `AdminPrefix` can be loaded into the `sv-graphql-client` `GraphServer` to use as a client library for accessing `auth` in GraphQL.
92
110
 
@@ -96,17 +114,17 @@ const { GraphServer } = require("@simpleview/sv-graphql-client");
96
114
  const graphServer = new GraphServer({ graphUrl : GRAPH_URL, prefixes : [AuthPrefix] });
97
115
  ```
98
116
 
99
- ## canIds(perm, node_type, bindings)
117
+ ### canIds(perm, node_type, bindings)
100
118
 
101
- This function is identical to `User.canIds` but requires you to pass in the `bindings` manually, it should only be used in cases where you cannot use `DirectiveCheckPerm`. See the documentation for `User.canIds` for how it functions.
119
+ This function is identical to `User.canIds` but requires you to pass in the `bindings` manually, it should only be used in cases where you cannot use `DirectiveCheckPerm`. See the documentation for [`User.canIds`](#User.canIds) for how it functions.
102
120
 
103
- ## DirectiveGetUser
121
+ ### DirectiveGetUser
104
122
 
105
123
  `DirectiveGetUser` can be used to convert a token into a user session.
106
124
 
107
- When using the directive, if your system passes the request headers object on context, you can utilize the header `x-sv-permissionjson` to set the permissions for a specific request. This is can only be used if the token is `sv : true` and it reduces the permissions of that specific request. This makes unit tests easier as you don't need to create roles and users for each specific cross section of permission testing.
125
+ When using the directive, if your system passes the request headers object on context, you can utilize the header `x-sv-permissionjson` to set the permissions for a specific request. This can only be used if the token is `sv : true` and it reduces the permissions of that specific request. This makes unit tests easier as you don't need to create roles and users for each specific cross section of permission testing.
108
126
 
109
- ### Adding DirectiveGetUser
127
+ #### Adding DirectiveGetUser
110
128
 
111
129
  The recommended approach is to split out a separate file in your schema to include the directive.
112
130
 
@@ -125,27 +143,27 @@ module.exports = getDirectiveGetUser({ name : "redirects_checkPerm", graphUrl :
125
143
 
126
144
  If you are not using `schemaLoader`, `getDirectiveGetUser()` returns `{ schemaDirectives, typeDefs }` and you can manually integrate those with your existing directives and schema files.
127
145
 
128
- ### Using DirectiveGetUser
146
+ #### Using DirectiveGetUser
129
147
 
130
- The directive is usually best applied to your root resolver, and requires that your root resolver has a acct_id has a top-level filter parameter. This is best used in conjunction with the `checkPerm` resolver to enforce the permissions on that user.
148
+ The directive is usually best applied to your root resolver, and requires that your root resolver has an acct_id as a top-level filter parameter. This is best used in conjunction with the `checkPerm` resolver to enforce the permissions on that user.
131
149
 
132
150
  In the below example, the top-level prefix converts the token into a user, then the specific resolver enforces permissions based on that user.
133
151
 
134
152
  ```
135
153
  query {
136
154
  prefix(acct_id: String): prefix_query @prefix_getUser
137
-
155
+
138
156
  type prefix_query {
139
157
  some_endpoint: some_result @prefix_checkPerm(sv: true)
140
158
  }
141
159
  }
142
160
  ```
143
161
 
144
- ## DirectiveCheckPerm
162
+ ### DirectiveCheckPerm
145
163
 
146
164
  `DirectiveCheckPerm` can be used to enforce permissions to access a resolver. It can enforce permissions based on `sv`, `permissions` or retrieve `object_bindings`.
147
165
 
148
- ### Adding the Directive
166
+ #### Adding the Directive
149
167
  The recommended approach is to split out a separate file in your schema to include the directive.
150
168
 
151
169
  Note: You will need to provide `name`, which should be `PREFIX_checkPerm` and `graphUrl` which should point to the version of auth you are accessing.
@@ -163,12 +181,12 @@ module.exports = getDirectiveCheckPerm({ name : "redirects_checkPerm", graphUrl
163
181
 
164
182
  If you are not using `schemaLoader`, `getDirectiveGetUser()` returns `{ schemaDirectives, typeDefs }` and you can manually integrate those with your existing directives and schema files.
165
183
 
166
- ### Using the directive
184
+ #### Using the directive
167
185
 
168
186
  * perms - [String] - An array of permissions this endpoint requires.
169
187
  * sv - Boolean - Whether this endpoint requires an SV user.
170
188
  * bindings
171
- * perms - [String] - The permissions for bindings to return
189
+ * perms - [String] - The permissions for bindings to return.
172
190
  * node_types - [String] - The node_types to return binding information on.
173
191
 
174
192
  ```
@@ -186,9 +204,9 @@ query {
186
204
  }
187
205
  ```
188
206
 
189
- ## User
207
+ ### User
190
208
 
191
- `User` is is returned by `AuthClient.getUser` but it can also be used without `AuthClient` when you want to convert the return from `auth.current` into a user which you wish to check permissions on.
209
+ `User` is returned by `AuthClient.getUser` but it can also be used without `AuthClient` when you want to convert the return from `auth.current` into a user which you wish to check permissions on.
192
210
 
193
211
  ```js
194
212
  const { User } = require("@simpleview/sv-auth-client");
@@ -206,17 +224,17 @@ const user = new User(result.doc);
206
224
  user.can(["some.perm.name"]);
207
225
  ```
208
226
 
209
- ### User.can
227
+ #### User.can
210
228
 
211
- * perms - array of strings - Returns boolean whether user has all requested permissions.
229
+ * perms - array of strings - Returns boolean as to whether the user has all requested permissions.
212
230
 
213
231
  ```js
214
232
  const allow = user.can(["cms.something.another", "cms.another.permission"]);
215
233
  ```
216
234
 
217
- ### User.canIds
235
+ #### User.canIds
218
236
 
219
- This function is used for assisting in filtering down queries based on what IDs a user has access to for a given permission and node_type. In order to use this function you must specify `bindings` in the `DirectiveCheckPerm` for the graphql endpoint being executed. If you are not using that mechanic, then use the generic `canIds` function rather than the `User.canIds` variant.
237
+ This function is used for assisting in filtering down queries based on what IDs a user has access to for a given permission and node_type. In order to use this function you must specify `bindings` in the `DirectiveCheckPerm` for the GraphQL endpoint being executed. If you are not using that mechanic, then use the generic `canIds` function rather than the `User.canIds` variant.
220
238
 
221
239
  Returns `true` if the user has root access to this permission/node_type.
222
240
 
@@ -224,7 +242,7 @@ Returns `false` if the user lacks all access to this permission/node_type. Note,
224
242
 
225
243
  Returns `string[]` of ids if the user has object bindings.
226
244
 
227
- * perm - string - Name of the permission
245
+ * perm - string - Name of the permission.
228
246
  * node_type - string - Name of the node_type to return the ids for.
229
247
 
230
248
  ```js
@@ -245,323 +263,166 @@ const result = await sqlQuery(`
245
263
  })
246
264
  ```
247
265
 
248
- ### User.toPlain
266
+ #### User.toPlain
249
267
 
250
268
  Convert the `User` object back to a plain JS object.
251
269
 
252
- # GraphQL Endpoints
253
-
254
- This section is provided to provide additional information about the GraphQL endpoints. To see the input parameters and output of each endpoint, please view the Schema in the GraphQL Explorer at https://graphql.simpleviewinc.com/.
255
-
256
-
257
- ## auth_query
258
- - **accounts**
259
- - Returns an array of accounts containing associated users and roles.
260
- - If the user is not an SV employee, they will only receive the accounts they have access to. If they are an SV employee they will receive all accounts.
261
- - See schema browser for filters/options.
262
- - Bearer token must be provided in Authorization header.
263
- ```
264
- query {
265
- auth {
266
- accounts {
267
- count
268
- docs {
269
- name
270
- active
271
- }
272
- }
273
- }
274
- }
275
- ```
276
-
277
- - **account_public**
278
- - Returns a single account, able to be filtered by 'name' or 'acct_id'.
279
- - Does not require a token, publically accessible.
280
- ```
281
- query {
282
- auth {
283
- account_public(filter: { name : 'test' }) {
284
- success
285
- message
286
- doc {
287
- acct_id
288
- name
289
- label
290
- }
291
- }
292
- }
293
- }
294
- ```
295
-
296
- - **current**
297
- - Retrieve the current user and their permissions for the specified account.
298
- - Returns a token invalid message if returned user is not valid for that account or the token is invalid.
299
- - This does not refresh the token.
300
- - Bearer token must be provided in Authorization header.
301
- ```
302
- query {
303
- auth {
304
- current(acct_id : "0") {
305
- success
306
- message
307
- doc {
308
- firstname
309
- lastname
310
- }
311
- }
312
- }
313
- }
314
- ```
315
-
316
- - **check_token_cache**
317
- - Internal method used for validating caches. Should not be used in normal integrations.
318
- - Validates the provided token and checks the cache to verify it is stale and needs to be revalidated.
319
- - Success is true if the user exists and the cache entry is valid.
320
- - This does not refresh the token.
321
- - Bearer token must be provided in Authorization header.
322
- ```
323
- query {
324
- auth {
325
- check_token_cache(date : "2019-03-15T23:51:17.019Z", acct_id : "0") {
326
- success
327
- message
328
- }
329
- }
330
- }
331
- ```
332
-
333
- - **login**
334
- - Provided an email and password, logs a user in by returning a token.
335
- - Returns an invalid credentials error if login fails.
336
- ```
337
- query {
338
- auth {
339
- login(email: "test0@test.com", password : "test"){
340
- token
341
- message
342
- }
343
- }
344
- }
345
- ```
346
-
347
- - **login_google**
348
- - Converts a Google OAuth token into an auth token.
349
- - Returns an invalid credentials error if login fails.
350
-
351
- - **login_service_account**
352
- - Login utilizing a GCP service account. The user will be granted SV permissions.
353
- - To obtain the credentials you will need the email and private_key from the service account. The `private_key` comes from the `private_key` field from the `.json` keyfile for the service account.
354
-
355
- - **refresh_token**
356
- - Converts a refresh_token received from a login endpoint into a regular token.
357
- - The refresh_token is retrieved from a login attempt and can be stored long term in a secure location to exchange for a normal token at anytime.
358
-
359
- ## auth_mutation
360
- - **accounts_upsert**
361
- - Provided an `acct_id` and account data, updates the associated account or inserts one if it does not exist.
362
- - This endpoint is restricted to SV employees only.
363
- - Bearer token must be provided in Authorization header.
364
- ```
365
- mutation {
366
- auth {
367
- accounts_upsert(input : { acct_id : "999", name : "Test Account", active : true }) {
368
- success
369
- message
370
- doc {
371
- id
372
- }
373
- }
374
- }
375
- }
376
- ```
377
-
378
- - **reset_password_start**
379
- - Starts the process for reseting a user's password by sending an password reset email to the user.
380
- - Sent email contains a reset link that expires after 24 hours.
381
- - Returns a the resulting error if password reset email fails to send. See [sv-email-client](https://github.com/simpleviewinc/sv-email-client) for more info on email errors.
382
- ```
383
- mutation {
384
- auth {
385
- reset_password_start(email : "test0@test.com", redirectUrl : "http://google.com") {
386
- success
387
- message
388
- }
389
- }
390
- }
391
- ```
392
-
393
- - **update_password**
394
- - Updates a user's password.
395
- - Requires a password reset token and a new password that is 8 characters or longer and doesn't not match a too-simple password DB.
396
- - Passwords are stored salted, hashed, and are irretrievable.
397
- ```
398
- mutation {
399
- auth {
400
- update_password(token : "XXXXXXXXXX", new_pass : "secure_password") {
401
- success
402
- message
403
- }
404
- }
405
- }
406
- ```
407
-
408
- ## admin_query
409
- - **products**
410
- - Returns all products and possible permissions for that product, for an account.
411
- - See schema browser for filters/options.
412
- ```
413
- query {
414
- admin(acct_id : "0") {
415
- products {
416
- count
417
- docs {
418
- name
419
- }
420
- }
421
- }
422
- }
423
- ```
424
-
425
- - **roles**
426
- - Returns all roles for an account.
427
- - See schema browser for filters/options.
428
- ```
429
- query {
430
- admin(acct_id : "0") {
431
- roles {
432
- count
433
- docs {
434
- name
435
- description
436
- }
437
- }
438
- }
439
- }
440
- ```
441
-
442
-
443
- - **users**
444
- - Returns all users on an account.
445
- - See schema browser for filters/options.
446
- ```
447
- query {
448
- admin(acct_id : "0") {
449
- users {
450
- count
451
- docs {
452
- firstname
453
- lastname
454
- }
455
- }
456
- }
457
- }
458
- ```
459
-
460
- ## admin_mutation
461
- - **products_upsert**
462
- - Provided an `acct_id` and product data, updates the associated product or inserts one if it does not exist.
463
- - This endpoint is used to define all possible permissions associated with a product belonging to an account. This is to say that possible permissions can vary from account to account for the same product.
464
- - This call should be made anytime the possible permissions for an account's product have changed.
465
- - This call can only be made by an `sv` user.
466
- - The permission object has a strict structure that must be followed.
467
- - Each permission starts with the product name and then drills down through `branch` permissions until it reaches a `leaf` permission.
468
- - If you have a permission called `product1.group1.group2.perm1` then `product1` must be the exact `name` of the product. `product1.group1`, `product1.group1.group2` and `product1.group1.group2.perm1` must all have their own entries in the array.
469
- - In the above example the permission `product1.group1` and `product1.group1.group2` are `branch` permissions. They must have a label and CANNOT have a permType. These branch permissions are used solely for organization and assisting the user in understanding your permission structure.
470
- - In the above example the permission `product1.group1.group2.perm1` is a `leaf` permission and must have a `permType`.
471
- - The order of the permissions in the array does not matter, but keeping them in a logical order in your code is preferable for your own sanity.
472
- - The product name must be all lowercase letters, numbers and dashes.
473
- - The permission name must be all lowercase letters, numbers and dashes separated by periods.
474
- - For each permission the permType must be `write`, `read`, or `remove`.
475
- - Description is optional. If specified the `leaf` or `branch` permission will received a tooltip in the UI to assist the user in understanding the permission or group.
476
- ```
477
- mutation {
478
- admin(acct_id : "0") {
479
- products_upsert(input: { name : "my_product", label : "Product", permissions : [
480
- { name : "prd.perm", label : "Permission Group" },
481
- { name : "prd.perm.read", label : "Permission - Read", description : "This is a read permission", permType : "read" },
482
- { name : "prd.perm.write", label : "Permission - Write", description : "This is a write permission", permType : "write" },
483
- { name : "prd.perm.remove", label : "Permission - Remove", description : "This is a remove permission", permType : "remove" },
484
- { name : "prd.group", label : "Another Group" },
485
- { name : "prd.group.nested", label : "A group on a group" },
486
- { name : "prd.group.nested.read", label : "Nested read permission", description : "Grants the user read on X", permType : "read" }
487
- ]}){
488
- success
489
- message
490
- }
491
- }
492
- }
493
- ```
494
-
495
- - **roles_upsert**
496
- - Provided an `id`, updates the associated role or inserts one if it does not exist.
497
- ```
498
- mutation {
499
- admin(acct_id : "0") {
500
- roles_upsert(input : { name : "Nav Admin", description : "Like a boss", permissions : [
501
- "cms.nav.primary.read",
502
- "cms.nav.primary.write",
503
- "cms.nav.primary.remove",
504
- "cms.nav.secondary.read",
505
- "cms.nav.secondary.write",
506
- "cms.nav.secondary.remove"
507
- ]}) {
508
- success
509
- message
510
- doc {
511
- id
512
- }
513
- }
514
- }
515
- }
516
- ```
517
-
518
- - **roles_remove**
519
- - Deletes roles from the system.
520
- - Take care not to call this endpoint without any filters as this will hard delete all roles on the account.
521
- ```
522
- mutation {
523
- admin(acct_id : "0") {
524
- roles_remove(filter : { id : "5c8c3725df622c0064491fc9" }) {
525
- success
526
- message
527
- }
528
- }
529
- }
530
- ```
531
-
532
- - **users_upsert**
533
- - Provided an `email` and user data, updates the associated user or inserts one if it does not exist.
534
- - This endpoint will send an invitational email to the provided email address.
535
- ```
536
- mutation {
537
- admin(acct_id : "0") {
538
- users_upsert(input : { email : "test@test.com", firstname : "Test", lastname : "User", active : true }) {
539
- success
540
- message
541
- doc {
542
- id
543
- }
544
- }
545
- }
546
- }
547
- ```
548
-
549
- - **users_remove**
550
- - Deletes users from the system.
551
- - Take care not to call this endpoint without any filters as this will hard delete all users on the account.
552
- ```
553
- mutation {
554
- admin(acct_id : "0") {
555
- users_remove(filter : { id : "5c8c37b5df622c0064491fca" }) {
556
- success
557
- message
558
- }
559
- }
560
- }
561
- ```
562
270
 
563
- # Development
271
+
272
+
273
+ ### OAuth 2.0
274
+
275
+ This is a library of functions to enable a product application to authenticate a user using the OAuth 2.0 framework. This works by handshaking codes and challenge tokens between the product and auth and uses the auth login to generate the access tokens for the product. There is a separate class for Express but Express is not required to use OAuth 2.0 authentication.
276
+
277
+ * User visits product application page
278
+ * If there is a session with a token and refresh token then serves content
279
+ * Creates `state` random string and stores in session
280
+ * Creates `code_verifier` random string and stores in session
281
+ * Redirects to auth `/oauth2/login/` endpoint passing:
282
+ * `response_type` - must be "code"
283
+ * `code_challenge_method` - must be "S256"
284
+ * `client_id` - The `client_id` of the application. e.g. `admin` or `cms`. This id should be registered with auth as an `oauth_client`.
285
+ * `redirect_uri` - The url which auth will redirect to upon successful login or if already logged in. This should match the `redirect_uri` registered with auth as an `oauth_client`. e.g. `https://test-account.admin.simpleviewinc.com/oauth2/callback/`.
286
+ * `state` - Generated above
287
+ * `code_challenge` - `Base64(SHA256(code_verifier))`
288
+ * `sv_auth_params` - JSON string containing an object. The properties of this object are added to the auth login url as extra parameters. This can be used to add e.g. the `account_name` or the `product`.
289
+ * If not logged in then redirects to auth login with redirectUrl of `/oauth2/login/`
290
+ * If logged in:
291
+ * Stores `client_id`, `code_challenge`, `date`, `refresh_token` and `code` which is random generated string
292
+ * Redirects to passed in `redirect_uri` passing back `code` and `state`
293
+ * Application callback page verifies `state` in query is same as `state` stored in session
294
+ * Calls auth `/oauth2/token/` endpoint as a `POST x-www-form-urlencoded` with form data:
295
+ * `grant_type` - Must be "authorization_code"
296
+ * `client_id` - The `client_id` of the application. e.g. `admin` or `cms`. This id should be registered with auth as an `oauth_client`.
297
+ * `redirect_uri` - The url which auth will redirect to upon successful login or if already logged in. This should match the `redirect_uri` registered with auth as an `oauth_client`. e.g. `https://test-account.admin.simpleviewinc.com/oauth2/callback/`.
298
+ * `code` - As passed in query
299
+ * `code_verifier` - As stored in session
300
+ * An `access_token` and `refresh_token` are returned which should be stored in the client-side session
301
+ * The user is then redirected back to the original product application page
302
+
303
+ To proxy requests to GraphQL including a user's token:
304
+
305
+ * User visits product application page which runs a query
306
+ * A POST request occurs to e.g. `https://client.simpleviewapp.com/graphql/` for some query
307
+ * Application should validate is POST and if origin and/or referer headers exist they match the expected domain
308
+ * If the `access_token` is nearing expiration:
309
+ * `POST x-www-form-urlencoded` request to auth `/oauth2/token/` route with form data:
310
+ * `grant_type` - Must be "refresh_token"
311
+ * `refresh_token` - This should be a valid refresh token previously obtained from auth
312
+ * An `access_token` and `refresh_token` are returned which should be stored in the client-side session
313
+ * Proxy request to upstream `graphql.simpleviewinc.com` adding users `access_token` from client-side session as `header authorization Bearer`
314
+
315
+ The functions outlined below ease the burden of the flows described above. For Express there is a separate class which significantly eases implementation. It is the responsibility of the product application to create a valid redirect uri such as `/oauth2/callback/` in their application as well as register the client as an `oauth_client`.
316
+
317
+ #### oauth2CreateRandomKey
318
+
319
+ This function creates a random key for use as the `state` or `code_verifier`.
320
+
321
+ This function returns a string and has no parameters.
322
+
323
+ #### oauth2CreateKeyHash
324
+
325
+ This function creates a hash of the passed in string. This can be used to create a `code_challenge` from the `code_verifier` for passing to the auth login.
326
+
327
+ #### oauth2CreateLoginUrl
328
+
329
+ This function creates a login url with the required OAuth 2.0 parameters.
330
+
331
+ Returns a url to `/oauth2/login` for auth.
332
+
333
+ * args
334
+ * `authUrl` - optional string - The URL of the auth system the website should utilise. Defaults to the live auth system. If you need to reference another system you can pass it here. Usually only used when testing in non-production environments.
335
+ * `client_id` - string - The `client_id` of the application. e.g. `admin` or `cms`. This id should be registered with auth as an `oauth_client`.
336
+ * `redirect_uri` - string - The url which auth will redirect to upon successful login or if already logged in. This should match the `redirect_uri` registered with auth as an `oauth_client`. e.g. `https://test-account.admin.simpleviewinc.com/oauth2/callback/`.
337
+ * `sv_auth_params` - optional object - The properties of this object are added to the auth login url as extra parameters. This can be used to add e.g. the `account_name` or the `product`.
338
+ * `state` - string - This is an opaque value used by the product application to maintain state between the request and callback. This value is included by auth when redirecting back to the product. This parameter should be used to prevent cross-site request forgery.
339
+ * `code_verifier` - string - This is a random key which should be generated from `oauth2CreateRandomKey`. This key is hashed using `oauth2CreateKeyHash` and passed as a `code_challenge`.
340
+
341
+ #### oauth2CreateLogoutUrl
342
+
343
+ This function creates a logout url to log the user out of auth and then redirect back to the auth login.
344
+
345
+ * args
346
+ * `authUrl` - optional string - The URL of the auth system the website should utilise. Defaults to the live auth system. If you need to reference another system you can pass it here. Usually only used when testing in non-production environments.
347
+ * `redirect_uri` - string - The url which auth will redirect to upon successful login. Usually this is the current url. e.g. `https://test-account.admin.simpleviewinc.com/`.
348
+ * `sv_auth_params` - optional object - The properties of this object are added to the auth login url as extra parameters. This can be used to add e.g. the `account_name` or the `product`.
349
+
350
+ #### oauth2GetTokens
351
+
352
+ This function calls the `/oauth2/token` route on auth. This is used for authorising the `code` in the callback.
353
+
354
+ When authorising the code the route checks that the `client_id` and the `redirect_uri` are valid for the client. The `code_verifier` is then hashed and the new hash and code are then checked that we have a previously stored `code` and `code_challenge` which is still valid. This call must be made within five minutes of the original login call which stores the challenge.
355
+
356
+ Returns a `token` and `refresh_token`.
357
+
358
+ * args
359
+ * `authUrl` - optional string - The URL of the auth system the website should utilise. Defaults to the live auth system. If you need to reference another system you can pass it here. Usually only used when testing in non-production environments.
360
+ * `client_id` - string - The `client_id` of the application. e.g. `admin` or `cms`. This id should be registered with auth as an `oauth_client`.
361
+ * `redirect_uri` - string - The url which auth will redirect to upon successful login or if already logged in. This should match the `redirect_uri` registered with auth as an `oauth_client`. e.g. `https://test-account.admin.simpleviewinc.com/oauth2/callback/`.
362
+ * `code` - string - This should have been previously passed from auth to the callback.
363
+ * `code_verifier` - string - This is a random key which should be generated from `oauth2CreateRandomKey`. This should have been stored in the session.
364
+
365
+ #### oauth2GetTokensFromRefresh
366
+
367
+ This function calls the `/oauth2/token` route on auth. This is used for refreshing tokens.
368
+
369
+ When requesting new tokens the route checks the validity of the `refresh_token`.
370
+
371
+ Returns a token and refresh_token.
372
+
373
+ * args
374
+ * `authUrl` - optional string - The URL of the auth system the website should utilise. Defaults to the live auth system. If you need to reference another system you can pass it here. Usually only used when testing in non-production environments.
375
+ * `refresh_token` - string - This should be a valid refresh token previously obtained from auth.
376
+
377
+ ### OAuth2Express
378
+
379
+ The OAuth2Express class provides a simple interface to allow products using Express to easily add OAuth 2.0 authentication with auth. See the [sv-auth](https://github.com/simpleviewinc/sv-auth) readme for sample usage.
380
+
381
+ * `args`
382
+ * `authUrl` - optional string - The URL of the auth system the website should utilise. Defaults to the live auth system. If you need to reference another system you can pass it here. Usually only used when testing in non-production environments.
383
+ * `client_id` - string - The `client_id` of the application. e.g. `admin` or `cms`. This id should be registered with auth as an `oauth_client`.
384
+ * `callbackPath` - optional string - The path that is registered as a callback route. Defaults to `/oauth2/callback/`.
385
+ * `logoutPath` - optional string - The path that is registered as a logout route. Defaults to `/logout/`.
386
+ * `createParams` - optional function - When executed with `req` as a parameter, returns an object containing any parameters which are to be passed to the auth login such as `acct_id`, `account_name` and `product`. Defaults to `undefined` which will pass no extra parameters.
387
+ * `sessionKey` - optional string - Key to store the declared session. Defaults to `session`.
388
+
389
+ #### OAuth2Express.middleware
390
+
391
+ This method is an express middleware function designed to wrap any private routes. It takes the same parameters as an Express route `(req, res, next)`.
392
+
393
+ If there is currently a user token in the session and it is older than a day, it will try to refresh the token.
394
+
395
+ If there is no user session then the user is redirected to the auth login.
396
+
397
+ If the above exceptions do not apply then the `next` method is run to move Express to the function for the route.
398
+
399
+ #### OAuth2Express.callback
400
+
401
+ This method must be registered on the callback route. It takes the same parameters as an Express route `(req, res)`.
402
+
403
+ It obtains a `token`, `refresh_token` and user from auth, stores them in the session and then redirects the user back to the original path.
404
+
405
+ #### OAuth2Express.logout
406
+
407
+ This method must be registered on the logout route. It takes the same parameters as an Express route `(req, res)`.
408
+
409
+ It deletes the session entry and redirects the user to the auth logout route, which logs the user out from auth and then redirects to the auth login.
410
+
411
+ #### OAuth2Express.applyMiddleware
412
+
413
+ This is a helper method which registers the `callback` and `logout` functions on the `callbackPath` and `logoutPath` respectively.
414
+
415
+ ## Development
564
416
 
565
417
  * Enter dev environment - `sudo npm run docker`
566
418
  * Test - `npm test`
567
- * Publish - `sudo npm run publish SEMVER`
419
+ * Publish - `sudo npm run publish SEMVER`
420
+
421
+ ## Related Documentation
422
+
423
+ * [sv-graphql-client](https://github.com/simpleviewinc/sv-graphql-client/)
424
+ * [sv-auth](https://github.com/simpleviewinc/sv-auth/)
425
+
426
+ ## Troubleshooting
427
+
428
+ For any assistance please reach out on the [sv-auth](https://simpleview-workspace.slack.com/archives/CUBJGR4SH) Slack channel.