├── .gitignore
├── README.md
├── package.json
├── public
├── favicon.ico
├── index.html
└── manifest.json
├── src
├── App.css
├── App.js
├── App.test.js
├── components
│ ├── LoginForm.js
│ ├── NotFound.js
│ ├── Profile.js
│ ├── ProtectedRoute.js
│ └── Router.js
├── config
│ └── app.json
├── helper.js
├── images
│ ├── login-validation1.png
│ ├── login-validation2.png
│ └── profile-page.png
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
└── yarn.lock
/.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 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React WPGraphQL JWT Authentication with Apollo Client
2 |
3 | ## Screenshots
4 |
5 | 
6 | 
7 | 
8 |
9 | ## Prerequisites
10 |
11 | Install and active the following plugins in your WordPress backend:
12 |
13 | 1. [WPGraphQL](https://github.com//wp-graphql/wp-graphql)
14 | 2. [WPGraphQL JWT Authentication](https://github.com/wp-graphql/wp-graphql-jwt-authentication)
15 |
16 | **Note: Follow the instructions given by [WPGraphQL](https://github.com//wp-graphql/wp-graphql) author to avoid exceptional behaviors.**
17 |
18 |
19 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
20 |
21 | ## Run the project
22 |
23 | In the project directory, you can run:
24 |
25 | ### `npm start`
26 |
27 | Runs the app in the development mode.
28 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
29 |
30 | The page will reload if you make edits.
31 | You will also see any lint errors in the console.
32 |
33 | ### Change WordPress URL
34 |
35 | Go to `app.json` file and change the `siteUrl` value to yours.
36 |
37 | ## Covered features:
38 |
39 | 👉 Client side form validations
40 | 👉 Server side form validations
41 | 👉 WordPress Authentication (login) with WPGraphQL
42 | 👉 [Apollo GraphQL Client](https://www.apollographql.com/) for handling GraphQL mutation
43 | 👉 Protected route with [React Router](https://reacttraining.com/react-router/)
44 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-wp-graphql-auth",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "apollo-boost": "^0.3.1",
7 | "axios": "^0.18.0",
8 | "bootstrap": "^4.3.1",
9 | "graphql": "^14.1.1",
10 | "react": "^16.8.3",
11 | "react-apollo": "^2.5.1",
12 | "react-bootstrap": "^1.0.0-beta.5",
13 | "react-dom": "^16.8.3",
14 | "react-router-dom": "^4.3.1",
15 | "react-scripts": "2.1.5"
16 | },
17 | "scripts": {
18 | "start": "react-scripts start",
19 | "build": "react-scripts build",
20 | "test": "react-scripts test",
21 | "eject": "react-scripts eject"
22 | },
23 | "eslintConfig": {
24 | "extends": "react-app"
25 | },
26 | "browserslist": [
27 | ">0.2%",
28 | "not dead",
29 | "not ie <= 11",
30 | "not op_mini all"
31 | ]
32 | }
33 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hussain-t/react-wp-graphql-auth/8a6d36beecbc1007fccda6f3dbabe1507ec7ba00/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
10 |
11 |
15 |
16 |
25 |
31 | React App
32 |
33 |
34 |
35 |
36 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/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 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 40vmin;
8 | pointer-events: none;
9 | }
10 |
11 | .App-header {
12 | background-color: #282c34;
13 | min-height: 100vh;
14 | display: flex;
15 | flex-direction: column;
16 | align-items: center;
17 | justify-content: center;
18 | font-size: calc(10px + 2vmin);
19 | color: white;
20 | }
21 |
22 | .App-link {
23 | color: #61dafb;
24 | }
25 |
26 | @keyframes App-logo-spin {
27 | from {
28 | transform: rotate(0deg);
29 | }
30 | to {
31 | transform: rotate(360deg);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { ApolloProvider } from 'react-apollo'
3 | import ApolloClient from 'apollo-boost';
4 |
5 | import Router from './components/Router';
6 | import { domain } from './config/app.json'
7 |
8 | const client = new ApolloClient({
9 | uri: `${domain.env.siteUrl}/graphql`
10 | })
11 |
12 | class App extends Component {
13 | render() {
14 | return (
15 |
16 |
17 |
18 | );
19 | }
20 | }
21 |
22 | export default App;
23 |
--------------------------------------------------------------------------------
/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/components/LoginForm.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { Form, Button, Alert } from 'react-bootstrap';
3 | import { Mutation } from 'react-apollo';
4 | import gql from 'graphql-tag';
5 |
6 | import { AUTH_TOKEN } from '../helper';
7 |
8 | const LOGIN_USER = gql`
9 | mutation LoginUser($username: String! $password: String!) {
10 | login(input: {
11 | clientMutationId: "uniqueId"
12 | username: $username
13 | password: $password
14 | }) {
15 | authToken
16 | user {
17 | id
18 | userId
19 | name
20 | }
21 | }
22 | }
23 | `
24 |
25 | class LoginForm extends Component {
26 | state = {
27 | validate: false,
28 | username: '',
29 | password: '',
30 | error: '',
31 | }
32 | _isMounted = false;
33 |
34 | componentDidMount() {
35 | this._isMounted = true;
36 | }
37 |
38 | componentWillUnmount() {
39 | this._isMounted = false;
40 | }
41 |
42 | handleLogin = async (event, login) => {
43 | event.preventDefault();
44 | const { username, password } = this.state;
45 | if(this._isMounted) {
46 | this.setState({ validate: true });
47 | }
48 | await login({ variables: { username, password } })
49 | .then(response => this.handleLoginSuccess(response))
50 | .catch(err => this.handleLoginFail(err.graphQLErrors[0].message))
51 | }
52 |
53 | handleLoginSuccess = response => {
54 | localStorage.setItem(AUTH_TOKEN, JSON.stringify(response.data.login));
55 | this.props.history.push('/profile');
56 | if(this._isMounted) {
57 | this.setState({
58 | validate: false,
59 | username: '',
60 | password: '',
61 | error: '',
62 | });
63 | }
64 | this.props.history.push('/profile');
65 | }
66 |
67 | handleLoginFail = err => {
68 | const error = err.split('_').join(' ').toUpperCase();
69 |
70 | if(this._isMounted) {
71 | this.setState({
72 | validate: true,
73 | loading: false,
74 | error ,
75 | });
76 | }
77 | }
78 |
79 | handleUsername = username => {
80 | this.setState({ username });
81 | }
82 |
83 | handlePassword = password => {
84 | this.setState({ password });
85 | }
86 |
87 | renderMessage(loading, error) {
88 | if (error) {
89 | return (
90 |
91 | {this.state.error}
92 |
93 | )
94 | } else if (loading) {
95 | return (
96 |
97 | Loading...
98 |
99 | )
100 | }
101 | }
102 |
103 | render() {
104 | const { validate } = this.state;
105 | return (
106 |
107 | {(login, { loading, error }) => (
108 |
109 |
117 | Username
118 | this.handleUsername(event.target.value)}
123 | value={this.state.username}
124 | />
125 | Username cannot be empty!
126 |
127 |
128 | Password
129 | this.handlePassword(event.target.value)}
134 | value={this.state.password}
135 | />
136 | Password cannot be empty!
137 |
138 | {this.renderMessage(loading, error)}
139 |
142 |
143 |
144 | )}
145 |
146 | )
147 | }
148 | }
149 |
150 | export default LoginForm;
151 |
--------------------------------------------------------------------------------
/src/components/NotFound.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | const NotFound = () => (
4 | 404! Page not fount!!!!
5 | )
6 |
7 | export default NotFound;
8 |
--------------------------------------------------------------------------------
/src/components/Profile.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import { AUTH_TOKEN, getUserSnippet } from '../helper';
4 |
5 | const Profile = props => {
6 | const user = JSON.parse(localStorage.getItem(AUTH_TOKEN));
7 |
8 | return (
9 |
10 |
11 |
12 |
{getUserSnippet(user.user.name)}
13 |
14 |
{user.user.name}
15 |
22 |
23 |
24 | )
25 | }
26 |
27 | export default Profile;
28 |
--------------------------------------------------------------------------------
/src/components/ProtectedRoute.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Route, Redirect } from 'react-router-dom';
3 |
4 | import { AUTH_TOKEN } from '../helper';
5 |
6 | const ProtectedRoute = ({ component: Component, ...rest }) => {
7 | const token = localStorage.getItem(AUTH_TOKEN);
8 | return (
9 | token ? (
12 |
13 | ) : (
14 |
22 | )
23 | }
24 | />
25 | )
26 | }
27 |
28 | export default ProtectedRoute;
--------------------------------------------------------------------------------
/src/components/Router.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { BrowserRouter, Route, Switch } from 'react-router-dom';
3 |
4 | import LoginForm from './LoginForm';
5 | import Profile from './Profile';
6 | import NotFound from './NotFound';
7 | import ProtectedRoute from './ProtectedRoute';
8 |
9 | const Router = () => (
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | )
18 |
19 | export default Router;
20 |
--------------------------------------------------------------------------------
/src/config/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "domain": {
3 | "env": {
4 | "siteUrl": "https://lexcampus.on-its-way.com/"
5 | }
6 | },
7 | "API": {
8 | "WP": "wp-json/",
9 | "JWT": "jwt-auth/v1/"
10 | },
11 | "endpoint": {
12 | "token": "token/"
13 | }
14 | }
--------------------------------------------------------------------------------
/src/helper.js:
--------------------------------------------------------------------------------
1 | export const AUTH_TOKEN = window.location.host + '/AUTH_TOKEN';
2 |
3 | export const getUserSnippet = username => {
4 | let initials = '';
5 | if (!username) {
6 | return initials;
7 | }
8 |
9 | const fullname = username.split(' ');
10 | const initialLetters = fullname.map(name => name.substring(0, 1));
11 | [initials] = initialLetters;
12 | if (initialLetters[1]) {
13 | initials += initialLetters[1];
14 | }
15 |
16 | return initials.toUpperCase();
17 | }
--------------------------------------------------------------------------------
/src/images/login-validation1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hussain-t/react-wp-graphql-auth/8a6d36beecbc1007fccda6f3dbabe1507ec7ba00/src/images/login-validation1.png
--------------------------------------------------------------------------------
/src/images/login-validation2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hussain-t/react-wp-graphql-auth/8a6d36beecbc1007fccda6f3dbabe1507ec7ba00/src/images/login-validation2.png
--------------------------------------------------------------------------------
/src/images/profile-page.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hussain-t/react-wp-graphql-auth/8a6d36beecbc1007fccda6f3dbabe1507ec7ba00/src/images/profile-page.png
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 0;
4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
6 | sans-serif;
7 | -webkit-font-smoothing: antialiased;
8 | -moz-osx-font-smoothing: grayscale;
9 | background: #f4f4f4;
10 | }
11 |
12 | code {
13 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
14 | monospace;
15 | }
16 |
17 | .container {
18 | width: 100%;
19 | margin: 0 auto;
20 | overflow: hidden;
21 | }
22 |
23 | @media(min-width: 992px) {
24 | .container {
25 | width: 50%;
26 | margin: 0 auto;
27 | overflow: hidden;
28 | }
29 | }
30 |
31 | .container form {
32 | margin: 2em;
33 | padding: 2em;
34 | box-shadow: 3px 3px 15px 0 #dadada;
35 | }
36 |
37 | @media(min-width: 992px) {
38 | .container form {
39 | margin: 5em;
40 | padding: 4em;
41 | box-shadow: 3px 3px 15px 0 #dadada;
42 | }
43 | }
44 |
45 | .profile-container {
46 | margin: 2em;
47 | padding: 2em;
48 | box-shadow: 3px 3px 15px 0 #dadada;
49 | display: flex;
50 | justify-content: center;
51 | align-items: center;
52 | flex-direction: column;
53 | text-align: center;
54 | }
55 |
56 | .user-snippet {
57 | background: #F15F79;
58 | padding: 40px;
59 | width: 150px;
60 | height: 150px;
61 | margin: 50px;
62 | border-radius: 75px;
63 | }
64 |
65 | .user-snippet h1 {
66 | color: #ffffff;
67 | text-align: center;
68 | padding-top: 16px;
69 | }
70 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | ReactDOM.render(, document.getElementById('root'));
8 |
9 | // If you want your app to work offline and load faster, you can change
10 | // unregister() to register() below. Note this comes with some pitfalls.
11 | // Learn more about service workers: http://bit.ly/CRA-PWA
12 | serviceWorker.unregister();
13 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/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 http://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 http://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 http://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 |
--------------------------------------------------------------------------------