@amedia/user 0.14.91 → 0.14.93

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/README.md +87 -71
  2. package/dist/user.js +23 -3
  3. package/package.json +5 -5
package/README.md CHANGED
@@ -1,51 +1,26 @@
1
- [![Maintainability](https://api.codeclimate.com/v1/badges/7842ee129dc476822359/maintainability)](https://codeclimate.com/repos/609b74f497caf801a000778d/maintainability)
2
- [![Test Coverage](https://api.codeclimate.com/v1/badges/7842ee129dc476822359/test_coverage)](https://codeclimate.com/repos/609b74f497caf801a000778d/test_coverage)
3
-
4
1
  # @amedia/user
5
2
 
6
3
  The goal of this module is to simplify the usage of aID data and services in Amedia frontend code. The module is designed to be used several places on a webpage independently, and the module will ensure that requests from different parts of the webpage are handled in an efficient manner.
7
4
 
8
- An important requirement for this module is Eik. When used in production, this module should always be loaded from an alias in Eik. This is to ensure that all components on a page that uses this module will use same version. The normal way to load the module from Eik is through import maps.
9
-
10
- This module is owned by Team aID. If you, after having read this file, have any questions or comments; we are happy to help on slack #team-aid
11
-
12
5
  # Usage
13
6
 
14
7
  Please be advised that you are required to use ESM in order to use this module.
15
8
 
16
9
  ## Importing the module
17
10
 
18
- Add this module to your project by running `npm install -d @amedia/user`. This will allow for type-hinting, but will not include the implementation. This means you must also set up import maps for loading the actual code. Just point `@amedia/user` to `https://assets.acdn.no/pkg/@amedia/user/v0/user.js`.
19
-
20
- See Ego, Bacchus or Saturn for examples on how to use this module through Eik.
21
-
22
- Once the module is installed, it can be imported in your source code using a standard import like this:
23
-
24
- ```ts
25
- import {
26
- UserDataRequest,
27
- PaywallUnlockRequest,
28
- goToLoginPage,
29
- logout,
30
- ...etc,
31
- } from '@amedia/user';
32
- ```
33
-
34
- When your source code is bundled together for production, it's important that the bundler (rollup, webpack etc.) will use an import map to replace this import with `import {} from https://assets.acdn.no/pkg/@amedia/user/v0/user.js` instead of bundling a hard coded version of the module in your bundled assets. If this happens, the page will end up with different versions of this module, which in time will cause incompatibilities and extra code to download.
35
-
36
- You can read more about Eik on [Slite](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/iexhL4MZn3).
11
+ Add this module to your project by running `npm install -d @amedia/user`. This will allow for type-hinting, and will provide some mock-functionality. To get the actual implementation for production you must swap out `@amedia/user` with `https://assets.acdn.no/pkg/@amedia/user/v0/user.js`. This can be done easily with import-maps. For inspiration, see Ego, Bacchus or Saturn on how to use this module through an Eik plugin. You can read more about Eik on [Slite](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/iexhL4MZn3).
37
12
 
38
13
  ## Mocking
39
14
 
40
15
  When working exclusively on a frontend app, it might be cumbersome to boot the entire aid rig locally for development. To make this easier, the npm package provides a mock for you to use.
41
16
 
42
- **To enable mocked data** you just comment out the eik import. This will cause your bundler to include the mock in the bundle.
17
+ **To enable mocked data** you just comment out the import map translation. This will cause your bundler to include the mocks.
43
18
 
44
19
  Then mocked, you'll be logged in as a user with full access. Check the browser console for information about this persona, other personas available, and how to choose between them.
45
20
 
46
21
  ### Caveats of the mock
47
22
 
48
- This is not intended to be a complete mock as it would've soon required us to reimplement aID in the mock :)
23
+ This is not intended to be a complete mock as it would've soon required us to reimplement most of aID in the mock :)
49
24
 
50
25
  Supported actions:
51
26
 
@@ -63,9 +38,7 @@ Unsupported (will throw Error):
63
38
 
64
39
  The most common use case for aID on newspapers is to get some kind of data about a user, this could be the user's name, some stored preference, access or data that has been derived about the user.
65
40
 
66
- To get user data you first need to create a `new UserDataRequest()`, then specify what data you need and lastly decide if you want to wait until all data is available, or you want to get partial updates.
67
-
68
- This module tries to simplify the model representing various data about the user. We have introduced (and re-used) some concepts that are listed.
41
+ To get user data you first need to create a `new UserDataRequest()` instance, then specify what data you need and lastly decide if you want to wait until all data is available, or you want to get partial updates.
69
42
 
70
43
  ### Data model
71
44
 
@@ -82,21 +55,57 @@ Attributes are data directly related to the user, with the exception of access.
82
55
  | extraData | Record<string,unknown> | Data that has been modelled about the user (gender, ad segments etc. from Nebula) |
83
56
  | privacyPreferences | [PrivacyPreferences](https://github.com/amedia/amedia-user-js/blob/master/src/types.ts#L16) | Privacy preferences set on Min aID. |
84
57
 
85
- Attributes are requested by calling `.withAttributes()` on a `UserDataRequest` with a list of the attributes you need.
58
+ Attributes are requested by calling `.withAttributes(attributes: Array<string>)` on a `UserDataRequest` with a list of the attributes you need.
86
59
 
87
60
  In the response, `attributes` is an object where each requested attribute is an attribute. So you can get the name by accessing `attributes.name` for example.
88
61
 
89
62
  NOTE: Fetching each attribute has a cost, so keep the list to a minimum. Don't request attributes you don't really need.
90
63
 
91
- NOTE2: If you need to know if the current user is an employee, you are encouraged to use data from extraData rather than access as extraData is quicker.
64
+ NOTE2: If you need to know if the current user is an employee, you are encouraged to use data from `extraData` rather than `access` as `extraData` is quicker.
92
65
 
93
66
  #### Storage
94
67
 
95
68
  Storage are namespaces stored in Europa. A namespace is a named set of key value pairs stored for a specific user. An example could be favourite_teams, which could contain team_id as key and timestamp it was stored as favourite as value.
96
69
 
97
- Storage is requested by calling `.withStorage()` on a `UserDataRequest` with a list of namespaces you need.
70
+ Storage is requested by calling `.withStorage(namespaces: Array<string>)` on a `UserDataRequest`. If a namespace does not exist it will be "created" in that you'll get an empty object back. Saving data to it will perform the actual creation.
71
+
72
+ In the response, `storage` is an object with each namespace as an attribute which leads to an object with attributes for each key in the namespace. So you can access `storage.favourite_teams.myteamid` and get the value stored for `teamid` in the `favourite_teams` namespace. This value will be whatever was saved there, but always a string.
73
+
74
+ ```ts
75
+ type Storage = { [namespace: string]: Record<string, string> };
76
+ ```
77
+
78
+ #### Client Storage
79
+
80
+ This works just as [regular storage](#storage), but the namespaces are scoped to oauth clients.
81
+
82
+ Client Storage is requested by calling `.withClientStorage(clientId: string, namespaces: Array<string>)` on a UserDataRequest.
83
+
84
+ In the response, `clientStorage[clientId]` is an object with each namespace as en attribute that works as described above.
98
85
 
99
- In the response, `storage` is an object with each namespace as an attribute which leads to an object with attributes for each key in the namespace. So you can access `storage.favourite_teams.myteamid` and get the value stored for `teamid` in the `favourite_teams` namespace. This value will be whatever was saved there.
86
+ ```ts
87
+ type ClientStorage = { [clientId: string]: Storage };
88
+ ```
89
+
90
+ #### Writing to storage namespaces
91
+
92
+ A namespace is a proxied instance of `Namespace`.
93
+ You access this as any old object, but it provides a save()-method for when to wish to persist this namespace for later use.
94
+
95
+ ```ts
96
+ import { UserDataRequest } from '@amedia/user';
97
+
98
+ const { storage } = await new UserDataRequest()
99
+ .withStorage('my_namespace')
100
+ .fetch();
101
+ storage.my_namespace.my_key = 'my data';
102
+ storage.my_namespace.save();
103
+
104
+ delete storage.my_namespace.my_key;
105
+ storage.my_namespace.save();
106
+ ```
107
+
108
+ In this example, `my_key` in `my_namespace` would be updated to `my data` (and then deleted). Other data would probably be left "untouched". **Meaning**, if this namespace sees a lot of changes outside this instance you may end up overwriting other changes if you delay a lot between reading av writing!
100
109
 
101
110
  #### State
102
111
 
@@ -122,13 +131,14 @@ The most flexible way to get userdata is by subscribing to updates. This is done
122
131
  Full usage example:
123
132
 
124
133
  ```ts
125
- import { UserDataRequest } from '...';
134
+ import { UserDataRequest } from '@amedia/user';
126
135
 
127
136
  const unsubscribe = new UserDataRequest()
128
137
  .withAttributes(['name', 'trackingKey'])
129
- .withStorage(['my_namespace']) // You might know this as Europa
130
- .subscribe(({ attributes, state, storage }) => {
131
- console.log(attributes, state, storage);
138
+ .withStorage(['my_namespace'])
139
+ .withClientStorage('client-id', ['my-client-namespace'])
140
+ .subscribe(({ attributes, state, storage, clientStorage }) => {
141
+ console.log(attributes, state, storage, clientStorage);
132
142
  });
133
143
 
134
144
  // If you wish to unsubscribe from further updates:
@@ -148,14 +158,15 @@ In many use cases it's more convenient to just wait until everything is ready, s
148
158
  Full usage example:
149
159
 
150
160
  ```ts
151
- import { UserDataRequest } from '...';
161
+ import { UserDataRequest } from '@amedia/user';
152
162
 
153
163
  new UserDataRequest()
154
- .withAttributes(['name', 'email'])
155
- .withStorage(['my_namespace']) // You might know this as Europa
164
+ .withAttributes(['name'])
165
+ .withStorage(['my_namespace'])
166
+ .withClientStorage('client-id', ['my-client-namespace'])
156
167
  .fetch()
157
- .then(({ attributes, state, storage }) => {
158
- console.log(attributes, state, storage);
168
+ .then(({ attributes, state, storage, clientStorage }) => {
169
+ console.log(attributes, state, storage, clientStorage);
159
170
  });
160
171
  ```
161
172
 
@@ -163,56 +174,66 @@ Fetch will wait until it has all the data you requested before resolving, unless
163
174
 
164
175
  If you really need to render the user's name or get their uuid etc. as fast as possible, use `.subscribe()`, if not, this is probably easier.
165
176
 
166
- ##### Timeouts
177
+ ##### Timeouts when using fetch
167
178
 
168
179
  Especially poor connections may result in almost eternal wait times - which is no good if your app is locked while waiting on the data. Because of this we have introduced a timeout. A timeout will cause the fetch to reject with FetchTimeoutError.
169
180
 
170
181
  _FetchTimeoutError will include any data we might have gotten before we timed out_
171
182
 
172
183
  ```ts
173
- .catch((e) => {
174
- if (e instanceof FetchTimeoutError) {
175
- console.log(e.partialData);
176
- // Maybe you're able to render your app in a reduced state (perhaps with some partialData) or decide not to render at all.
177
- }
178
- }
184
+ new UserDataRequest()
185
+ .withAttributes(['name'])
186
+ .withStorage(['my_namespace'])
187
+ .fetch()
188
+ .catch((e) => {
189
+ if (e instanceof FetchTimeoutError) {
190
+ console.log(e.partialData);
191
+ // Maybe you're able to render your app in a reduced state (using partialData).
192
+ }
193
+ };
179
194
  ```
180
195
 
181
196
  If you're running a background task and don't mind waiting longer than default (10 seconds), you may set a longer timeout in fetch:
182
197
 
183
198
  ```ts
184
- .fetch({timeout: 60000 /* milliseconds */ })
199
+ new UserDataRequest()
200
+ .withAttributes(['name'])
201
+ .withStorage(['my_namespace'])
202
+ .fetch({ timeout: 60000 /* milliseconds */ });
185
203
  ```
186
204
 
187
205
  This may also be lowered below the default, but network request do take some time, even on fast networks, so don't shoot your app in the foot by lowering it too much.
188
206
 
189
207
  ## Actions
190
208
 
191
- The following methods are actions that the user needs to be able to perform in an environment using logged in users.
209
+ ### `getLoginUrl({requestedUrl: string context: string}): string`
210
+
211
+ Builds and returns the aID login URL. See `goToLoginPage` for details
212
+
213
+ ### `goToLoginPage({requestedUrl: string context: string}): void`
192
214
 
193
- ### `goToLoginPage(requestedUrl: string)`
215
+ Send the user to the aID login page. It will take care of building the correct URL, including your current site domain, so the login page is skinned correctly. By default, the user will be sent back to the current url after login has been completed. You may include a requestedUrl if you need to control where the user should end up.
194
216
 
195
- This action will send the user to the aID login page. It will take care of building the correct URL, including your current site domain, so the login page is skinned correctly.
217
+ **Note**: We also support sending a context string when requesting a login. Please include your app-name or more recognizable string. If your app has multiple places for requesting login, it's nice to include that info as well. Eg: `goToLoginPage({context: my-app_switch-user})`. The context will help us understand where logins originate from to assist in debugging.
196
218
 
197
- You may include a requestedUrl if you need to control where the user should end up after logging in. The default is to send the user back to the current URL where this action was called.
219
+ ### `requestDataRefresh(): void`
198
220
 
199
- ### `logout()`
221
+ If you need to ensure the latest data is available, you may request a data refresh. @amedia/user will look up all data it has in cache and contact various endponints to ensure they are up to date. If you're subscribing to updates, your callback will be executed if anything changes.
200
222
 
201
- This action will log the user out of aID. The logout is global, meaning it will log the session out of all sites and aid.no.
223
+ **Note**: A data refresh will be automatically performed every time the page regains focus (eg. user switches tabs)
202
224
 
203
- ## Updating storage
225
+ ### `logout(): Promise<void>`
204
226
 
205
- If you need to store preferences, favourite teams etc for the user, you can choose between two methods. One will update only the attributes of a namespace that you specify, the other will update everything. The main difference is that if you opt for updating everything, attributes that are present on the backend, but not in the update, will be deleted.
227
+ This action will log the user out of aID. The logout is global, meaning it will log the session out of all sites and aid.no. After logout has completed the promise will resolve, giving your app the opportunity to reset state / reload the page etc.
206
228
 
207
- ### Update changed values (PATCH)
229
+ ### DEPRECATED: `~updateStorage(storage: Storage): void~`
208
230
 
231
+ [See: Writing-to-storage-namespaces](#writing-to-storage-namespaces)
209
232
  The safest way to update a value is to use `updateStorage()`. This will send a `PATCH` to Europa to only update the specified attributes of a namespace, and keep the rest as it is. This reduces concurrency issues where someone could have updated a different attribute after you read the namespace.
210
233
 
211
234
  Example of use:
212
235
 
213
236
  ```ts
214
- import { updateStorage } from '...';
215
-
216
237
  updateStorage({
217
238
  my_namespace: {
218
239
  my: 'data',
@@ -220,17 +241,14 @@ updateStorage({
220
241
  });
221
242
  ```
222
243
 
223
- In the example, only `my` in `my_namespace` would be updated to `data`. If the namespace also contained `{ your: 'loss' }`, this would be kept untouched, so the resulting namespace would now contain `{ my: 'data', your: 'loss' }`.
224
-
225
- ### Update the entire namespace (PUT)
244
+ ### DEPRECATED: `~saveStorage(storage: Storage): void~`
226
245
 
227
- If you're not afraid of concurrency issues, or you need to make sure that old attributes are removed, you should use `saveStorage()`. This works in the same way as `updateStorage()`, but it will send a `PUT` to Europa, which will then make sure that attributes that are stored in the namespaces in the request, but are not a part of the request, will be removed.
246
+ [See: Writing-to-storage-namespaces](#writing-to-storage-namespaces)
247
+ Will send a `PUT` to Europa to update the entire namespace/namespaces, deleting missing data in the process. Please be advised that you may be overwriting updates done by other apps to these namespaces, so it's best to save with a recent namespace if it sees heavy writes :)
228
248
 
229
249
  Example of use:
230
250
 
231
251
  ```ts
232
- import { updateStorage } from '...';
233
-
234
252
  saveStorage({
235
253
  my_namespace: {
236
254
  my: 'data',
@@ -238,8 +256,6 @@ saveStorage({
238
256
  });
239
257
  ```
240
258
 
241
- In the example, `my` in `my_namespace` would be updated to `data`. If the namespace also contained `{ your: 'loss' }`, this would removed, so the resulting namespace would now contain `{ my: 'data' }`.
242
-
243
259
  ## Unlocking the paywall
244
260
 
245
261
  Amedia's sites use a Paywall that's based on a cookie called VSTOKEN that is read by Varnish and used by the content system to decide if the content should be shown to the user or not. If not, the content will load what we call an incentive, a dialogue above the content, that will allow the user to log in and/or buy subscription. The incentive will use `PaywallUnlockRequest` to see if it can somehow grant access to the user.
package/dist/user.js CHANGED
@@ -132,15 +132,35 @@ export class PaywallUnlockRequest {
132
132
  return this;
133
133
  }
134
134
 
135
+ reloadOnAccess() {
136
+ this.reload = true;
137
+ return this;
138
+ }
139
+
135
140
  async tryUnlock() {
136
141
  if (!this.persona.state.isLoggedIn) {
137
142
  return { isLoggedIn: false, hasAccess: false, accessFeatures: [] };
138
143
  }
144
+
145
+ const hasAccess = this.requestedAccessFeatures.every((raf) =>
146
+ this.persona.attributes.access.includes(raf)
147
+ );
148
+ if (hasAccess) {
149
+ if (this.reload) {
150
+ console.log(
151
+ "[@amedia/user PaywallUnlockRequest]: Access granted. Would've performed reload at this time."
152
+ );
153
+ }
154
+ if (this.requestedUrl) {
155
+ console.log(
156
+ `[@amedia/user PaywallUnlockRequest]: Access granted. Would've performed redirect (to '${this.requestedUrl}') at this time.`
157
+ );
158
+ }
159
+ }
160
+
139
161
  return {
140
162
  isLoggedIn: true,
141
- hasAccess: this.requestedAccessFeatures.every((raf) =>
142
- this.persona.attributes.access.includes(raf)
143
- ),
163
+ hasAccess,
144
164
  accessFeatures: this.persona.attributes.access,
145
165
  };
146
166
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.14.91",
3
+ "version": "0.14.93",
4
4
  "description": "Client lib for working with aID user and associated data",
5
5
  "repository": "https://github.com/amedia/amedia-user-js",
6
6
  "author": "Amedia Utvikling (ID og data)",
@@ -52,12 +52,12 @@
52
52
  "@amedia/kragl": "^1.2.3",
53
53
  "@changesets/changelog-github": "^0.4.8",
54
54
  "@changesets/cli": "^2.26.0",
55
- "@eik/esbuild-plugin": "^1.1.27",
55
+ "@eik/esbuild-plugin": "^1.1.28",
56
56
  "@types/jest": "^29.4.0",
57
57
  "@types/node": "^18.11.18",
58
58
  "concurrently": "^7.6.0",
59
59
  "cors": "^2.8.5",
60
- "esbuild": "0.17.4",
60
+ "esbuild": "0.17.5",
61
61
  "express": "^4.18.2",
62
62
  "jest": "^29.4.1",
63
63
  "jest-environment-jsdom": "^29.4.1",
@@ -66,10 +66,10 @@
66
66
  "mockdate": "^3.0.5",
67
67
  "npm-run-all": "^4.1.5",
68
68
  "prettier": "^2.8.3",
69
- "rollup": "3.12.0",
69
+ "rollup": "3.12.1",
70
70
  "rollup-plugin-dts": "5.1.1",
71
71
  "ts-jest": "^29.0.5",
72
72
  "tslib": "^2.5.0",
73
- "typescript": "^4.9.4"
73
+ "typescript": "^4.9.5"
74
74
  }
75
75
  }