Full Code of skoruba/react-oidc-client-js for AI

master 8035229b34a9 cached
33 files
31.0 KB
9.0k tokens
32 symbols
1 requests
Download .txt
Repository: skoruba/react-oidc-client-js
Branch: master
Commit: 8035229b34a9
Files: 33
Total size: 31.0 KB

Directory structure:
gitextract_ato4xgph/

├── .gitignore
├── LICENSE
├── README.md
├── appveyor.yml
├── docs/
│   └── README.md
└── src/
    ├── .gitignore
    ├── package.json
    ├── public/
    │   ├── index.html
    │   ├── manifest.json
    │   ├── signin-callback.html
    │   └── silent-renew.html
    ├── src/
    │   ├── components/
    │   │   ├── AppContent.tsx
    │   │   ├── AuthContent.tsx
    │   │   ├── Buttons.test.tsx
    │   │   ├── Buttons.tsx
    │   │   ├── Header.test.tsx
    │   │   ├── Header.tsx
    │   │   ├── JsonTreeViewer.tsx
    │   │   └── __snapshots__/
    │   │       ├── Buttons.test.tsx.snap
    │   │       └── Header.test.tsx.snap
    │   ├── containers/
    │   │   ├── App.css
    │   │   ├── App.test.tsx
    │   │   └── App.tsx
    │   ├── helpers/
    │   │   └── Constants.ts
    │   ├── index.css
    │   ├── index.tsx
    │   ├── react-app-env.d.ts
    │   ├── registerServiceWorker.ts
    │   ├── services/
    │   │   ├── ApiService.ts
    │   │   └── AuthService.ts
    │   └── setupTests.ts
    ├── tsconfig.json
    └── tslint.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/

# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# Visual Studio 2017 auto generated files
Generated\ Files/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUNIT
*.VisualState.xml
TestResult.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

# Benchmark Results
BenchmarkDotNet.Artifacts/

# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json

# StyleCop
StyleCopReport.xml

# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb

# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap

# Visual Studio Trace Files
*.e2e

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# JustCode is a .NET coding add-in
.JustCode

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json

# Visual Studio code coverage results
*.coverage
*.coveragexml

# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj

# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets

# Microsoft Azure Build Output
csx/
*.build.csdef

# Microsoft Azure Emulator
ecf/
rcf/

# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx

# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/

# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs

# Including strong name files can present a security risk 
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk

# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak

# SQL Server files
*.mdf
*.ldf
*.ndf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser

# Microsoft Fakes
FakesAssemblies/

# GhostDoc plugin setting file
*.GhostDoc.xml

# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt

# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw

# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions

# Paket dependency manager
.paket/paket.exe
paket-files/

# FAKE - F# Make
.fake/

# JetBrains Rider
.idea/
*.sln.iml

# CodeRush
.cr/

# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config

# Tabs Studio
*.tss

# Telerik's JustMock configuration file
*.jmconfig

# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

# OpenCover UI analysis results
OpenCover/

# Azure Stream Analytics local run output 
ASALocalRun/

# MSBuild Binary and Structured Log
*.binlog

# NVidia Nsight GPU debugger configuration file
*.nvuser

# MFractors (Xamarin productivity tool) working folder 
.mfractor/


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2018 Jan Škoruba

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:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

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.


================================================
FILE: README.md
================================================
![Logo](docs/Images/Skoruba-Logo-ReadMe.png)

# React-oidc-client-js

> OpenID Connect (OIDC) client with React and typescript

