├── public ├── robots.txt ├── favicon.ico ├── logo192.png ├── logo512.png ├── manifest.json └── index.html ├── src ├── containers │ ├── index.js │ └── home │ │ └── home.js ├── store │ ├── reducers │ │ ├── index.js │ │ └── authReducer.js │ ├── types │ │ └── index.js │ ├── index.js │ └── actions │ │ └── authAction.js ├── components │ ├── index.js │ ├── home │ │ └── home.js │ └── header │ │ └── header.js ├── config │ └── index.js ├── App.test.js ├── index.js ├── routers.js ├── contexts │ └── auth0-context.js └── serviceWorker.js ├── .gitignore ├── README.md └── package.json /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /src/containers/index.js: -------------------------------------------------------------------------------- 1 | export { default as HomeContainer } from './home/home'; 2 | -------------------------------------------------------------------------------- /src/store/reducers/index.js: -------------------------------------------------------------------------------- 1 | export { default as authReducer } from './authReducer'; 2 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Abdul-majid-ashrafi/auth0-react.js/master/public/favicon.ico -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Abdul-majid-ashrafi/auth0-react.js/master/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Abdul-majid-ashrafi/auth0-react.js/master/public/logo512.png -------------------------------------------------------------------------------- /src/components/index.js: -------------------------------------------------------------------------------- 1 | export { default as HomeComponent } from './home/home'; 2 | export { default as Header } from './header/header'; 3 | -------------------------------------------------------------------------------- /src/config/index.js: -------------------------------------------------------------------------------- 1 | export const auth0Config = { 2 | domain: "dev-------.au.auth0.com", 3 | client_id: "........" 4 | } 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/store/types/index.js: -------------------------------------------------------------------------------- 1 | export const LOGIN_START ='LOGIN_START'; 2 | export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; 3 | export const LOGIN_FAILD = 'LOGIN_FAILD'; 4 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /src/store/index.js: -------------------------------------------------------------------------------- 1 | import { createStore, combineReducers, applyMiddleware } from 'redux'; 2 | import thunk from 'redux-thunk'; 3 | 4 | import { 5 | authReducer 6 | } from './reducers'; 7 | 8 | export default createStore(combineReducers({ 9 | auth: authReducer 10 | }), {}, applyMiddleware(thunk)); -------------------------------------------------------------------------------- /src/components/home/home.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useAuth0 } from '../../contexts/auth0-context'; 3 | 4 | function HomeComponent() { 5 | const { user } = useAuth0(); 6 | 7 | return ( 8 |
9 |

Hello {user.nickname}

10 |
11 | ); 12 | } 13 | export default HomeComponent; -------------------------------------------------------------------------------- /src/containers/home/home.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import { HomeComponent } from '../../components'; 3 | 4 | export class HomeContainer extends Component { 5 | render() { 6 | return ( 7 |
8 | 9 |
10 | ) 11 | } 12 | } 13 | 14 | export default HomeContainer 15 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import Routing from './routers'; 4 | import store from './store'; 5 | import { Provider } from 'react-redux' 6 | import { Auth0Provider } from './contexts/auth0-context'; 7 | 8 | ReactDOM.render( 9 | 10 | 11 | 12 | 13 | , 14 | document.getElementById('root') 15 | ); 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | .env 8 | 9 | # testing 10 | /coverage 11 | 12 | # production 13 | /build 14 | 15 | # misc 16 | .DS_Store 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | 26 | package-lock.json -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Features 2 | 3 | There are some important features in this repo: 4 | * Using the Auth0 SPA SDK to create an React Context (auth0-context.js) 5 | * Redux are implemented 6 | * React router dom are implemented 7 | 8 | ## Trying out this Repo 9 | 10 | To try out this repo and see it in action: 11 | 1. Clone the repo: git clone https://github.com/Abdul-majid-ashrafi/auth0-react.js.git 12 | 2. Install dependencies: npm install 13 | 3. Change your auth0 applications credentials in config/index.js 14 | 4. Start the app: npm start 15 | 5. View the app: http://localhost:3000 16 | 17 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /src/store/reducers/authReducer.js: -------------------------------------------------------------------------------- 1 | import { LOGIN_START, LOGIN_SUCCESS, LOGIN_FAILD } from '../types'; 2 | 3 | let initialState = { 4 | isLoggin: false, 5 | isLoading: false, 6 | } 7 | 8 | function authReducer(auth = initialState, action) { 9 | switch (action.type) { 10 | case LOGIN_START: 11 | return {...auth, isLoggin: false, isLoading: true }; 12 | case LOGIN_SUCCESS: 13 | return {...auth, isLoggin: true, isLoading: false }; 14 | case LOGIN_FAILD: 15 | return {...auth, isLoggin: false, isLoading: false }; 16 | default: 17 | return auth; 18 | } 19 | } 20 | 21 | export default authReducer; -------------------------------------------------------------------------------- /src/store/actions/authAction.js: -------------------------------------------------------------------------------- 1 | import { LOGIN_SUCCESS, LOGIN_FAILD } from '../types' 2 | import { message } from 'antd' 3 | 4 | 5 | const AuthAction = (username, password) => (dispatch) => { 6 | if (username === 'admin' && password === 'admin') { 7 | var randomToken = require('random-token'); 8 | var token = randomToken(16) 9 | localStorage.setItem('session', JSON.stringify(token)) 10 | window.location.reload() 11 | } 12 | else { 13 | dispatch({ type: LOGIN_FAILD }) 14 | message.error('enter Valid UserName Or PassWord') 15 | } 16 | var loginSucces = localStorage.getItem('session'); 17 | loginSucces = JSON.parse(loginSucces); 18 | if (loginSucces !== null) { 19 | dispatch({ type: LOGIN_SUCCESS }) 20 | } 21 | 22 | } 23 | 24 | export default AuthAction -------------------------------------------------------------------------------- /src/components/header/header.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useAuth0 } from '../../contexts/auth0-context'; 3 | import { Button } from 'antd'; 4 | 5 | function Header() { 6 | const { isAuthenticated, loginWithRedirect, logout } = useAuth0(); 7 | 8 | return ( 9 |
10 | {/* if there is no user. show the login button */} 11 | {!isAuthenticated && ( 12 | 13 | )} 14 | 15 | {/* if there is a user. show user name and logout button */} 16 | {isAuthenticated && ( 17 | <> 18 | 21 | 22 | )} 23 |
24 |
25 | ); 26 | } 27 | 28 | export default Header; -------------------------------------------------------------------------------- /src/routers.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useAuth0 } from './contexts/auth0-context'; 3 | import { 4 | BrowserRouter as Router, 5 | Switch, 6 | Route 7 | } from "react-router-dom"; 8 | 9 | import { Header } from './components'; 10 | import { HomeContainer } from './containers'; 11 | 12 | // page not found component will be render if got wrong url/path 13 | const PageNotFound = () => { 14 | return

