Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Coding Update & ReadMe Update #20

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
46 changes: 45 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,55 @@ You should send this authorization with any request to the protected endpoints
Authorization: Bearer <ACCESS_TOKEN>
```

Usage:

Login:
```
let userToken = null;
axios.post('http://localhost:8000/auth/login',{
"email": "[email protected]",
"password":"nilson"
}).then(function (response) {
console.log (response.data);
userToken = response.data.access_token;
}).catch(function (error) {
console.log(error);
});
```

Read:
```
const config = {
headers: {
Authorization: "Bearer " + userToken
}
};
axios.get('http://localhost:8000/products',config)
.then(function (response) {
console.log (response.data);
}).catch(function (error) {
console.log(error);
});
```

List of APIs:

| API | Usage |
| --- | --- |
| `POST /auth/login` | User Login |
| `POST /auth/register` | Register New User |
| `GET /products` | for getting the products |
| `GET /products/<id>` | for getting a single product by id |
| `POST /products` | for creating a new product |
| `PUT /products/<id>` | for updating a product by id |
| `PATCH /products/<id>` | for partially updating a product by id |
| `DELETE /products/<id>` | for deleting a product by id |


Check out these tutorials:

- [Mocking a REST API Back-End for Your Angular App with JSON-Server and Faker.js](https://www.techiediaries.com/angular-mock-backend)
- [Building a Fake and JWT Protected REST API with json-server](https://www.techiediaries.com/fake-api-jwt-json-server)
- [Angular 9 Tutorial: Build an Example App with Angular CLI, Angular Router, HttpClient & Angular Material](https://www.shabang.dev/angular-tutorial-build-an-example-app-with-angular-cli-router-httpclient-and-angular-material/)



3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
"author": "ME:)",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"json-server": "^0.14.2",
"json-server": "^0.16.3",
"jsonwebtoken": "^8.1.0"
}
}
41 changes: 22 additions & 19 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
const fs = require('fs')
const bodyParser = require('body-parser')
const jsonServer = require('json-server')
const jwt = require('jsonwebtoken')
const jsonFileForUsers = 'users.json';
const jsonFileForData = 'database.json';

const server = jsonServer.create()
const router = jsonServer.router('./database.json')
const userdb = JSON.parse(fs.readFileSync('./users.json', 'UTF-8'))
const SECRET_KEY = 'ectawgwkpagm' // this is the secret key for the authorization
const expiresIn = '1h' // this is the expiration time for jwt token

server.use(bodyParser.urlencoded({extended: true}))
server.use(bodyParser.json())
server.use(jsonServer.defaults());
const fs = require('fs');
const express = require('express');
const jsonServer = require('json-server');
const jwt = require('jsonwebtoken');

const server = jsonServer.create();
const router = jsonServer.router(`./${jsonFileForData}`);
const userdb = JSON.parse(fs.readFileSync(`./${jsonFileForUsers}`, 'UTF-8'));

const SECRET_KEY = '123456789'
server.use(express.urlencoded({extended: true}));
server.use(express.json());
server.use(jsonServer.defaults());

const expiresIn = '1h'

// Create a token from a payload
function createToken(payload){
return jwt.sign(payload, SECRET_KEY, {expiresIn})
return jwt.sign(payload, SECRET_KEY, {expiresIn});
}

// Verify the token
Expand All @@ -43,7 +46,7 @@ server.post('/auth/register', (req, res) => {
return
}

fs.readFile("./users.json", (err, data) => {
fs.readFile(`./${jsonFileForUsers}`, (err, data) => {
if (err) {
const status = 401
const message = err
Expand All @@ -52,14 +55,14 @@ fs.readFile("./users.json", (err, data) => {
};

// Get current users data
var data = JSON.parse(data.toString());
let dataObj = JSON.parse(data.toString());

// Get the id of last user
var last_item_id = data.users[data.users.length-1].id;
let last_item_id = dataObj.users[dataObj.users.length-1].id;

//Add new user
data.users.push({id: last_item_id + 1, email: email, password: password}); //add some data
var writeData = fs.writeFile("./users.json", JSON.stringify(data), (err, result) => { // WRITE
dataObj.users.push({id: last_item_id + 1, email: email, password: password}); //add some data
fs.writeFile(`./${jsonFileForUsers}`, JSON.stringify(dataObj), (err, result) => { // WRITE
if (err) {
const status = 401
const message = err
Expand All @@ -75,7 +78,7 @@ fs.readFile("./users.json", (err, data) => {
res.status(200).json({access_token})
})

// Login to one of the users from ./users.json
// User Login
server.post('/auth/login', (req, res) => {
console.log("login endpoint called; request body:");
console.log(req.body);
Expand Down
50 changes: 49 additions & 1 deletion users.json
Original file line number Diff line number Diff line change
@@ -1 +1,49 @@
{"users":[{"id":1,"email":"[email protected]","password":"bruno"},{"id":2,"email":"[email protected]","password":"techie"},{"id":3,"email":"[email protected]","password":"nilson"},{"id":4,"email":"[email protected]","password":"nilson"},{"id":5,"email":"[email protected]","password":"nilson"},{"id":6,"email":"[email protected]","password":"nilson"},{"id":7,"email":"[email protected]","password":"nilson"},{"id":8,"email":"[email protected]","password":"nilson"},{"id":9,"email":"[email protected]","password":"nilson"}]}
{
"users":[
{
"id":1,
"email":"[email protected]",
"password":"bruno"
},
{
"id":2,
"email":"[email protected]",
"password":"techie"
},
{
"id":3,
"email":"[email protected]",
"password":"nilson"
},
{
"id":4,
"email":"[email protected]",
"password":"nilson"
},
{
"id":5,
"email":"[email protected]",
"password":"nilson"
},
{
"id":6,
"email":"[email protected]",
"password":"nilson"
},
{
"id":7,
"email":"[email protected]",
"password":"nilson"
},
{
"id":8,
"email":"[email protected]",
"password":"nilson"
},
{
"id":9,
"email":"[email protected]",
"password":"nilson"
}
]
}