- This is sample application that contains [oidc-client-js](https://github.com/IdentityModel/oidc-client-js) and `React` with `Typescript`.

- The application is based on `create-react-app` - [Create React App](https://github.com/facebook/create-react-app)

## ℹ️ Project status: Not maintained

This project is no longer maintained.

It demonstrates a legacy approach where access tokens are stored in
`localStorage` / `sessionStorage`, which is **no longer considered secure**
for modern SPA applications.

👉 **Current recommendation:**  
Use the **Backend for Frontend (BFF) pattern**, where tokens are handled
server-side and never exposed to the browser.

# Installation

## Cloning app

- `git clone https://github.com/skoruba/react-oidc-client-js.git`
- `cd src/`

## Install dependecies

- Install dependecies - `yarn install`

## Running app

- `yarn start` - start the web server that is running on [http://localhost:4200](http://localhost:4200)

- The application is connected to `OpenID Connect Provider` that is running on [https://demo.identityserver.io/](https://demo.identityserver.io/)
- This STS has configured a SPA client to run on http://localhost:4200, therefore a sample application will be running on this port `4200`.

## App preview

![Logo](docs/Images/react-oidc-client-screenshot.png)


================================================
FILE: appveyor.yml
================================================
environment:
  matrix:
    - nodejs_version: '12'
    - nodejs_version: '10'
    - nodejs_version: '8'
install:
  - ps: Install-Product node $env:nodejs_version
  - npm install --global npm@latest
  - set PATH=%APPDATA%\npm;%PATH%
  - npm install -g create-react-app
  - npm install
matrix:
  fast_finish: true
build: off
shallow_clone: true
test_script:
  - node --version
  - npm --version
  - cd src/
  - npm install -g create-react-app
  - npm install
  - npm test
cache:
  - '%APPDATA%\npm-cache'


================================================
FILE: docs/README.md
================================================
![Logo](Images/Skoruba-Logo-ReadMe.png)

# react-oidc-client-js docs


================================================
FILE: src/.gitignore
================================================
# See https://help.github.com/ignore-files/ for more about ignoring files.

# dependencies
/node_modules

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*


================================================
FILE: src/package.json
================================================
{
  "name": "react-oidc-client-js",
  "description": "OpenID Connect (OIDC) javascript client with React",
  "version": "3.0.0",
  "dependencies": {
    "axios": "0.19.2",
    "core-js": "3.6.5",
    "bootstrap": "4.5.0",
    "enzyme": "3.11.0",
    "enzyme-adapter-react-16": "1.15.2",
    "oidc-client": "1.10.1",
    "ramda": "0.27.0",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-json-tree": "0.11.2",
    "react-scripts": "3.4.1",
    "react-test-renderer": "16.13.1",
    "react-app-polyfill": "1.0.6",
    "react-toastify": "6.0.8"
  },
  "scripts": {
    "start": "set PORT=4200 && react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "@types/axios": "0.14.0",
    "@types/enzyme": "3.10.5",
    "@types/enzyme-adapter-react-16": "1.0.6",
    "@types/jest": "26.0.4",
    "@types/node": "14.0.23",
    "@types/ramda": "0.27.11",
    "@types/react": "16.9.43",
    "@types/react-dom": "16.9.8",
    "@types/react-json-tree": "0.6.11",
    "@types/react-test-renderer": "16.9.2",
    "@types/toastr": "2.1.38",
    "typescript": "3.9.6"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version",
      "ie 11"
    ]
  }
}


================================================
FILE: src/public/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>


================================================
FILE: src/public/manifest.json
================================================
{
  "short_name": "React App",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    }
  ],
  "start_url": "./index.html",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}


================================================
FILE: src/public/signin-callback.html
================================================
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Authentification callback processing..</title>
</head>

<body>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>

    <h1>Authentification callback processing...</h1>

    <script src="oidc-client.min.js"></script>
    <script>
        new Oidc.UserManager({ response_mode: "query" }).signinRedirectCallback().then(function () {
            window.location = "index.html";
        }).catch(function (e) {
            console.error(e);
        });
    </script>

</body>

</html>

================================================
FILE: src/public/silent-renew.html
================================================
<script src="oidc-client.min.js"></script>
<script>
    var mgr = new Oidc.UserManager();
    mgr.signinSilentCallback().catch(function (error) {
        console.error(error);
    });
</script>

================================================
FILE: src/src/components/AppContent.tsx
================================================
import * as React from 'react';

import { ToastContainer, toast } from 'react-toastify';
import { ApiService } from '../services/ApiService';
import { AuthService } from '../services/AuthService';

import AuthContent from './AuthContent';
import Buttons from './Buttons';

export default class AppContent extends React.Component<any, any> {
  public authService: AuthService;
  public apiService: ApiService;
  private shouldCancel: boolean;

  constructor(props: any) {
    super(props);

    this.authService = new AuthService();
    this.apiService = new ApiService();
    this.state = { user: {}, api: {} };
    this.shouldCancel = false;
  }

  public componentDidMount() {
    this.getUser();
  }

  public login = () => {
    this.authService.login();
  };

  public callApi = () => {
    this.apiService
      .callApi()
      .then(data => {
        this.setState({ api: data.data });
        toast.success('Api return successfully data, check in section - Api response');
      })
      .catch(error => {
        toast.error(error);
      });
  };

  public componentWillUnmount() {
    this.shouldCancel = true;
  }

  public renewToken = () => {
    this.authService
      .renewToken()
      .then(user => {
        toast.success('Token has been sucessfully renewed. :-)');
        this.getUser();
      })
      .catch(error => {
        toast.error(error);
      });
  };

  public logout = () => {
    this.authService.logout();
  };

  public getUser = () => {
    this.authService.getUser().then(user => {
      if (user) {
        toast.success('User has been successfully loaded from store.');
      } else {
        toast.info('You are not logged in.');
      }

      if (!this.shouldCancel) {
        this.setState({ user });
      }
    });
  };

  public render() {
    return (
      <>
        <ToastContainer />

        <Buttons
          login={this.login}
          logout={this.logout}
          renewToken={this.renewToken}
          getUser={this.getUser}
          callApi={this.callApi}
        />

        <AuthContent api={this.state.api} user={this.state.user} />
      </>
    );
  }
}


================================================
FILE: src/src/components/AuthContent.tsx
================================================
import * as React from 'react';
import JsonTreeViewer from './JsonTreeViewer';

export interface IAuthContentProps {
  api: any;
  user: any;
}

export default class AuthContent extends React.Component<IAuthContentProps, any> {
  public shouldExpandNode = (keyPath: Array<string | number>, data: [any] | {}, level: number) => {
    return true;
  };

  public render() {
    return (
      <div className="row">
        <div className="col-md-6">
          <JsonTreeViewer data={this.props.user} title="User Profile" shouldExpandNode={this.shouldExpandNode} />
        </div>
        <div className="col-md-6">
          <JsonTreeViewer data={this.props.api} title="Api Response" shouldExpandNode={this.shouldExpandNode} />
        </div>
      </div>
    );
  }
}


================================================
FILE: src/src/components/Buttons.test.tsx
================================================
import { shallow } from 'enzyme';
import * as React from 'react';
import * as renderer from 'react-test-renderer';

import Buttons from './Buttons';

describe(Buttons, () => {
  const mockLogin = jest.fn();
  const mockLogout = jest.fn();
  const mockRenewToken = jest.fn();
  const mockCallApi = jest.fn();
  const mockGetUser = jest.fn();

  const component = shallow(
    <Buttons
      login={mockLogin}
      logout={mockLogout}
      renewToken={mockRenewToken}
      callApi={mockCallApi}
      getUser={mockGetUser}
    />
  );

  it('renders and matches our snapshot', () => {
    const buttonComponent = renderer.create(
      <Buttons
        login={mockLogin}
        logout={mockLogout}
        renewToken={mockRenewToken}
        callApi={mockCallApi}
        getUser={mockGetUser}
      />
    );
    const tree = buttonComponent.toJSON();
    expect(tree).toMatchSnapshot();
  });

  it('contains the image and h1', () => {
    expect(component.find('button')).toHaveLength(5);
  });

  it('try to click on login button', () => {
    component.find('button.btn-login').simulate('click');
    expect(mockLogin).toBeCalled();
  });

  it('try to click on logout button', () => {
    component.find('button.btn-logout').simulate('click');
    expect(mockLogout).toBeCalled();
  });
});


================================================
FILE: src/src/components/Buttons.tsx
================================================
import * as React from 'react';

interface IButtonsProps {
  login: () => void;
  getUser: () => void;
  callApi: () => void;
  renewToken: () => void;
  logout: () => void;
}

const Buttons: React.SFC<IButtonsProps> = props => {
  return (
    <div className="row">
      <div className="col-md-12 text-center" style={{ marginTop: '30px' }}>
        <button className="btn btn-primary btn-login" style={{ margin: '10px' }} onClick={props.login}>
          Login
        </button>
        <button className="btn btn-secondary btn-getuser" style={{ margin: '10px' }} onClick={props.getUser}>
          Get User info
        </button>
        <button className="btn btn-warning btn-getapi" style={{ margin: '10px' }} onClick={props.callApi}>
          Call API
        </button>
        <button className="btn btn-success btn-renewtoken" style={{ margin: '10px' }} onClick={props.renewToken}>
          Renew Token
        </button>
        <button className="btn btn-dark btn-logout" style={{ margin: '10px' }} onClick={props.logout}>
          Logout
        </button>
      </div>
    </div>
  );
};

export default Buttons;


================================================
FILE: src/src/components/Header.test.tsx
================================================
import { shallow } from 'enzyme';
import * as React from 'react';
import * as renderer from 'react-test-renderer';

import logo from '../logo.svg';
import Header from './Header';

describe(Header, () => {
  const pageTitle = 'React app with oidc-client-js';

  const component = shallow(<Header pageTitle={pageTitle} logoSrc={logo} />);

  it('renders and matches our snapshot', () => {
    const headerComponent = renderer.create(<Header pageTitle={pageTitle} logoSrc={logo} />);
    const tree = headerComponent.toJSON();
    expect(tree).toMatchSnapshot();
  });

  it('contains the image and h1', () => {
    expect(component.find('img')).toHaveLength(1);
    expect(component.find('h1')).toHaveLength(1);
  });

  it('h1 contains correct title', () => {
    expect(component.find('h1').text()).toEqual(pageTitle);
    expect(component.contains(pageTitle)).toEqual(true);
  });
});


================================================
FILE: src/src/components/Header.tsx
================================================
import * as React from 'react';

export interface IHeaderProps {
  pageTitle: string;
  logoSrc: any;
}

export default function Header(props: IHeaderProps) {
  return (
    <header className="App-header">
      <img src={props.logoSrc} className="App-logo" alt="logo" />
      <h1 className="App-title">{props.pageTitle}</h1>
    </header>
  );
}


================================================
FILE: src/src/components/JsonTreeViewer.tsx
================================================
import * as R from 'ramda';
import * as React from 'react';
import JSONTree from 'react-json-tree';

export interface IJsonTreeViewer {
  data: any;
  title: string;
  shouldExpandNode?: (keyPath: Array<string | number>, data: [any] | {}, level: number) => boolean;
}

export default class JsonTreeViewer extends React.Component<IJsonTreeViewer, any> {
  public renderJsonData() {
    return R.not(R.isEmpty(this.props.data)) && R.not(R.isNil(this.props.data)) ? (
      <>
        <h1>{this.props.title}</h1>
        <JSONTree data={this.props.data} theme="bright" shouldExpandNode={this.props.shouldExpandNode} />
      </>
    ) : null;
  }

  public render() {
    return this.renderJsonData();
  }
}


================================================
FILE: src/src/components/__snapshots__/Buttons.test.tsx.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Buttons renders and matches our snapshot 1`] = `
<div
  className="row"
>
  <div
    className="col-md-12 text-center"
    style={
      Object {
        "marginTop": "30px",
      }
    }
  >
    <button
      className="btn btn-primary btn-login"
      onClick={[MockFunction]}
      style={
        Object {
          "margin": "10px",
        }
      }
    >
      Login
    </button>
    <button
      className="btn btn-secondary btn-getuser"
      onClick={[MockFunction]}
      style={
        Object {
          "margin": "10px",
        }
      }
    >
      Get User info
    </button>
    <button
      className="btn btn-warning btn-getapi"
      onClick={[MockFunction]}
      style={
        Object {
          "margin": "10px",
        }
      }
    >
      Call API
    </button>
    <button
      className="btn btn-success btn-renewtoken"
      onClick={[MockFunction]}
      style={
        Object {
          "margin": "10px",
        }
      }
    >
      Renew Token
    </button>
    <button
      className="btn btn-dark btn-logout"
      onClick={[MockFunction]}
      style={
        Object {
          "margin": "10px",
        }
      }
    >
      Logout
    </button>
  </div>
</div>
`;


================================================
FILE: src/src/components/__snapshots__/Header.test.tsx.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Header renders and matches our snapshot 1`] = `
<header
  className="App-header"
>
  <img
    alt="logo"
    className="App-logo"
    src="logo.svg"
  />
  <h1
    className="App-title"
  >
    React app with oidc-client-js
  </h1>
</header>
`;


