Skip to content

Commit

Permalink
Merge pull request #291 from authts/refactor-logger
Browse files Browse the repository at this point in the history
refactor: additional logger improvements
  • Loading branch information
pamapa authored Jan 13, 2022
2 parents 3e29ee0 + da00870 commit 1d82543
Show file tree
Hide file tree
Showing 58 changed files with 662 additions and 686 deletions.
76 changes: 50 additions & 26 deletions docs/index.md
Original file line number Diff line number Diff line change
@@ -1,47 +1,71 @@
[oidc-client-ts](https://github.com/authts/oidc-client-ts) is a TypeScript library intended to be used by web applications and run in browsers. It provides protocol support for OIDC and OAuth2, as well as management functions for user sessions and access tokens management.

If you are unfamiliar with OpenID Connect, then you should learn the [protocol](https://openid.net/specs/openid-connect-core-1_0.html) first. This library is designed as a spec-compliant protocol library.
If you are unfamiliar with OpenID Connect, then you should learn the
[protocol](https://openid.net/specs/openid-connect-core-1_0.html) first. This
library is designed as a spec-compliant protocol library.

There are two main classes that you might want to use depend on the level at with you use to use the library:
There are two main classes that you might want to use depend on the level at
with you use to use the library:

- [UserManager](classes/UserManager.html) provides a higher level API for signing a user in, signing out, managing the user's claims
- [OidcClient](classes/OidcClient.html) provides the raw OIDC/OAuth2 protocol support

The remainder of this document will primarily focus on the [UserManager](classes/UserManager.html).
- [UserManager](classes/UserManager.html) provides a higher level API for
signing a user in, signing out, managing the user's claims
- [OidcClient](classes/OidcClient.html) provides the raw OIDC/OAuth2 protocol
support

The remainder of this document will primarily focus on the
[UserManager](classes/UserManager.html).

## UserManager

### Configuration

The [UserManager](classes/UserManager.html) constructor requires a settings object as a parameter:
The [UserManager](classes/UserManager.html) constructor requires a settings
object as a parameter:

- [UserManagerSettings](interfaces/UserManagerSettings.html) which extends
- [OidcClientSettings](interfaces/OidcClientSettings.html)

#### Required settings
* [authority](interfaces/OidcClientSettings.html#authority): The URL of the OIDC/OAuth2 provider.
* [client_id](interfaces/OidcClientSettings.html#client_id): Your client application's identifier as registered with the OIDC/OAuth2 provider.
* [redirect_uri](interfaces/OidcClientSettings.html#redirect_uri): The redirect URI of your client application to receive a response from the OIDC/OAuth2 provider.

- [authority](interfaces/OidcClientSettings.html#authority): The URL of the
OIDC/OAuth2 provider.
- [client_id](interfaces/OidcClientSettings.html#client_id): Your client
application's identifier as registered with the OIDC/OAuth2 provider.
- [redirect_uri](interfaces/OidcClientSettings.html#redirect_uri): The redirect
URI of your client application to receive a response from the OIDC/OAuth2
provider.

#### Provider settings if CORS not supported on OIDC/OAuth2 provider metadata endpoint
The [authority](interfaces/OidcClientSettings.html#authority) URL setting is used to make HTTP requests to discover more information about the OIDC/OAuth2 provider and populate a `metadata` property on the settings. If the server does not allow CORS on the metadata endpoint, then these additional settings can be manually configured. These values can be found on the metadata endpoint of the provider:

The [authority](interfaces/OidcClientSettings.html#authority) URL setting is
used to make HTTP requests to discover more information about the OIDC/OAuth2
provider and populate a `metadata` property on the settings. If the server does
not allow CORS on the metadata endpoint, then these additional settings can be
manually configured. These values can be found on the metadata endpoint of the
provider:

- metadata property which contains:
- issuer
- authorization_endpoint
- userinfo_endpoint
- end_session_endpoint
- jwks_uri
- [signingKeys](interfaces/UserManagerSettings.html#signingKeys) (which is the `keys` property of the `jwks_uri` endpoint)
- [metadataSeed](interfaces/UserManagerSettings.html#metadataSeed) can be used to seed or add additional values to the results of the discovery request.
- issuer
- authorization_endpoint
- userinfo_endpoint
- end_session_endpoint
- jwks_uri
- [signingKeys](interfaces/UserManagerSettings.html#signingKeys) (which is the
`keys` property of the `jwks_uri` endpoint)
- [metadataSeed](interfaces/UserManagerSettings.html#metadataSeed) can be used
to seed or add additional values to the results of the discovery request.

### Events
The [UserManager](classes/UserManager.html) will raise various events about the user's session:

The [UserManager](classes/UserManager.html) will raise various events about the
user's session:

- [UserManagerEvents](classes/UserManagerEvents.html) which extends
- [AccessTokenEvents](classes/AccessTokenEvents.html)

To register for the events, there is an `events` property on the [UserManager](classes/UserManager.html) with `addXxx` and `removeXxx` APIs to add/remove callbacks for the events. An example:
To register for the events, there is an `events` property on the
[UserManager](classes/UserManager.html) with `addXxx` and `removeXxx` APIs to
add/remove callbacks for the events. An example:

```javascript
const mgr = new UserManager();
Expand All @@ -50,22 +74,23 @@ mgr.events.addAccessTokenExpiring(function() {
});
```


## User
The [User](classes/User.html) type is returned from the [UserManager](classes/UserManager.html)'s [getUser](classes/UserManager.html#getUser) API.


## Logging
The oidc-client-ts library supports logging. You can set a logger by assigning `Oidc.Log.logger` to anything that supports a `info`, `warn`, and `error` methods that accept a params array. By default, no logger is configured.

The `console` object in the browser supports these, so a common way to easily enable logging in the browser is to simply add this code:
The `console` object in the browser supports these, so a common way to easily
enable logging in the browser is to simply add this code:

```javascript
Oidc.Log.logger = console;
Oidc.Log.setLogger(console);
```

Also, logging has levels so you can control the verbosity by setting the `Oidc.Log.level` to one of `Oidc.Log.NONE`, `Oidc.Log.ERROR`, `Oidc.Log.WARN`, or `Oidc.Log.INFO`. The default is `Oidc.Log.INFO`.

Also, logging has levels so you can control the verbosity by calling
`Oidc.Log.setLevel()` with one of `Oidc.Log.NONE`, `Oidc.Log.ERROR`,
`Oidc.Log.WARN`, or `Oidc.Log.INFO`. The default is `Oidc.Log.INFO`.

## Provider specific settings
Additional provider specific settings may be needed for a flawless operation:
Expand Down Expand Up @@ -97,7 +122,6 @@ This custom state should not be confused with the URL state parameter. The latte

- [React Helper Library](https://github.com/authts/react-oidc-context)


## Training

- [Securing Angular Apps with OpenID and OAuth2](https://noyes.me/ng-openid-oauth2)
5 changes: 5 additions & 0 deletions docs/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,8 @@ removed.
- Compared to 1.x, this function will now throw if _any_ revocation of the
types specified fail. Uses the `revokeTokenTypes` setting when no `types`
are passed.

### [Log](https://authts.github.io/oidc-client-ts/modules/Log.html)

- The getter/setters for `Log.level` and `Log.logger` have been replaced by
`Log.setLevel()` and `Log.setLogger()`.
30 changes: 18 additions & 12 deletions docs/oidc-client-ts.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,30 +171,34 @@ export interface JwtClaims {
}

// @public
export class Log {
export enum Log {
// (undocumented)
static get DEBUG(): number;
DEBUG = 4,
// (undocumented)
static get ERROR(): number;
ERROR = 1,
// (undocumented)
static get INFO(): number;
INFO = 3,
// (undocumented)
static get level(): number;
static set level(value: number);
NONE = 0,
// (undocumented)
static get logger(): ILogger;
static set logger(value: ILogger);
WARN = 2
}

// @public
export namespace Log {
// (undocumented)
static get NONE(): number;
export function reset(): void;
// (undocumented)
static reset(): void;
export function setLevel(value: Log): void;
// (undocumented)
static get WARN(): number;
export function setLogger(value: ILogger): void;
}

// @public
export class Logger {
constructor(name: string);
constructor(_name: string);
// (undocumented)
create(method: string): Logger;
// (undocumented)
debug(...args: unknown[]): void;
// (undocumented)
Expand All @@ -208,6 +212,8 @@ export class Logger {
// (undocumented)
static info(name: string, ...args: unknown[]): void;
// (undocumented)
throw(err: unknown): never;
// (undocumented)
warn(...args: unknown[]): void;
// (undocumented)
static warn(name: string, ...args: unknown[]): void;
Expand Down
3 changes: 2 additions & 1 deletion jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ const collectCoverage = yn(process.env.CI);
export default {
preset: "ts-jest",
clearMocks: true,
setupFilesAfterEnv: ["./test/setup.ts"],
testMatch: ["**/{src,test}/**/*.test.ts"],
testEnvironment: "jsdom",
collectCoverage,
coverageReporters: collectCoverage ? ["lcov"] : ["lcov", "text"],
globals: {
"ts-jest": {
// skip ts-jest type checking, incremental compilation with tsc is much faster
isolatedModules: true
isolatedModules: true,
},
},
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Log, UserManager, settings } from "./sample-settings";
import { log } from "./sample";

Log.logger = console;
Log.level = Log.DEBUG;
Log.setLogger(console);
Log.setLevel(Log.DEBUG);

new UserManager(settings).signinCallback().then(function(user) {
log("signin response success", user);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Log, UserManager, settings } from "./sample-settings";
import { log } from "./sample";

Log.logger = console; // log;
Log.level = Log.DEBUG;
Log.setLogger(console);
Log.setLevel(Log.DEBUG);

new UserManager(settings).signinCallback().then(function(user) {
log("signin response success", user);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Log, UserManager, settings } from "./sample-settings";
import { log } from "./sample";

Log.logger = console;
Log.level = Log.INFO;
Log.setLogger(console);
Log.setLevel(Log.INFO);

// can pass true param and will keep popup window open
new UserManager(settings).signoutCallback().then(function() {
Expand Down
4 changes: 2 additions & 2 deletions samples/Parcel/src/code-flow-identityserver/sample-silent.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Log, UserManager, settings } from "./sample-settings";
import { log } from "./sample";

Log.logger = console;
Log.level = Log.INFO;
Log.setLogger(console);
Log.setLevel(Log.INFO);

new UserManager(settings).signinCallback().then(function(user) {
log("signin callback response success", user);
Expand Down
4 changes: 2 additions & 2 deletions samples/Parcel/src/code-flow-identityserver/sample.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ document.getElementById("popupSignout").addEventListener("click", popupSignout,
///////////////////////////////
// config
///////////////////////////////
Log.logger = console;
Log.level = Log.DEBUG;
Log.setLogger(console);
Log.setLevel(Log.INFO);

function log() {
document.getElementById("out").innerText = "";
Expand Down
4 changes: 2 additions & 2 deletions samples/Parcel/src/oidc-client/sample-callback.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Log, settings } from "./sample-settings";
import { log } from "./sample";

Log.logger = console;
Log.level = Log.INFO;
Log.setLogger(console);
Log.setLevel(Log.INFO);

new OidcClient(settings).processSigninResponse().then(function(response) {
log("signin response success", response);
Expand Down
4 changes: 2 additions & 2 deletions samples/Parcel/src/oidc-client/sample.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ document.getElementById("links").addEventListener("change", toggleLinks, false);
///////////////////////////////
// OidcClient config
///////////////////////////////
Log.logger = console;
Log.level = Log.DEBUG;
Log.setLogger(console);
Log.setLevel(Log.INFO);

function log() {
document.getElementById("out").innerText = "";
Expand Down
4 changes: 2 additions & 2 deletions samples/Parcel/src/user-manager/sample-popup-signin.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Log, UserManager, settings } from "./sample-settings";
import { log } from "./sample";

Log.logger = console;
Log.level = Log.INFO;
Log.setLogger(console);
Log.setLevel(Log.INFO);

new UserManager(settings).signinPopupCallback().then(function() {
log("signin popup callback response success");
Expand Down
4 changes: 2 additions & 2 deletions samples/Parcel/src/user-manager/sample-popup-signout.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Log, UserManager, settings } from "./sample-settings";
import { log } from "./sample";

Log.logger = console;
Log.level = Log.INFO;
Log.setLogger(console);
Log.setLevel(Log.INFO);

new UserManager(settings).signoutPopupCallback(undefined, true).then(function() {
log("signout popup callback response success");
Expand Down
4 changes: 2 additions & 2 deletions samples/Parcel/src/user-manager/sample-silent.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Log, UserManager, settings } from "./sample-settings";
import { log } from "./sample";

Log.logger = console;
Log.level = Log.INFO;
Log.setLogger(console);
Log.setLevel(Log.INFO);

new UserManager(settings).signinSilentCallback().then(function() {
log("signin silent callback response success");
Expand Down
4 changes: 2 additions & 2 deletions samples/Parcel/src/user-manager/sample.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ document.getElementById("popupSignout").addEventListener("click", popupSignout,
///////////////////////////////
// config
///////////////////////////////
Log.logger = console;
Log.level = Log.DEBUG;
Log.setLogger(console);
Log.setLevel(Log.INFO);

function log() {
document.getElementById("out").innerText = "";
Expand Down
9 changes: 5 additions & 4 deletions src/AccessTokenEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ export class AccessTokenEvents {
}

public load(container: User): void {
const logger = this._logger.create("load");
// only register events if there's an access token and it has an expiration
if (container.access_token && container.expires_in !== undefined) {
const duration = container.expires_in;
this._logger.debug("load: access token present, remaining duration:", duration);
logger.debug("access token present, remaining duration:", duration);

if (duration > 0) {
// only register expiring if we still have time
Expand All @@ -36,17 +37,17 @@ export class AccessTokenEvents {
expiring = 1;
}

this._logger.debug("load: registering expiring timer in:", expiring);
logger.debug("registering expiring timer, raising in", expiring, "seconds");
this._expiringTimer.init(expiring);
}
else {
this._logger.debug("load: canceling existing expiring timer because we're past expiration.");
logger.debug("canceling existing expiring timer because we're past expiration.");
this._expiringTimer.cancel();
}

// if it's negative, it will still fire
const expired = duration + 1;
this._logger.debug("load: registering expired timer in:", expired);
logger.debug("registering expired timer, raising in", expired, "seconds");
this._expiredTimer.init(expired);
}
else {
Expand Down
4 changes: 2 additions & 2 deletions src/CheckSessionIFrame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class CheckSessionIFrame {
return;
}

this._logger.debug("start");
this._logger.create("start");

this.stop();

Expand All @@ -94,10 +94,10 @@ export class CheckSessionIFrame {
}

public stop(): void {
this._logger.create("stop");
this._session_state = null;

if (this._timer) {
this._logger.debug("stop");

clearInterval(this._timer);
this._timer = null;
Expand Down
Loading

0 comments on commit 1d82543

Please sign in to comment.