Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions API-Authentication-JWT-main/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@

# Created by https://www.toptal.com/developers/gitignore/api/node,react
# Edit at https://www.toptal.com/developers/gitignore?templates=node,react

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test
.env.production

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

### react ###
.DS_*
**/*.backup.*
**/*.back.*

node_modules

*.sublime*

psd
thumb
sketch

# End of https://www.toptal.com/developers/gitignore/api/node,react
71 changes: 71 additions & 0 deletions API-Authentication-JWT-main/Backend/Controllers/UserController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const User = require("../model/User");
const bcrypt = require("bcryptjs");
const jwt = require('jsonwebtoken');
const {
LoginSchema,
RegistreSchema,
} = require("../Validation/authSchema");


module.exports = {
Register: async (req, res) => {

// Validate data
const { error } = dataValidation(RegistreSchema, req.body);
if (error) return res.status(400).send(error);

// Checking if the user is already in the database
const emailExist = await User.findOne({ email: req.body.email });
if (emailExist) return res.status(400).send("Email is already exist");

// Hash the password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);

// Create a new User
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword,
});
try {
await user.save();
res.send({ user: user._id });
} catch (err) {
res.status(400).send(err);
}
},


Login: async (req, res) => {

// Validate data
const { error } = dataValidation(LoginSchema ,req.body);
if (error) return res.status(400).send(error);

// Checking if the email exist
const user = await User.findOne({ email: req.body.email });
if (!user) return res.status(400).send("Email doesn't exist");

// Checking if password correct
const validPass = await bcrypt.compare(req.body.password, user.password);
if(!validPass) return res.status(400).send("Invalid Password");

// Create and assign a token
const token = jwt.sign({_id: user._id}, process.env.Token_Secret);
res.header('auth-token', token);

result = {
message: 'logged in successfully',
token
}
res.send(result);

},

Private: (req, res) => {
res.send('you are allowed to access this private route !!!');
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const Joi = require('@hapi/joi');

const dataValidation = (Schema, data) => {
return Schema.validate(data);
}

module.exports.dataValidation = dataValidation;
14 changes: 14 additions & 0 deletions API-Authentication-JWT-main/Backend/Middleware/verifyToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const jwt = require('jsonwebtoken');

module.exports = function(req,res,next){
const token = req.header('auth-token');
if(!token) return res.status(401).send('Access Denied');

try{
const verified = jwt.verify(token, process.env.Token_Secret);
req.user = verified;
next();
}catch(err){
res.status(400).send('Invalid Token');
}
}
71 changes: 71 additions & 0 deletions API-Authentication-JWT-main/Backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# API-Authentication-JWT

This project is a sample implementation of an authentication system that uses JSON Web Token to manage users' login data in Node.js web server.

Express.js, Mongoose Syntax is used in this project.


# Installing & Configuration

1. Install dependencies

```
npm install
```

2. Run the server

```
npm start
```

# APIs

## Auth Route

### Register

POST `/api/user/register`
```
{
username,
email,
password
}
```
Description: creates a new user; Password is stored in HMAC-SHA1 format.


### Login

POST `/api/user/login`

```
{
email,
password
}

```
Description: logs in to the server. Server will return a JWT token as:


```
{
"message": "logged in successfully",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTAwNDNlODQ4ZGRjMTNlYzQ5NDhhMzMiLCJpYXQiOjE2Mjc0MTI1NjJ9.AWmff1edu6kg6D8Df7GHq1jsPRBdOL3SzzlrA1GFJJM"
}
```

## Private Route

GET `/api/private`

It returns a String: `you are allowed to access this private route` . It requires authentication.

The JWT - `access_token` must be sent on the `Authorization` header as follows: `auth-token: Bearer {jwt}`

# Use Postman

Postman provides a powerful GUI platform to make your API development faster & easier, from building API requests through testing, documentation and sharing

16 changes: 16 additions & 0 deletions API-Authentication-JWT-main/Backend/Validation/authSchema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const Joi = require('@hapi/joi');

const LoginSchema = Joi.object({
email: Joi.string().required().email(),
password: Joi.string().min(6).required()
})

const RegisterSchema = Joi.object({
name: Joi.string().required().min(6),
email: Joi.string().required().email(),
password: Joi.string().min(6).required()
})


module.exports.LoginSchema = LoginSchema;
module.exports.RegisterSchema = RegisterSchema;
38 changes: 38 additions & 0 deletions API-Authentication-JWT-main/Backend/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");


app.use(cors({
origin: "*",
}));


// Import Routes
const authRoute = require("./routes/auth");
const privateRoute = require('./routes/privateRoute');

dotenv.config();

// Connect to DB
mongoose.connect(process.env.DB_QUERY, {
useNewUrlParser: true,
useUnifiedTopology: true
}, () => {
console.log('Successfully connected to Mongo DB');
});


// Middleware
app.use(express.json());
app.use(bodyParser.json());


// Route Middleware
app.use("/api/user", authRoute);
app.use("/api/", privateRoute);

app.listen(3001, () => console.log("Server is Up and Running"));
21 changes: 21 additions & 0 deletions API-Authentication-JWT-main/Backend/model/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
name:{
type: String,
required: true,
min:6,
},
email:{
type: String,
required: true,
min:6,
},
password:{
type: String,
required: true,
min:6
}
});

module.exports = mongoose.model('User', UserSchema);
Loading