================================================
FILE: src/src/containers/App.css
================================================
.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 80px;
}

.App-header {
  background-color: #222;
  height: 150px;
  padding: 20px;
  color: white;
  text-align: center;
}

.App-title {
  font-size: 1.5em;
}

.App-intro {
  font-size: large;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

#toast-container > div {
  opacity: 1;
}


================================================
FILE: src/src/containers/App.test.tsx
================================================
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';

const storageMock = {
  clear: jest.fn(),
  getItem: jest.fn(),
  setItem: jest.fn()
};

(global as any).sessionStorage = storageMock;
(global as any).localStorage = storageMock;

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});


================================================
FILE: src/src/containers/App.tsx
================================================
import * as React from 'react';
import AppContent from '../components/AppContent';
import Header from '../components/Header';
import logo from '../logo.svg';
import './App.css';

class App extends React.Component {
  public render() {
    return (
      <div className="App">
        <Header pageTitle="Welcome to React and oidc-client-js" logoSrc={logo} />
        <div className="container-fluid">
          <div className="row">
            <div className="col">
              <AppContent />
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default App;


================================================
FILE: src/src/helpers/Constants.ts
================================================
export class Constants {
  public static stsAuthority = 'https://demo.identityserver.io/';
  public static clientId = 'interactive.public';
  public static clientRoot = 'http://localhost:4200/';
  public static clientScope = 'openid profile email api';

  public static apiRoot = 'https://demo.identityserver.io/api/';
}


================================================
FILE: src/src/index.css
================================================
body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}


================================================
FILE: src/src/index.tsx
================================================
import 'bootstrap/dist/css/bootstrap.min.css';
import 'react-toastify/dist/ReactToastify.css';

import 'react-app-polyfill/ie11';
import 'core-js';

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './containers/App';
import './index.css';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root') as HTMLElement);
registerServiceWorker();


================================================
FILE: src/src/react-app-env.d.ts
================================================
/// <reference types="react-scripts" />


================================================
FILE: src/src/registerServiceWorker.ts
================================================
// tslint:disable:no-console
// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the 'N+1' visit to a page, since previously
// cached resources are updated in the background.

// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(
      process.env.PUBLIC_URL!,
      window.location.toString()
    );
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Lets check if a service worker still exists or not.
        checkValidServiceWorker(swUrl);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit https://goo.gl/SC7cgQ'
          );
        });
      } else {
        // Is not local host. Just register service worker
        registerValidSW(swUrl);
      }
    });
  }
}

