Initial Commit

main
Tushar Kapil 2 years ago
commit 4b251540ea

BIN
.DS_Store vendored

Binary file not shown.

BIN
client/.DS_Store vendored

Binary file not shown.

27238
client/package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,40 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.1",
"react-scripts": "5.0.0",
"react-toastify": "^8.1.0",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

@ -0,0 +1,87 @@
import "./App.css";
import { Fragment, useState, useEffect } from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import {
BrowserRouter as Router,
Route,
Routes,
Navigate,
} from "react-router-dom";
import Login from "./components/Login";
import Dashboard from "./components/Dashboard";
import Register from "./components/Register";
toast.configure();
function App() {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const setAuth = (boolean) => {
setIsAuthenticated(boolean);
};
const isAuth = async () => {
try {
const response = await fetch("http://localhost:5000/auth/is-verify", {
method: "GET",
headers: { token: localStorage.token },
});
const parseRes = await response.json();
parseRes === true ? setIsAuthenticated(true) : setIsAuthenticated(false);
} catch (error) {
console.log(error.message);
}
};
useEffect(() => {
isAuth();
}, []);
return (
<Fragment>
<ToastContainer />
<Router>
<div className="container">
<Routes>
<Route path="/" element={<Navigate to="/login" />} />
<Route
path="/login"
element={
!isAuthenticated ? (
<Login setAuth={setAuth} />
) : (
<Navigate to="/dashboard" />
)
}
/>
<Route
path="/register"
element={
!isAuthenticated ? (
<Register setAuth={setAuth} />
) : (
<Navigate to="/login" />
)
}
/>
<Route
path="/dashboard"
element={
isAuthenticated ? (
<Dashboard setAuth={setAuth} />
) : (
<Navigate to="/login" />
)
}
/>
</Routes>
</div>
</Router>
</Fragment>
);
}
export default App;

@ -0,0 +1,43 @@
import React, { Fragment, useState, useEffect } from "react";
import { toast } from "react-toastify";
import "./dashboard.css";
const Dashboard = ({ setAuth }) => {
const [name, setName] = useState("");
const getName = async () => {
try {
const response = await fetch("http://localhost:5000/dashboard/", {
method: "GET",
headers: { token: localStorage.token },
});
const parseRes = await response.json();
setName(parseRes.user_name);
} catch (error) {
console.log(error);
}
};
const logOut = (e) => {
e.preventDefault();
localStorage.removeItem("token");
setAuth(false);
toast.success("Uh oh GoodBye :(");
};
useEffect(() => {
getName();
}, []);
return (
<Fragment>
<div className="container1">
<h1 className="heading">Hello {name} ! Welcome To The Dashboard.</h1>
<button className="btn btn-primary bt" onClick={(e) => logOut(e)}>
Log Out
</button>
</div>
</Fragment>
);
};
export default Dashboard;

@ -0,0 +1,74 @@
import React, { Fragment, useState } from "react";
import { Link } from "react-router-dom";
import { ToastContainer, toast } from "react-toastify";
const Login = ({ setAuth }) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const emailHandler = (e) => {
setEmail(e.target.value);
};
const passwordHandler = (e) => {
setPassword(e.target.value);
};
const submitHandler = async (e) => {
e.preventDefault();
const body = { email, password };
try {
const response = await fetch("http://localhost:5000/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const parseRes = await response.json();
if (parseRes.token) {
localStorage.setItem("token", parseRes.token);
setAuth(true);
toast.success("login success");
} else {
setAuth(false);
toast.error(parseRes);
}
} catch (error) {
console.log(error.message);
}
};
toast.configure();
return (
<Fragment>
<ToastContainer />
<h1 className="text-center my-5">Login</h1>
<form onSubmit={submitHandler}>
<input
type="email"
name="email"
placeholder="email"
className="form-control my-3"
value={email}
onChange={(e) => emailHandler(e)}
/>
<input
type="password"
name="password"
placeholder="password"
className="form-control my-3"
value={password}
onChange={(e) => passwordHandler(e)}
/>
<button className="btn btn-success btn-block">Log In</button>
</form>
<Link className="register" to="/register">
Don't Have An Account ? Register Here
</Link>
</Fragment>
);
};
export default Login;

