Skip to content

Commit 0d8c73b

Browse files
committed
Initial commit
0 parents  commit 0d8c73b

File tree

26 files changed

+39150
-0
lines changed

26 files changed

+39150
-0
lines changed

.DS_Store

6 KB
Binary file not shown.

.gitattributes

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Auto detect text files and perform LF normalization
2+
* text=auto

README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# react-bhx-auth
2+
3+
Authentication is one of the most time-consuming things to do when you have to deal with web projects. This projects is a ReactJS authentication using [JWT (json web token)](https://jwt.io/) with REST calls to a server.
4+
5+
There's a backend folder inside the project with PHP pages (Apache server) for login.
6+
7+
The token is saved locally using [local storage](https://developer.mozilla.org/pt-BR/docs/Web/API/Window/localStorage).
8+
9+
## Feat
10+
11+
- ReactJS with create-react-app
12+
- Typescript
13+
- JWT - Token
14+
- PHP backend
15+
- REST
16+
- [Axios](https://www.npmjs.com/package/axios)
17+
18+
## How to use
19+
20+
In order to use this project get the component's folder (components/Auth) and the helper's folder. In components, the component Auth has two main functions:
21+
22+
- serverLoginUser: to send a post request to login
23+
- getAuth: get the current status of the user.
24+
25+
## Login form
26+
27+
In the example inside this project you can test one form login but you can pretty much use the form validator you like.
28+
29+
## Local storage
30+
31+
When the user loggin successfully, the component save a json inside the local storage.
32+
33+
```json
34+
{
35+
"auth": {
36+
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJiaHhzaXRlcyIsImVtYWlsIjoiZm9vQG1haWwuY29tIn0.Sk0VtWo_UNSaW-TfGjvMGpiOwxx4cz9SEDkjx70MZvE",
37+
"email": "foo@mail.com",
38+
"timestamp": "2020-09-02 21:14:13"
39+
}
40+
}
41+
```
42+
43+
## Backend
44+
45+
Even though is not the main purpose, inside this project you will find a backend folder with PHP files.
46+
47+
You can put this folder inside your [localhost](http://localhost) and change the endpoint inside the components folder. The default value for this is pointing to some BHX Sites path with the same file but you can do this locally or even try use NodeJS instead of PHP (Apache).
48+
49+
### Fake data inside PHP
50+
51+
For testing purposes you will need to put **foo@mail.com** as e-mail and **123** as password.
52+
53+
Inside the PHP (login.php) page you will find the a simple checker to check if the login is correct.
54+
55+
```php
56+
// fake database return
57+
$DATABASE_PASSWORD = md5('123');
58+
$DATABASE_EMAIL = 'foo@mail.com';
59+
```
60+
61+
### JWT serverKey
62+
63+
In order to use JWT you have to define a key (string). Set this inside the PHP page (auth.php)
64+
65+
```php
66+
// JWT config
67+
$JWTServerkey = '123123';
68+
```
69+
70+
## Example
71+
72+
![login.gif](react-bhx-auth%209006df9d7f2a492388f768486923f721/login.gif)

backend/.DS_Store

6 KB
Binary file not shown.

backend/check.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
header('Content-Type: application/json; charset=UTF-8');
4+
5+
// JWT auth
6+
include "connect/auth.php";
7+
8+
$dataResponse = array();
9+
$dataResponse['status'] = 1;
10+
$dataResponse['message'] = '';
11+
$errors = array();
12+
13+
$currentTimestamp = Date('Y-m-d H:i:s');
14+
$userEmail = addslashes(trim($_GET['email']));
15+
16+
$isAuth = verifyAuth($clientToken, $JWTServerkey);
17+
18+
19+
if($isAuth) {
20+
21+
$emailValidation = createJWTAuth($userEmail, $JWTServerkey);
22+
23+
if('Bearer '.$emailValidation === $clientToken) {
24+
$dataResponse['timestamp'] = $currentTimestamp;
25+
$dataResponse['status'] = 1;
26+
$dataResponse['email'] = $userEmail;
27+
$dataResponse['token'] = $emailValidation;
28+
$dataResponse['message'] = 'Valid Token and valid Email';
29+
} else {
30+
$dataResponse['timestamp'] = $currentTimestamp;
31+
$dataResponse['status'] = 3;
32+
$dataResponse['message'] = 'Valid Token but invalid email';
33+
}
34+
} else {
35+
$dataResponse['timestamp'] = $currentTimestamp;
36+
$dataResponse['status'] = 2;
37+
$dataResponse['message'] = 'Invalid Token';
38+
}
39+
40+
$resultadosJson = json_encode($dataResponse);
41+
echo $resultadosJson;

backend/connect/auth.php

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
<?php
2+
// access
3+
header('Access-Control-Allow-Origin: *');
4+
header('Access-Control-Allow-Credentials: true');
5+
header('Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT');
6+
header('Access-Control-Allow-Headers: Authorization, Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
7+
8+
//conecta ao banco
9+
error_reporting(0);
10+
date_default_timezone_set('America/Sao_Paulo');
11+
12+
// JWT config
13+
$JWTServerkey = '123123';
14+
15+
// JWT key data
16+
$httpHeaderData = apache_request_headers();
17+
if(isset($httpHeaderData['authorization']) || isset($httpHeaderData['Authorization'])) {
18+
$clientToken = isset($httpHeaderData['authorization']) ? $httpHeaderData['authorization'] : $httpHeaderData['Authorization'];
19+
}
20+
21+
//
22+
function createJWTAuth($email, $key) {
23+
24+
$header = [
25+
'alg' => 'HS256',
26+
'typ' => 'JWT'
27+
];
28+
$header = json_encode($header);
29+
$header = base64UrlEncode($header);
30+
31+
$payload = [
32+
'iss' => 'bhxsites',
33+
'email' => $email
34+
];
35+
$payload = json_encode($payload);
36+
$payload = base64UrlEncode($payload);
37+
38+
$signature = hash_hmac('sha256', $header . "." . $payload , $key , true );
39+
$signature = base64UrlEncode($signature);
40+
41+
42+
return $header.".".$payload.".".$signature;
43+
}
44+
45+
//
46+
function verifyAuth($headerToken, $key) {
47+
48+
49+
50+
$bearer = explode (' ', $headerToken);
51+
$isValidAuth = 0;
52+
53+
$token = explode('.', $bearer[1]);
54+
$header = $token[0];
55+
$payload = $token[1];
56+
$sign = $token[2];
57+
58+
$valid = hash_hmac('sha256', $header . "." . $payload , $key , true);
59+
$valid = base64UrlEncode($valid);
60+
61+
62+
if ($sign == $valid) {
63+
return true;
64+
} else {
65+
return false;
66+
}
67+
}
68+
69+
70+
//
71+
function base64UrlEncode ($value) {
72+
$b64 = base64_encode($value);
73+
if ($b64 === false) {
74+
return false;
75+
}
76+
$url = strtr($b64, '+/', '-_');
77+
return rtrim($url, '=');
78+
}
79+
80+
81+
//
82+
function getAuthorizatedUserData($connection, $userEmail, $JWTServerkey, $clientToken) {
83+
84+
$responseData = array(
85+
'status' => '0',
86+
'id' => '0',
87+
'email' => '0'
88+
);
89+
$emailValidation = createJWTAuth($userEmail, $JWTServerkey);
90+
91+
// check if email is correct
92+
if('Bearer '.$emailValidation === $clientToken) {
93+
94+
// find user id
95+
$queryUsers = mysqli_query($connection, "SELECT
96+
usr_id,
97+
usr_email
98+
FROM users
99+
WHERE usr_email = '{$userEmail}' AND usr_status = 1
100+
ORDER BY usr_id
101+
DESC
102+
LIMIT 1") or die ("User Not Found");
103+
104+
// check if user was found
105+
if (mysqli_num_rows ($queryUsers) > 0) {
106+
$dataUser = mysqli_fetch_assoc($queryUsers);
107+
$responseData['status'] = 1;
108+
$responseData['id'] = $dataUser['usr_id'];
109+
$responseData['email'] = $dataUser['usr_email'];
110+
} else {
111+
112+
// no user
113+
$responseData['status'] = 2;
114+
}
115+
116+
} else {
117+
118+
// not auth
119+
$responseData['status'] = 2;
120+
}
121+
122+
return $responseData;
123+
}

backend/login.php

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
header('Content-Type: application/json; charset=UTF-8');
4+
5+
// JWT auth
6+
include "connect/auth.php";
7+
8+
$dataResponse = array();
9+
$dataResponse['status'] = 0;
10+
$dataResponse['message'] = '';
11+
$errors = array();
12+
13+
// var
14+
$userEmail = addslashes(trim($_POST['email']));
15+
$userEmail = str_replace(" ", "", $userEmail);
16+
17+
$userPassword = addslashes(trim($_POST['password']));
18+
$userPassword = str_replace(" ", "", $userPassword);
19+
$userPasswordMd5 = md5($userPassword);
20+
$currentTimestamp = Date('Y-m-d H:i:s');
21+
22+
// creating new token JWT
23+
$token = createJWTAuth($userEmail, $JWTServerkey);
24+
25+
// verify
26+
$validInputs = false;
27+
28+
// check input
29+
if( $userEmail != '' && strlen($userEmail) >= 3 && $userPassword != '' && strlen($userPassword) >= 3 ) {
30+
$validInputs = true;
31+
} else {
32+
$dataResponse['message'] = 'Empty field not allowed';
33+
$dataResponse['status'] = 2;
34+
}
35+
36+
if($validInputs) {
37+
38+
// fake database return
39+
$DATABASE_PASSWORD = md5('123');
40+
$DATABASE_EMAIL = 'foo@mail.com';
41+
42+
if( $DATABASE_EMAIL == $userEmail && $DATABASE_PASSWORD == $userPasswordMd5) {
43+
44+
$dataResponse['token'] = $token;
45+
$dataResponse['timestamp'] = $currentTimestamp;
46+
47+
$dataResponse['user'] = array(
48+
'id' => 1,
49+
'email' => $userEmail,
50+
);
51+
$dataResponse['status'] = 1;
52+
$dataResponse['message'] = 'Logged';
53+
54+
} else {
55+
$dataResponse['message'] = 'Invalid E-mail or Password';
56+
$dataResponse['status'] = 3;
57+
}
58+
}
59+
60+
$resultadosJson = json_encode($dataResponse);
61+
echo $resultadosJson;

react-app/.gitignore

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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*

react-app/README.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Getting Started with Create React App
2+
3+
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4+
5+
## Available Scripts
6+
7+
In the project directory, you can run:
8+
9+
### `npm start`
10+
11+
Runs the app in the development mode.\
12+
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13+
14+
The page will reload if you make edits.\
15+
You will also see any lint errors in the console.
16+
17+
### `npm test`
18+
19+
Launches the test runner in the interactive watch mode.\
20+
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21+
22+
### `npm run build`
23+
24+
Builds the app for production to the `build` folder.\
25+
It correctly bundles React in production mode and optimizes the build for the best performance.
26+
27+
The build is minified and the filenames include the hashes.\
28+
Your app is ready to be deployed!
29+
30+
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31+
32+
### `npm run eject`
33+
34+
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35+
36+
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37+
38+
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39+
40+
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41+
42+
## Learn More
43+
44+
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45+
46+
To learn React, check out the [React documentation](https://reactjs.org/).

0 commit comments

Comments
 (0)