function registerValidSW(swUrl: string) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker) {
          installingWorker.onstatechange = () => {
            if (installingWorker.state === 'installed') {
              if (navigator.serviceWorker.controller) {
                // At this point, the old content will have been purged and
                // the fresh content will have been added to the cache.
                // It's the perfect time to display a 'New content is
                // available; please refresh.' message in your web app.
                console.log('New content is available; please refresh.');
              } else {
                // At this point, everything has been precached.
                // It's the perfect time to display a
                // 'Content is cached for offline use.' message.
                console.log('Content is cached for offline use.');
              }
            }
          };
        }
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl: string) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl)
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      if (
        response.status === 404 ||
        response.headers.get('content-type')!.indexOf('javascript') === -1
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}


================================================
FILE: src/src/services/ApiService.ts
================================================
import axios from 'axios';
import { Constants } from '../helpers/Constants';
import { AuthService } from './AuthService';

export class ApiService {
  private authService: AuthService;

  constructor() {
    this.authService = new AuthService();
  }

  public callApi(): Promise<any> {
    return this.authService.getUser().then(user => {
      if (user && user.access_token) {
        return this._callApi(user.access_token).catch(error => {
          if (error.response.status === 401) {
            return this.authService.renewToken().then(renewedUser => {
              return this._callApi(renewedUser.access_token);
            });
          }
          throw error;
        });
      } else if (user) {
        return this.authService.renewToken().then(renewedUser => {
          return this._callApi(renewedUser.access_token);
        });
      } else {
        throw new Error('user is not logged in');
      }
    });
  }