@ -0,0 +1,85 @@
import React, { Fragment, useState } from "react";
import { Link } from "react-router-dom";
import { toast } from "react-toastify";
import "./register.css";
const Register = ({ setAuth }) => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const nameHandler = (e) => {
setName(e.target.value);
};
const emailHandler = (e) => {
setEmail(e.target.value);
};
const passwordHandler = (e) => {
setPassword(e.target.value);
};
const submitHandler = async (e) => {
e.preventDefault();
const body = { name, email, password };
try {
const response = await fetch("http://localhost:5000/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const parseRes = await response.json();
if (parseRes.token) {
localStorage.setItem("token", parseRes.token);
setAuth(true);
toast.success("Registration Success");
} else {
toast.error(parseRes);
}
} catch (error) {
console.log(error.message);
}
// setEmail("");
// setName("");
// setPassword("");
};
return (
<Fragment>
<h1 className="text-center my-5 register_h1">Register</h1>
<form onSubmit={submitHandler}>
<input
type="email"
placeholder="email"
name="email"
className="form-control my-3"
value={email}
onChange={(e) => emailHandler(e)}
/>
<input
type="text"
placeholder="name"
name="text"
className="form-control my-3"
value={name}
onChange={(e) => nameHandler(e)}
/>
<input
type="password"
name="password"
placeholder="password"
className="form-control my-3"
value={password}
onChange={(e) => passwordHandler(e)}
/>
<button className="btn btn-success btn-block">Register</button>
</form>
<Link className="register" to="/login">
Already Have An Account? Login Here
</Link>
</Fragment>
);
};
export default Register;

