├── .env
├── .gitignore
├── README.md
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── src
├── App.css
├── App.js
├── actions
│ ├── auth.js
│ ├── message.js
│ └── types.js
├── common
│ ├── AuthVerify.js
│ └── EventBus.js
├── components
│ ├── BoardAdmin.js
│ ├── BoardModerator.js
│ ├── BoardUser.js
│ ├── Home.js
│ ├── Login.js
│ ├── Profile.js
│ └── Register.js
├── index.css
├── index.js
├── reducers
│ ├── auth.js
│ ├── index.js
│ └── message.js
├── serviceWorker.js
├── services
│ ├── auth-header.js
│ ├── auth.service.js
│ └── user.service.js
├── setupTests.js
└── store.js
└── yarn.lock
/.env:
--------------------------------------------------------------------------------
1 | PORT=8081
--------------------------------------------------------------------------------
/.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 Redux Login, Logout, Registration example using Hooks
2 |
3 | For more detail, please visit:
4 | > [React Redux Login, Logout, Registration example with Hooks](https://bezkoder.com/react-hooks-redux-login-registration-example/)
5 |
6 | > [React Hooks: JWT Authentication & Authorization (without Redux) example](https://bezkoder.com/react-hooks-jwt-auth/)
7 |
8 | > [React Redux Login, Logout, Registration example (using React Components)](https://bezkoder.com/react-redux-jwt-auth/)
9 |
10 | Fullstack (JWT Authentication & Authorization example):
11 | > [React + Spring Boot](https://bezkoder.com/spring-boot-react-jwt-auth/)
12 |
13 | > [React + Node.js Express](https://bezkoder.com/react-express-authentication-jwt/)
14 |
15 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
16 |
17 | ### Set port
18 | .env
19 | ```
20 | PORT=8081
21 | ```
22 |
23 | ### Note:
24 | Open `src/services/auth-header.js` and modify `return` statement for appropriate back-end (found in the tutorial).
25 |
26 | ```js
27 | export default function authHeader() {
28 | const user = JSON.parse(localStorage.getItem('user'));
29 |
30 | if (user && user.accessToken) {
31 | // return { Authorization: 'Bearer ' + user.accessToken }; // for Spring Boot back-end
32 | return { 'x-access-token': user.accessToken }; // for Node.js Express back-end
33 | } else {
34 | return {};
35 | }
36 | }
37 | ```
38 |
39 | ### Project setup
40 |
41 | In the project directory, you can run:
42 |
43 | ```
44 | npm install
45 | # or
46 | yarn install
47 | ```
48 |
49 | or
50 |
51 | ### Compiles and hot-reloads for development
52 |
53 | ```
54 | npm start
55 | # or
56 | yarn start
57 | ```
58 |
59 | Open [http://localhost:8081](http://localhost:8081) to view it in the browser.
60 |
61 | The page will reload if you make edits.
62 |
63 | ### Related Posts
64 | > [In-depth Introduction to JWT-JSON Web Token](https://bezkoder.com/jwt-json-web-token/)
65 |
66 | > [React CRUD example using Hooks](https://bezkoder.com/react-hooks-crud-axios-api/)
67 |
68 | > [React Pagination using Hooks example](https://bezkoder.com/react-pagination-hooks/)
69 |
70 | > [React Hooks File Upload example](https://bezkoder.com/react-hooks-file-upload/)
71 |
72 | Fullstack with Node.js Express:
73 | > [React.js + Node.js Express + MySQL](https://bezkoder.com/react-node-express-mysql/)
74 |
75 | > [React.js + Node.js Express + PostgreSQL](https://bezkoder.com/react-node-express-postgresql/)
76 |
77 | > [React.js + Node.js Express + MongoDB](https://bezkoder.com/react-node-express-mongodb-mern-stack/)
78 |
79 | Fullstack with Spring Boot:
80 | > [React.js + Spring Boot + MySQL](https://bezkoder.com/react-spring-boot-crud/)
81 |
82 | > [React.js + Spring Boot + PostgreSQL](https://bezkoder.com/spring-boot-react-postgresql/)
83 |
84 | > [React.js + Spring Boot + MongoDB](https://bezkoder.com/react-spring-boot-mongodb/)
85 |
86 | Fullstack with Django:
87 | > [React.js Hooks + Django Rest Framework](https://bezkoder.com/django-react-hooks/)
88 |
89 | Serverless:
90 | > [React Hooks Firebase Realtime Database: CRUD App ](https://bezkoder.com/react-firebase-hooks-crud/)
91 |
92 | > [React Hooks Firestore example: CRUD App](https://bezkoder.com/react-hooks-firestore/)
93 |
94 | Integration (run back-end & front-end on same server/port)
95 | > [Integrate React with Spring Boot](https://bezkoder.com/integrate-reactjs-spring-boot/)
96 |
97 | > [Integrate React with Node.js Express](https://bezkoder.com/integrate-react-express-same-server-port/)
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-redux-hooks-jwt-auth",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^4.2.4",
7 | "@testing-library/react": "^9.3.2",
8 | "@testing-library/user-event": "^7.1.2",
9 | "axios": "^0.27.2",
10 | "bootstrap": "^4.6.1",
11 | "react": "^18.2.0",
12 | "react-dom": "^18.2.0",
13 | "react-redux": "^8.0.1",
14 | "react-router-dom": "^6.4.0",
15 | "react-scripts": "5.0.1",
16 | "react-validation": "^3.0.7",
17 | "redux": "^4.2.0",
18 | "redux-thunk": "^2.4.1",
19 | "validator": "^13.7.0"
20 | },
21 | "scripts": {
22 | "start": "react-scripts start",
23 | "build": "react-scripts build",
24 | "test": "react-scripts test",
25 | "eject": "react-scripts eject"
26 | },
27 | "eslintConfig": {
28 | "extends": "react-app"
29 | },
30 | "browserslist": {
31 | "production": [
32 | ">0.2%",
33 | "not dead",
34 | "not op_mini all"
35 | ],
36 | "development": [
37 | "last 1 chrome version",
38 | "last 1 firefox version",
39 | "last 1 safari version"
40 | ]
41 | },
42 | "devDependencies": {
43 | "redux-devtools-extension": "^2.13.8"
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bezkoder/react-redux-hooks-jwt-auth/b5d0bcf29dbee8c1d763373bc85b5dfda2a8583a/public/favicon.ico
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bezkoder/react-redux-hooks-jwt-auth/b5d0bcf29dbee8c1d763373bc85b5dfda2a8583a/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bezkoder/react-redux-hooks-jwt-auth/b5d0bcf29dbee8c1d763373bc85b5dfda2a8583a/public/logo512.png
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | label {
2 | display: block;
3 | margin-top: 10px;
4 | }
5 |
6 | .card-container.card {
7 | max-width: 350px !important;
8 | padding: 40px 40px;
9 | }
10 |
11 | .card {
12 | background-color: #f7f7f7;
13 | padding: 20px 25px 30px;
14 | margin: 0 auto 25px;
15 | margin-top: 50px;
16 | -moz-border-radius: 2px;
17 | -webkit-border-radius: 2px;
18 | border-radius: 2px;
19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
22 | }
23 |
24 | .profile-img-card {
25 | width: 96px;
26 | height: 96px;
27 | margin: 0 auto 10px;
28 | display: block;
29 | -moz-border-radius: 50%;
30 | -webkit-border-radius: 50%;
31 | border-radius: 50%;
32 | }
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect, useCallback } from "react";
2 | import { useDispatch, useSelector } from "react-redux";
3 | import { Routes, Route, Link, useLocation } from "react-router-dom";
4 |
5 | import "bootstrap/dist/css/bootstrap.min.css";
6 | import "./App.css";
7 |
8 | import Login from "./components/Login";
9 | import Register from "./components/Register";
10 | import Home from "./components/Home";
11 | import Profile from "./components/Profile";
12 | import BoardUser from "./components/BoardUser";
13 | import BoardModerator from "./components/BoardModerator";
14 | import BoardAdmin from "./components/BoardAdmin";
15 |
16 | import { logout } from "./actions/auth";
17 | import { clearMessage } from "./actions/message";
18 |
19 | // import AuthVerify from "./common/AuthVerify";
20 | import EventBus from "./common/EventBus";
21 |
22 | const App = () => {
23 | const [showModeratorBoard, setShowModeratorBoard] = useState(false);
24 | const [showAdminBoard, setShowAdminBoard] = useState(false);
25 |
26 | const { user: currentUser } = useSelector((state) => state.auth);
27 | const dispatch = useDispatch();
28 |
29 | let location = useLocation();
30 |
31 | useEffect(() => {
32 | if (["/login", "/register"].includes(location.pathname)) {
33 | dispatch(clearMessage()); // clear message when changing location
34 | }
35 | }, [dispatch, location]);
36 |
37 | const logOut = useCallback(() => {
38 | dispatch(logout());
39 | }, [dispatch]);
40 |
41 | useEffect(() => {
42 | if (currentUser) {
43 | setShowModeratorBoard(currentUser.roles.includes("ROLE_MODERATOR"));
44 | setShowAdminBoard(currentUser.roles.includes("ROLE_ADMIN"));
45 | } else {
46 | setShowModeratorBoard(false);
47 | setShowAdminBoard(false);
48 | }
49 |
50 | EventBus.on("logout", () => {
51 | logOut();
52 | });
53 |
54 | return () => {
55 | EventBus.remove("logout");
56 | };
57 | }, [currentUser, logOut]);
58 |
59 | return (
60 |
61 |
126 |
127 |
128 |
129 | } />
130 | } />
131 | } />
132 | } />
133 | } />
134 | } />
135 | } />
136 | } />
137 |
138 |
139 |
140 | {/*
*/}
141 |
142 | );
143 | };
144 |
145 | export default App;
146 |
--------------------------------------------------------------------------------
/src/actions/auth.js:
--------------------------------------------------------------------------------
1 | import {
2 | REGISTER_SUCCESS,
3 | REGISTER_FAIL,
4 | LOGIN_SUCCESS,
5 | LOGIN_FAIL,
6 | LOGOUT,
7 | SET_MESSAGE,
8 | } from "./types";
9 |
10 | import AuthService from "../services/auth.service";
11 |
12 | export const register = (username, email, password) => (dispatch) => {
13 | return AuthService.register(username, email, password).then(
14 | (response) => {
15 | dispatch({
16 | type: REGISTER_SUCCESS,
17 | });
18 |
19 | dispatch({
20 | type: SET_MESSAGE,
21 | payload: response.data.message,
22 | });
23 |
24 | return Promise.resolve();
25 | },
26 | (error) => {
27 | const message =
28 | (error.response &&
29 | error.response.data &&
30 | error.response.data.message) ||
31 | error.message ||
32 | error.toString();
33 |
34 | dispatch({
35 | type: REGISTER_FAIL,
36 | });
37 |
38 | dispatch({
39 | type: SET_MESSAGE,
40 | payload: message,
41 | });
42 |
43 | return Promise.reject();
44 | }
45 | );
46 | };
47 |
48 | export const login = (username, password) => (dispatch) => {
49 | return AuthService.login(username, password).then(
50 | (data) => {
51 | dispatch({
52 | type: LOGIN_SUCCESS,
53 | payload: { user: data },
54 | });
55 |
56 | return Promise.resolve();
57 | },
58 | (error) => {
59 | const message =
60 | (error.response &&
61 | error.response.data &&
62 | error.response.data.message) ||
63 | error.message ||
64 | error.toString();
65 |
66 | dispatch({
67 | type: LOGIN_FAIL,
68 | });
69 |
70 | dispatch({
71 | type: SET_MESSAGE,
72 | payload: message,
73 | });
74 |
75 | return Promise.reject();
76 | }
77 | );
78 | };
79 |
80 | export const logout = () => (dispatch) => {
81 | AuthService.logout();
82 |
83 | dispatch({
84 | type: LOGOUT,
85 | });
86 | };
87 |
--------------------------------------------------------------------------------
/src/actions/message.js:
--------------------------------------------------------------------------------
1 | import { SET_MESSAGE, CLEAR_MESSAGE } from "./types";
2 |
3 | export const setMessage = (message) => ({
4 | type: SET_MESSAGE,
5 | payload: message,
6 | });
7 |
8 | export const clearMessage = () => ({
9 | type: CLEAR_MESSAGE,
10 | });
11 |
--------------------------------------------------------------------------------
/src/actions/types.js:
--------------------------------------------------------------------------------
1 | export const REGISTER_SUCCESS = "REGISTER_SUCCESS";
2 | export const REGISTER_FAIL = "REGISTER_FAIL";
3 | export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
4 | export const LOGIN_FAIL = "LOGIN_FAIL";
5 | export const LOGOUT = "LOGOUT";
6 |
7 | export const SET_MESSAGE = "SET_MESSAGE";
8 | export const CLEAR_MESSAGE = "CLEAR_MESSAGE";
9 |
--------------------------------------------------------------------------------
/src/common/AuthVerify.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect } from "react";
2 | import { useLocation } from "react-router-dom";
3 |
4 | const parseJwt = (token) => {
5 | try {
6 | return JSON.parse(atob(token.split(".")[1]));
7 | } catch (e) {
8 | return null;
9 | }
10 | };
11 |
12 | const AuthVerify = (props) => {
13 | let location = useLocation();
14 |
15 | useEffect(() => {
16 | const user = JSON.parse(localStorage.getItem("user"));
17 |
18 | if (user) {
19 | const decodedJwt = parseJwt(user.accessToken);
20 |
21 | if (decodedJwt.exp * 1000 < Date.now()) {
22 | props.logOut();
23 | }
24 | }
25 | }, [location, props]);
26 |
27 | return ;
28 | };
29 |
30 | export default AuthVerify;
31 |
--------------------------------------------------------------------------------
/src/common/EventBus.js:
--------------------------------------------------------------------------------
1 | const eventBus = {
2 | on(event, callback) {
3 | document.addEventListener(event, (e) => callback(e.detail));
4 | },
5 | dispatch(event, data) {
6 | document.dispatchEvent(new CustomEvent(event, { detail: data }));
7 | },
8 | remove(event, callback) {
9 | document.removeEventListener(event, callback);
10 | },
11 | };
12 |
13 | export default eventBus;
14 |
--------------------------------------------------------------------------------
/src/components/BoardAdmin.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from "react";
2 |
3 | import UserService from "../services/user.service";
4 | import EventBus from "../common/EventBus";
5 |
6 | const BoardAdmin = () => {
7 | const [content, setContent] = useState("");
8 |
9 | useEffect(() => {
10 | UserService.getAdminBoard().then(
11 | (response) => {
12 | setContent(response.data);
13 | },
14 | (error) => {
15 | const _content =
16 | (error.response &&
17 | error.response.data &&
18 | error.response.data.message) ||
19 | error.message ||
20 | error.toString();
21 |
22 | setContent(_content);
23 |
24 | if (error.response && error.response.status === 401) {
25 | EventBus.dispatch("logout");
26 | }
27 | }
28 | );
29 | }, []);
30 |
31 | return (
32 |
33 |
36 |
37 | );
38 | };
39 |
40 | export default BoardAdmin;
41 |
--------------------------------------------------------------------------------
/src/components/BoardModerator.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from "react";
2 |
3 | import UserService from "../services/user.service";
4 | import EventBus from "../common/EventBus";
5 |
6 | const BoardModerator = () => {
7 | const [content, setContent] = useState("");
8 |
9 | useEffect(() => {
10 | UserService.getModeratorBoard().then(
11 | (response) => {
12 | setContent(response.data);
13 | },
14 | (error) => {
15 | const _content =
16 | (error.response &&
17 | error.response.data &&
18 | error.response.data.message) ||
19 | error.message ||
20 | error.toString();
21 |
22 | setContent(_content);
23 |
24 | if (error.response && error.response.status === 401) {
25 | EventBus.dispatch("logout");
26 | }
27 | }
28 | );
29 | }, []);
30 |
31 | return (
32 |
33 |
36 |
37 | );
38 | };
39 |
40 | export default BoardModerator;
41 |
--------------------------------------------------------------------------------
/src/components/BoardUser.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from "react";
2 |
3 | import UserService from "../services/user.service";
4 | import EventBus from "../common/EventBus";
5 |
6 | const BoardUser = () => {
7 | const [content, setContent] = useState("");
8 |
9 | useEffect(() => {
10 | UserService.getUserBoard().then(
11 | (response) => {
12 | setContent(response.data);
13 | },
14 | (error) => {
15 | const _content =
16 | (error.response &&
17 | error.response.data &&
18 | error.response.data.message) ||
19 | error.message ||
20 | error.toString();
21 |
22 | setContent(_content);
23 |
24 | if (error.response && error.response.status === 401) {
25 | EventBus.dispatch("logout");
26 | }
27 | }
28 | );
29 | }, []);
30 |
31 | return (
32 |
33 |
36 |
37 | );
38 | };
39 |
40 | export default BoardUser;
41 |
--------------------------------------------------------------------------------
/src/components/Home.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from "react";
2 |
3 | import UserService from "../services/user.service";
4 |
5 | const Home = () => {
6 | const [content, setContent] = useState("");
7 |
8 | useEffect(() => {
9 | UserService.getPublicContent().then(
10 | (response) => {
11 | setContent(response.data);
12 | },
13 | (error) => {
14 | const _content =
15 | (error.response && error.response.data) ||
16 | error.message ||
17 | error.toString();
18 |
19 | setContent(_content);
20 | }
21 | );
22 | }, []);
23 |
24 | return (
25 |
26 |
29 |
30 | );
31 | };
32 |
33 | export default Home;
34 |
--------------------------------------------------------------------------------
/src/components/Login.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useRef } from "react";
2 | import { useDispatch, useSelector } from "react-redux";
3 | import { Navigate, useNavigate } from 'react-router-dom';
4 |
5 | import Form from "react-validation/build/form";
6 | import Input from "react-validation/build/input";
7 | import CheckButton from "react-validation/build/button";
8 |
9 | import { login } from "../actions/auth";
10 |
11 | const required = (value) => {
12 | if (!value) {
13 | return (
14 |
15 | This field is required!
16 |
17 | );
18 | }
19 | };
20 |
21 | const Login = (props) => {
22 | let navigate = useNavigate();
23 |
24 | const form = useRef();
25 | const checkBtn = useRef();
26 |
27 | const [username, setUsername] = useState("");
28 | const [password, setPassword] = useState("");
29 | const [loading, setLoading] = useState(false);
30 |
31 | const { isLoggedIn } = useSelector(state => state.auth);
32 | const { message } = useSelector(state => state.message);
33 |
34 | const dispatch = useDispatch();
35 |
36 | const onChangeUsername = (e) => {
37 | const username = e.target.value;
38 | setUsername(username);
39 | };
40 |
41 | const onChangePassword = (e) => {
42 | const password = e.target.value;
43 | setPassword(password);
44 | };
45 |
46 | const handleLogin = (e) => {
47 | e.preventDefault();
48 |
49 | setLoading(true);
50 |
51 | form.current.validateAll();
52 |
53 | if (checkBtn.current.context._errors.length === 0) {
54 | dispatch(login(username, password))
55 | .then(() => {
56 | navigate("/profile");
57 | window.location.reload();
58 | })
59 | .catch(() => {
60 | setLoading(false);
61 | });
62 | } else {
63 | setLoading(false);
64 | }
65 | };
66 |
67 | if (isLoggedIn) {
68 | return ;
69 | }
70 |
71 | return (
72 |
73 |
74 |

79 |
80 |
123 |
124 |
125 | );
126 | };
127 |
128 | export default Login;
129 |
--------------------------------------------------------------------------------
/src/components/Profile.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Navigate } from 'react-router-dom';
3 | import { useSelector } from "react-redux";
4 |
5 | const Profile = () => {
6 | const { user: currentUser } = useSelector((state) => state.auth);
7 |
8 | if (!currentUser) {
9 | return ;
10 | }
11 |
12 | return (
13 |
14 |
15 |
16 | {currentUser.username} Profile
17 |
18 |
19 |
20 | Token: {currentUser.accessToken.substring(0, 20)} ...{" "}
21 | {currentUser.accessToken.substr(currentUser.accessToken.length - 20)}
22 |
23 |
24 | Id: {currentUser.id}
25 |
26 |
27 | Email: {currentUser.email}
28 |
29 |
Authorities:
30 |
31 | {currentUser.roles &&
32 | currentUser.roles.map((role, index) => - {role}
)}
33 |
34 |
35 | );
36 | };
37 |
38 | export default Profile;
39 |
--------------------------------------------------------------------------------
/src/components/Register.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useRef } from "react";
2 | import { useDispatch, useSelector } from "react-redux";
3 |
4 | import Form from "react-validation/build/form";
5 | import Input from "react-validation/build/input";
6 | import CheckButton from "react-validation/build/button";
7 | import { isEmail } from "validator";
8 |
9 | import { register } from "../actions/auth";
10 |
11 | const required = (value) => {
12 | if (!value) {
13 | return (
14 |
15 | This field is required!
16 |
17 | );
18 | }
19 | };
20 |
21 | const validEmail = (value) => {
22 | if (!isEmail(value)) {
23 | return (
24 |
25 | This is not a valid email.
26 |
27 | );
28 | }
29 | };
30 |
31 | const vusername = (value) => {
32 | if (value.length < 3 || value.length > 20) {
33 | return (
34 |
35 | The username must be between 3 and 20 characters.
36 |
37 | );
38 | }
39 | };
40 |
41 | const vpassword = (value) => {
42 | if (value.length < 6 || value.length > 40) {
43 | return (
44 |
45 | The password must be between 6 and 40 characters.
46 |
47 | );
48 | }
49 | };
50 |
51 | const Register = () => {
52 | const form = useRef();
53 | const checkBtn = useRef();
54 |
55 | const [username, setUsername] = useState("");
56 | const [email, setEmail] = useState("");
57 | const [password, setPassword] = useState("");
58 | const [successful, setSuccessful] = useState(false);
59 |
60 | const { message } = useSelector(state => state.message);
61 | const dispatch = useDispatch();
62 |
63 | const onChangeUsername = (e) => {
64 | const username = e.target.value;
65 | setUsername(username);
66 | };
67 |
68 | const onChangeEmail = (e) => {
69 | const email = e.target.value;
70 | setEmail(email);
71 | };
72 |
73 | const onChangePassword = (e) => {
74 | const password = e.target.value;
75 | setPassword(password);
76 | };
77 |
78 | const handleRegister = (e) => {
79 | e.preventDefault();
80 |
81 | setSuccessful(false);
82 |
83 | form.current.validateAll();
84 |
85 | if (checkBtn.current.context._errors.length === 0) {
86 | dispatch(register(username, email, password))
87 | .then(() => {
88 | setSuccessful(true);
89 | })
90 | .catch(() => {
91 | setSuccessful(false);
92 | });
93 | }
94 | };
95 |
96 | return (
97 |
98 |
99 |

104 |
105 |
159 |
160 |
161 | );
162 | };
163 |
164 | export default Register;
165 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { createRoot } from "react-dom/client";
3 | import { Provider } from "react-redux";
4 | import store from "./store";
5 | import "./index.css";
6 | import App from "./App";
7 | import * as serviceWorker from "./serviceWorker";
8 |
9 | import { BrowserRouter } from "react-router-dom";
10 |
11 | const container = document.getElementById("root");
12 | const root = createRoot(container);
13 |
14 | root.render(
15 |
16 |
17 |
18 |
19 |
20 | );
21 |
22 | // If you want your app to work offline and load faster, you can chađinge
23 | // unregister() to register() below. Note this comes with some pitfalls.
24 | // Learn more about service workers: https://bit.ly/CRA-PWA
25 | serviceWorker.unregister();
26 |
--------------------------------------------------------------------------------
/src/reducers/auth.js:
--------------------------------------------------------------------------------
1 | import {
2 | REGISTER_SUCCESS,
3 | REGISTER_FAIL,
4 | LOGIN_SUCCESS,
5 | LOGIN_FAIL,
6 | LOGOUT,
7 | } from "../actions/types";
8 |
9 | const user = JSON.parse(localStorage.getItem("user"));
10 |
11 | const initialState = user
12 | ? { isLoggedIn: true, user }
13 | : { isLoggedIn: false, user: null };
14 |
15 | export default function (state = initialState, action) {
16 | const { type, payload } = action;
17 |
18 | switch (type) {
19 | case REGISTER_SUCCESS:
20 | return {
21 | ...state,
22 | isLoggedIn: false,
23 | };
24 | case REGISTER_FAIL:
25 | return {
26 | ...state,
27 | isLoggedIn: false,
28 | };
29 | case LOGIN_SUCCESS:
30 | return {
31 | ...state,
32 | isLoggedIn: true,
33 | user: payload.user,
34 | };
35 | case LOGIN_FAIL:
36 | return {
37 | ...state,
38 | isLoggedIn: false,
39 | user: null,
40 | };
41 | case LOGOUT:
42 | return {
43 | ...state,
44 | isLoggedIn: false,
45 | user: null,
46 | };
47 | default:
48 | return state;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/reducers/index.js:
--------------------------------------------------------------------------------
1 | import { combineReducers } from "redux";
2 | import auth from "./auth";
3 | import message from "./message";
4 |
5 | export default combineReducers({
6 | auth,
7 | message,
8 | });
9 |
--------------------------------------------------------------------------------
/src/reducers/message.js:
--------------------------------------------------------------------------------
1 | import { SET_MESSAGE, CLEAR_MESSAGE } from "../actions/types";
2 |
3 | const initialState = {};
4 |
5 | export default function (state = initialState, action) {
6 | const { type, payload } = action;
7 |
8 | switch (type) {
9 | case SET_MESSAGE:
10 | return { message: payload };
11 |
12 | case CLEAR_MESSAGE:
13 | return { message: "" };
14 |
15 | default:
16 | return state;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/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.0/8 are 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 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/src/services/auth-header.js:
--------------------------------------------------------------------------------
1 | export default function authHeader() {
2 | const user = JSON.parse(localStorage.getItem("user"));
3 |
4 | if (user && user.accessToken) {
5 | // For Spring Boot back-end
6 | // return { Authorization: "Bearer " + user.accessToken };
7 |
8 | // for Node.js Express back-end
9 | return { "x-access-token": user.accessToken };
10 | } else {
11 | return {};
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/services/auth.service.js:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 |
3 | const API_URL = "http://localhost:8080/api/auth/";
4 |
5 | const register = (username, email, password) => {
6 | return axios.post(API_URL + "signup", {
7 | username,
8 | email,
9 | password,
10 | });
11 | };
12 |
13 | const login = (username, password) => {
14 | return axios
15 | .post(API_URL + "signin", {
16 | username,
17 | password,
18 | })
19 | .then((response) => {
20 | if (response.data.accessToken) {
21 | localStorage.setItem("user", JSON.stringify(response.data));
22 | }
23 |
24 | return response.data;
25 | });
26 | };
27 |
28 | const logout = () => {
29 | localStorage.removeItem("user");
30 | };
31 |
32 | export default {
33 | register,
34 | login,
35 | logout,
36 | };
37 |
--------------------------------------------------------------------------------
/src/services/user.service.js:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 | import authHeader from "./auth-header";
3 |
4 | const API_URL = "http://localhost:8080/api/test/";
5 |
6 | const getPublicContent = () => {
7 | return axios.get(API_URL + "all");
8 | };
9 |
10 | const getUserBoard = () => {
11 | return axios.get(API_URL + "user", { headers: authHeader() });
12 | };
13 |
14 | const getModeratorBoard = () => {
15 | return axios.get(API_URL + "mod", { headers: authHeader() });
16 | };
17 |
18 | const getAdminBoard = () => {
19 | return axios.get(API_URL + "admin", { headers: authHeader() });
20 | };
21 |
22 | export default {
23 | getPublicContent,
24 | getUserBoard,
25 | getModeratorBoard,
26 | getAdminBoard,
27 | };
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------
/src/store.js:
--------------------------------------------------------------------------------
1 | import { createStore, applyMiddleware } from "redux";
2 | import { composeWithDevTools } from "redux-devtools-extension";
3 | import thunk from "redux-thunk";
4 | import rootReducer from "./reducers";
5 |
6 | const middleware = [thunk];
7 |
8 | const store = createStore(
9 | rootReducer,
10 | composeWithDevTools(applyMiddleware(...middleware))
11 | );
12 |
13 | export default store;
14 |
--------------------------------------------------------------------------------