Page Not Found

15 | } 16 | 17 | function Routing() { 18 | const { isAuthenticated } = useAuth0(); 19 | return ( 20 | <> 21 |
22 | 23 | 24 | 25 | 26 | {(isAuthenticated) ? : ""} 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | ); 35 | } 36 | 37 | export default Routing; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "auth0", 3 | "version": "1.0.0", 4 | "description": "Auth0 with reactjs and routes , redux are implemented", 5 | "dependencies": { 6 | "@ant-design/icons": "^4.1.0", 7 | "@auth0/auth0-spa-js": "^1.11.0", 8 | "antd": "^4.2.0", 9 | "axios": "^0.19.2", 10 | "react": "^16.13.1", 11 | "react-dom": "^16.13.1", 12 | "react-redux": "^7.2.1", 13 | "react-router-dom": "^5.2.0", 14 | "react-scripts": "3.2.0", 15 | "redux": "^4.0.5", 16 | "redux-thunk": "^2.3.0" 17 | }, 18 | "devDependencies": {}, 19 | "scripts": { 20 | "start": "react-scripts start", 21 | "build": "react-scripts build", 22 | "test": "react-scripts test", 23 | "eject": "react-scripts eject" 24 | }, 25 | "repository": { 26 | "type": "git", 27 | "url": "git+https://github.com/Abdul-majid-ashrafi/auth0-react.js.git" 28 | }, 29 | "author": "Majid Ashraf", 30 | "license": "ISC", 31 | "browserslist": { 32 | "production": [ 33 | ">0.2%", 34 | "not dead", 35 | "not op_mini all" 36 | ], 37 | "development": [ 38 | "last 1 chrome version", 39 | "last 1 firefox version", 40 | "last 1 safari version" 41 | ] 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/contexts/auth0-context.js: -------------------------------------------------------------------------------- 1 | import React, { Component, createContext, useContext } from 'react'; 2 | import { auth0Config } from '../config'; 3 | import createAuth0Client from '@auth0/auth0-spa-js'; 4 | 5 | // create the context 6 | export const Auth0Context = createContext(); 7 | export const useAuth0 = () => useContext(Auth0Context); 8 | 9 | // create a provider 10 | export class Auth0Provider extends Component { 11 | state = { 12 | auth0Client: null, 13 | isLoading: true, 14 | isAuthenticated: false, 15 | user: null 16 | }; 17 | config = { 18 | domain: auth0Config.domain, 19 | client_id: auth0Config.client_id, 20 | redirect_uri: window.location.origin 21 | }; 22 | 23 | componentDidMount() { 24 | this.initializeAuth0(); 25 | } 26 | 27 | // initialize the auth0 library 28 | initializeAuth0 = async () => { 29 | const auth0Client = await createAuth0Client(this.config); 30 | this.setState({ auth0Client }); 31 | 32 | // check to see if they have been redirected after login 33 | if (window.location.search.includes('code=')) { 34 | return this.handleRedirectCallback(); 35 | } 36 | 37 | const isAuthenticated = await auth0Client.isAuthenticated(); 38 | const user = isAuthenticated ? await auth0Client.getUser() : null; 39 | this.setState({ isLoading: false, isAuthenticated, user }); 40 | }; 41 | 42 | handleRedirectCallback = async () => { 43 | this.setState({ isLoading: true }); 44 | 45 | await this.state.auth0Client.handleRedirectCallback(); 46 | const user = await this.state.auth0Client.getUser(); 47 | 48 | this.setState({ user, isAuthenticated: true, isLoading: false }); 49 | window.history.replaceState({}, document.title, window.location.pathname); 50 | }; 51 | 52 | render() { 53 | const { auth0Client, isLoading, isAuthenticated, user } = this.state; 54 | const { children } = this.props; 55 | 56 | const configObject = { 57 | isLoading, 58 | isAuthenticated, 59 | user, 60 | loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p), 61 | getTokenSilently: (...p) => auth0Client.getTokenSilently(...p), 62 | getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p), 63 | logout: (...p) => auth0Client.logout(...p) 64 | }; 65 | 66 | return {children}; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------