  private _callApi(token: string) {
    const headers = {
      Accept: 'application/json',
      Authorization: 'Bearer ' + token
    };

    return axios.get(Constants.apiRoot + 'test', { headers });
  }
}


================================================
FILE: src/src/services/AuthService.ts
================================================
import { Log, User, UserManager } from 'oidc-client';

import { Constants } from '../helpers/Constants';

export class AuthService {
  public userManager: UserManager;

  constructor() {
    const settings = {
      authority: Constants.stsAuthority,
      client_id: Constants.clientId,
      redirect_uri: `${Constants.clientRoot}signin-callback.html`,
      silent_redirect_uri: `${Constants.clientRoot}silent-renew.html`,
      // tslint:disable-next-line:object-literal-sort-keys
      post_logout_redirect_uri: `${Constants.clientRoot}`,
      response_type: 'code',
      scope: Constants.clientScope
    };
    this.userManager = new UserManager(settings);

    Log.logger = console;
    Log.level = Log.INFO;
  }

  public getUser(): Promise<User | null> {
    return this.userManager.getUser();
  }

  public login(): Promise<void> {
    return this.userManager.signinRedirect();
  }

  public renewToken(): Promise<User> {
    return this.userManager.signinSilent();
  }

  public logout(): Promise<void> {
    return this.userManager.signoutRedirect();
  }
}