@ -0,0 +1,25 @@
.heading {
text-align: center;
font-family: Arial, Helvetica, sans-serif;
background-color: #f3ec78;
background-image: linear-gradient(45deg, #f3ec78, #af4261);
background-size: 100%;
-webkit-background-clip: text;
-moz-background-clip: text;
-webkit-text-fill-color: transparent;
-moz-text-fill-color: transparent;
font-weight: 700;
margin-bottom: 100px;
margin-top: 100px;
}
.container1 {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
body {
background-color: rgb(248, 244, 244);
}

@ -0,0 +1,11 @@
.register_h1 {
font-weight: 700;
font-family: Arial, Helvetica, sans-serif;
background-color: #f3ec78;
background-image: linear-gradient(45deg, #f3ec78, #af4261);
background-size: 100%;
-webkit-background-clip: text;
-moz-background-clip: text;
-webkit-text-fill-color: transparent;
-moz-text-fill-color: transparent;
}

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

@ -0,0 +1,11 @@
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);

@ -0,0 +1 @@
jwtSecret = tushar

@ -0,0 +1,11 @@
const { Pool } = require("pg");
const pool = new Pool({
user: "tushar",
password: "",
host: "localhost",
port: 5432,
database: "jwt",
});
module.exports = pool;

@ -0,0 +1,9 @@
CREATE TABLE users(
user_id uuid PRIMARY KEY DEFAULT
uuid_generate_v4(),
user_name VARCHAR(255) NOT NULL,
user_email VARCHAR(255) NOT NULL,
user_password VARCHAR(255) NOT NULL
);
INSERT INTO users (user_name, user_email, user_password) VALUES ('Tushar', 'tushar20@gmail.com', '1234');

@ -0,0 +1,14 @@
const express = require("express");
const app = express();
const cors = require("cors");
// MIDDLEWARES
app.use(express.json());
app.use(cors());
// ROUTES
app.use("/auth", require("./routes/jwtauth"));
app.use("/dashboard", require("./routes/dashboard"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Running On Port ${PORT}`));

@ -0,0 +1,18 @@
const jwt = require("jsonwebtoken");
require("dotenv").config();
module.exports = async (req, res, next) => {
try {
const jwtToken = req.header("token");
if (!jwtToken) {
return res.status(403).json("Not Authorized");
}
const payload = jwt.verify(jwtToken, process.env.jwtSecret);
req.user = payload.user;
next();
} catch (error) {
return res.status(403).json("Not Authorized");
}
};

@ -0,0 +1,23 @@
module.exports = function (req, res, next) {
const { email, name, password } = req.body;
function validEmail(userEmail) {
return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(userEmail);
}
if (req.path === "/register") {
if (![email, name, password].every(Boolean)) {
return res.json("Missing Credentials");
} else if (!validEmail(email)) {
return res.json("Invalid Email");
}
} else if (req.path === "/login") {
if (![email, password].every(Boolean)) {
return res.json("Missing Credentials");
} else if (!validEmail(email)) {
return res.json("Invalid Email");
}
}
next();
};

File diff suppressed because it is too large Load Diff

@ -0,0 +1,21 @@
{
"name": "jwt",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"cors": "^2.8.5",
"dotenv": "^14.2.0",
"express": "^4.17.2",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.15",
"pg": "^8.7.1"
}
}

@ -0,0 +1,17 @@
const pool = require("../db");
const authorization = require("../middlewares/authorization");
const router = require("express").Router();
router.get("/", authorization, async (req, res) => {
try {
const user = await pool.query(
"SELECT user_name FROM users WHERE user_id = $1",
[req.user]
);
res.json(user.rows[0]);
} catch (error) {
return res.status(500).json("Server Error");
}
});
module.exports = router;

@ -0,0 +1,77 @@
const router = require("express").Router();
const pool = require("../db");
const bcrypt = require("bcrypt");
const jwtGenerator = require("../utils/jwtGenerator");
const validInfo = require("../middlewares/validinfo");
const authorization = require("../middlewares/authorization");
// Register Route
router.post("/register", validInfo, async (req, res) => {
try {
// Destructre From Body
const { name, email, password } = req.body;
//Check For existing User
const user = await pool.query("SELECT * FROM users WHERE user_email = $1", [
email,
]);
if (user.rows.length > 0) {
return res.status(401).json("User Already Exists !");
}
// Bcrypt Password
const saltRound = 10;
const salt = await bcrypt.genSalt(saltRound);
const bcryptPassword = await bcrypt.hash(password, salt);
// Save User In databse
const newUser = await pool.query(
"INSERT INTO users (user_name,user_email,user_password) Values($1,$2,$3) returning * ",
[name, email, bcryptPassword]
);
// Create JWT Token
const token = jwtGenerator(newUser.rows[0].user_id);
res.json({ token });
} catch (error) {
res.status(500).send("Server error");
}
});
// Login Route
router.post("/login", validInfo, async (req, res) => {
// 1. Destructre req.body
const { email, password } = req.body;
// 2. Check for Existing User
const user = await pool.query("SELECT * FROM users WHERE user_email = $1", [
email,
]);
if (user.rows.length === 0) {
return res.status(401).json("Email or Password is Incorrect");
}
// 3. Compare Password
const validPassword = await bcrypt.compare(
password,
user.rows[0].user_password
);
if (!validPassword) {
return res.status(401).json("Email or Password is Incorrect");
}
// 4, Generate JWT
const token = jwtGenerator(user.rows[0].user_id);
res.json({ token });
});
// Verify User
router.get("/is-verify", authorization, async (req, res) => {
try {
res.json(true);
} catch (error) {
res.status(500).send("Server error");
}
});
module.exports = router;

@ -0,0 +1,11 @@
const jwt = require("jsonwebtoken");
require("dotenv").config();
function jwtGenerator(user_id) {
const payload = {
user: user_id,
};
return jwt.sign(payload, process.env.jwtSecret, { expiresIn: "1hr" });
}
module.exports = jwtGenerator;
Loading…
Cancel
Save