================================================
FILE: src/src/setupTests.ts
================================================
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });


================================================
FILE: src/tsconfig.json
================================================
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": [
    "src"
  ]
}


================================================
FILE: src/tslint.json
================================================
{
  "extends": ["tslint:recommended", "tslint-react", "tslint-config-prettier"],
  "linterOptions": {
    "exclude": [
      "config/**/*.js",
      "node_modules/**/*.ts"
    ]
  }
}
Download .txt
gitextract_ato4xgph/

├── .gitignore
├── LICENSE
├── README.md
├── appveyor.yml
├── docs/
│   └── README.md
└── src/
    ├── .gitignore
    ├── package.json
    ├── public/
    │   ├── index.html
    │   ├── manifest.json
    │   ├── signin-callback.html
    │   └── silent-renew.html
    ├── src/
    │   ├── components/
    │   │   ├── AppContent.tsx
    │   │   ├── AuthContent.tsx
    │   │   ├── Buttons.test.tsx
    │   │   ├── Buttons.tsx
    │   │   ├── Header.test.tsx
    │   │   ├── Header.tsx
    │   │   ├── JsonTreeViewer.tsx
    │   │   └── __snapshots__/
    │   │       ├── Buttons.test.tsx.snap
    │   │       └── Header.test.tsx.snap
    │   ├── containers/
    │   │   ├── App.css
    │   │   ├── App.test.tsx
    │   │   └── App.tsx
    │   ├── helpers/
    │   │   └── Constants.ts
    │   ├── index.css
    │   ├── index.tsx
    │   ├── react-app-env.d.ts
    │   ├── registerServiceWorker.ts
    │   ├── services/
    │   │   ├── ApiService.ts
    │   │   └── AuthService.ts
    │   └── setupTests.ts
    ├── tsconfig.json
    └── tslint.json
Download .txt
SYMBOL INDEX (32 symbols across 10 files)

FILE: src/src/components/AppContent.tsx
  class AppContent (line 10) | class AppContent extends React.Component<any, any> {
    method constructor (line 15) | constructor(props: any) {
    method componentDidMount (line 24) | public componentDidMount() {
    method componentWillUnmount (line 44) | public componentWillUnmount() {
    method render (line 78) | public render() {

FILE: src/src/components/AuthContent.tsx
  type IAuthContentProps (line 4) | interface IAuthContentProps {
  class AuthContent (line 9) | class AuthContent extends React.Component<IAuthContentProps, any> {
    method render (line 14) | public render() {

FILE: src/src/components/Buttons.tsx
  type IButtonsProps (line 3) | interface IButtonsProps {

FILE: src/src/components/Header.tsx
  type IHeaderProps (line 3) | interface IHeaderProps {
  function Header (line 8) | function Header(props: IHeaderProps) {

FILE: src/src/components/JsonTreeViewer.tsx
  type IJsonTreeViewer (line 5) | interface IJsonTreeViewer {
  class JsonTreeViewer (line 11) | class JsonTreeViewer extends React.Component<IJsonTreeViewer, any> {
    method renderJsonData (line 12) | public renderJsonData() {
    method render (line 21) | public render() {

FILE: src/src/containers/App.tsx
  class App (line 7) | class App extends React.Component {
    method render (line 8) | public render() {

FILE: src/src/helpers/Constants.ts
  class Constants (line 1) | class Constants {

FILE: src/src/registerServiceWorker.ts
  function register (line 22) | function register() {
  function registerValidSW (line 59) | function registerValidSW(swUrl: string) {
  function checkValidServiceWorker (line 90) | function checkValidServiceWorker(swUrl: string) {
  function unregister (line 117) | function unregister() {

FILE: src/src/services/ApiService.ts
  class ApiService (line 5) | class ApiService {
    method constructor (line 8) | constructor() {
    method callApi (line 12) | public callApi(): Promise<any> {
    method _callApi (line 33) | private _callApi(token: string) {

FILE: src/src/services/AuthService.ts
  class AuthService (line 5) | class AuthService {
    method constructor (line 8) | constructor() {
    method getUser (line 25) | public getUser(): Promise<User | null> {
    method login (line 29) | public login(): Promise<void> {
    method renewToken (line 33) | public renewToken(): Promise<User> {
    method logout (line 37) | public logout(): Promise<void> {
Condensed preview — 33 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (35K chars).
[
  {
    "path": ".gitignore",
    "chars": 5582,
    "preview": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n##\n## G"
  },
  {
    "path": "LICENSE",
    "chars": 1068,
    "preview": "MIT License\n\nCopyright (c) 2018 Jan Škoruba\n\nPermission is hereby granted, free of charge, to any person obtaining a cop"
  },
  {
    "path": "README.md",
    "chars": 1442,
    "preview": "![Logo](docs/Images/Skoruba-Logo-ReadMe.png)\n\n# React-oidc-client-js\n\n> OpenID Connect (OIDC) client with React and type"
  },
  {
    "path": "appveyor.yml",
    "chars": 502,
    "preview": "environment:\n  matrix:\n    - nodejs_version: '12'\n    - nodejs_version: '10'\n    - nodejs_version: '8'\ninstall:\n  - ps: "
  },
  {
    "path": "docs/README.md",
    "chars": 69,
    "preview": "![Logo](Images/Skoruba-Logo-ReadMe.png)\n\n# react-oidc-client-js docs\n"
  },
  {
    "path": "src/.gitignore",
    "chars": 285,
    "preview": "# See https://help.github.com/ignore-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n\n# testing\n/cov"
  },
  {
    "path": "src/package.json",
    "chars": 1429,
    "preview": "{\n  \"name\": \"react-oidc-client-js\",\n  \"description\": \"OpenID Connect (OIDC) javascript client with React\",\n  \"version\": "
  },
  {
    "path": "src/public/index.html",
    "chars": 1590,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-wid"
  },
  {
    "path": "src/public/manifest.json",
    "chars": 317,
    "preview": "{\n  \"short_name\": \"React App\",\n  \"name\": \"Create React App Sample\",\n  \"icons\": [\n    {\n      \"src\": \"favicon.ico\",\n     "
  },
  {
    "path": "src/public/signin-callback.html",
    "chars": 566,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <title>Authentification callback processing..</title>\n</head>\n\n<body>\n    <"
  },
  {
    "path": "src/public/silent-renew.html",
    "chars": 193,
    "preview": "<script src=\"oidc-client.min.js\"></script>\n<script>\n    var mgr = new Oidc.UserManager();\n    mgr.signinSilentCallback()"
  },
  {
    "path": "src/src/components/AppContent.tsx",
    "chars": 2126,
    "preview": "import * as React from 'react';\n\nimport { ToastContainer, toast } from 'react-toastify';\nimport { ApiService } from '../"
  },
  {
    "path": "src/src/components/AuthContent.tsx",
    "chars": 765,
    "preview": "import * as React from 'react';\nimport JsonTreeViewer from './JsonTreeViewer';\n\nexport interface IAuthContentProps {\n  a"
  },
  {
    "path": "src/src/components/Buttons.test.tsx",
    "chars": 1299,
    "preview": "import { shallow } from 'enzyme';\nimport * as React from 'react';\nimport * as renderer from 'react-test-renderer';\n\nimpo"
  },
  {
    "path": "src/src/components/Buttons.tsx",
    "chars": 1126,
    "preview": "import * as React from 'react';\n\ninterface IButtonsProps {\n  login: () => void;\n  getUser: () => void;\n  callApi: () => "
  },
  {
    "path": "src/src/components/Header.test.tsx",
    "chars": 886,
    "preview": "import { shallow } from 'enzyme';\nimport * as React from 'react';\nimport * as renderer from 'react-test-renderer';\n\nimpo"
  },
  {
    "path": "src/src/components/Header.tsx",
    "chars": 348,
    "preview": "import * as React from 'react';\n\nexport interface IHeaderProps {\n  pageTitle: string;\n  logoSrc: any;\n}\n\nexport default "
  },
  {
    "path": "src/src/components/JsonTreeViewer.tsx",
    "chars": 705,
    "preview": "import * as R from 'ramda';\nimport * as React from 'react';\nimport JSONTree from 'react-json-tree';\n\nexport interface IJ"
  },
  {
    "path": "src/src/components/__snapshots__/Buttons.test.tsx.snap",
    "chars": 1271,
    "preview": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Buttons renders and matches our snapshot 1`] = `\n<div\n  className=\""
  },
  {
    "path": "src/src/components/__snapshots__/Header.test.tsx.snap",
    "chars": 298,
    "preview": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Header renders and matches our snapshot 1`] = `\n<header\n  className"
  },
  {
    "path": "src/src/containers/App.css",
    "chars": 421,
    "preview": ".App-logo {\n  animation: App-logo-spin infinite 20s linear;\n  height: 80px;\n}\n\n.App-header {\n  background-color: #222;\n "
  },
  {
    "path": "src/src/containers/App.test.tsx",
    "chars": 438,
    "preview": "import * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport App from './App';\n\nconst storageMock = {\n "
  },
  {
    "path": "src/src/containers/App.tsx",
    "chars": 593,
    "preview": "import * as React from 'react';\nimport AppContent from '../components/AppContent';\nimport Header from '../components/Hea"
  },
  {
    "path": "src/src/helpers/Constants.ts",
    "chars": 321,
    "preview": "export class Constants {\n  public static stsAuthority = 'https://demo.identityserver.io/';\n  public static clientId = 'i"
  },
  {
    "path": "src/src/index.css",
    "chars": 63,
    "preview": "body {\n  margin: 0;\n  padding: 0;\n  font-family: sans-serif;\n}\n"
  },
  {
    "path": "src/src/index.tsx",
    "chars": 439,
    "preview": "import 'bootstrap/dist/css/bootstrap.min.css';\nimport 'react-toastify/dist/ReactToastify.css';\n\nimport 'react-app-polyfi"
  },
  {
    "path": "src/src/react-app-env.d.ts",
    "chars": 40,
    "preview": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "src/src/registerServiceWorker.ts",
    "chars": 4534,
    "preview": "// tslint:disable:no-console\n// In production, we register a service worker to serve assets from local cache.\n\n// This l"
  },
  {
    "path": "src/src/services/ApiService.ts",
    "chars": 1142,
    "preview": "import axios from 'axios';\nimport { Constants } from '../helpers/Constants';\nimport { AuthService } from './AuthService'"
  },
  {
    "path": "src/src/services/AuthService.ts",
    "chars": 1071,
    "preview": "import { Log, User, UserManager } from 'oidc-client';\n\nimport { Constants } from '../helpers/Constants';\n\nexport class A"
  },
  {
    "path": "src/src/setupTests.ts",
    "chars": 123,
    "preview": "import Enzyme from 'enzyme';\nimport Adapter from 'enzyme-adapter-react-16';\n\nEnzyme.configure({ adapter: new Adapter() }"
  },
  {
    "path": "src/tsconfig.json",
    "chars": 494,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\n      \"dom\",\n      \"dom.iterable\",\n      \"esnext\"\n    ],\n    "
  },
  {
    "path": "src/tslint.json",
    "chars": 184,
    "preview": "{\n  \"extends\": [\"tslint:recommended\", \"tslint-react\", \"tslint-config-prettier\"],\n  \"linterOptions\": {\n    \"exclude\": [\n "
  }
]

About this extraction

This page contains the full source code of the skoruba/react-oidc-client-js GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 33 files (31.0 KB), approximately 9.0k tokens, and a symbol index with 32 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!