javascript API CRUD AUTH JWT
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript API CRUD AUTH JWT相关的知识,希望对你有一定的参考价值。
var express = require('express');
var _ = require('lodash')
var format = require('pg-format')
var router = express.Router();
var config = require('config');
var dbConfig = config.get('dbConfig');
const { Pool, Client } = require('pg')
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
const path = require('path');
const conString = 'postgres://postgres@localhost:5432/vidillion';
const pool = new Pool(dbConfig)
router.post("/login", function (req, res, next) {
var username = req.body.username;
var password = req.body.password;
var hash = crypto.createHash('sha256').update(password).digest('base64');
console.log("HASH---------", hash)
var selectQuery = format('SELECT * FROM USERS WHERE username=%L', username)
pool.query(selectQuery, (err, resp) => {
if (err) {
console.log('----ERROR IN DB----', err)
}
else {
console.log('----RESP IN DB----', resp)
var response = resp.rows.length != 0 && resp.rows || []
if (response.length != 0) {
if (hash == response[0].password) {
const payload = {
admin: response[0].role
};
var token = jwt.sign(payload, config.get('secretKey'), {
expiresIn: 60 * 60 * 24
});
res.json({ message: 'Authentication Success', userrole: response[0].role, token, success: true, })
}
else {
res.json({ message: 'Authentication failed incorrect password', success: false })
}
}
else {
res.json({ message: 'Invalid user', success: false })
}
}
// pool.end()
})
});
router.get("/", function (req, res, next) {
var selectQuery = "SELECT name,username,role,email FROM USERS WHERE system!='vidillion'"
const token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.get('secretKey'), function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
pool.query(selectQuery, (err, resp) => {
if (err) {
console.log('----ERROR IN DB----', err)
res.json({ message: 'Fetch Error', success: false })
}
else {
console.log('----RESP IN DB----', resp)
var response = resp.rows.length != 0 && resp.rows || []
res.json({ message: 'Fetch Success', success: true, users: response })
}
})
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
router.post("/create", function (req, res, next) {
console.log('----REQ IN DB----', req.body)
var username = req.body.username
var name = req.body.name
var password = req.body.password
var role = req.body.role
var email = req.body.email
var system = req.body.system
if (username && name && password && role && email) {
const token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.get('secretKey'), function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
var hashedPassword = crypto.createHash('sha256').update(password).digest('base64');
var selectQuery = format('INSERT INTO USERS (name,username,password,role,email,system) VALUES (%L,%L,%L,%L,%L,%L)', name, username, hashedPassword, role, email, system)
pool.query(selectQuery, (err, resp) => {
if (err) {
console.log('----ERROR IN DB----', err)
res.json({ message: 'DB Error', success: false, "Error": err.detail })
}
else {
console.log('----RESP IN DB----', resp)
res.json({ message: 'Add New User Success', success: true })
}
})
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
else {
res.json({ message: 'Field Missing', success: false })
}
});
router.post("/update", function (req, res, next) {
console.log('----REQ IN DB----', req.body)
var username = req.body.username
var name = req.body.name
var password = req.body.password
var role = req.body.role
var email = req.body.email
var system = req.body.system
if (username && role && name && email && system) {
var selectQuery = format('UPDATE USERS SET name=%L,role=%L,email=%L WHERE username=%L AND system=%L', name, role, email, username, system)
const token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.get('secretKey'), function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
pool.query(selectQuery, (error, respo) => {
if (error) {
console.log('----ERROR IN DB----', error)
res.json({ message: 'DB Error', success: false, "Error": error.detail })
}
else {
console.log('----RESP IN DB----', respo)
if (respo.rowCount == 0) {
res.json({ message: 'No User Found', success: false })
}
else {
res.json({ message: 'Update User Success', success: true })
}
}
// pool.end()
})
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
else {
res.json({ Message: 'Field Missing', success: false })
}
});
router.post("/delete", function (req, res, next) {
console.log('----REQ IN DB----', req.body)
var username = req.body.username
var system = req.body.system
if (username && system) {
var selectQuery = format('DELETE FROM USERS WHERE username=%L AND system=%L', username, system)
const token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.get('secretKey'), function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
pool.query(selectQuery, (err, resp) => {
if (err) {
console.log('----ERROR IN DB----', err)
res.json({ message: 'DB Error', success: false, "Error": err.detail })
}
else {
console.log('----RESP IN DB----', resp)
var response = resp.rowCount && resp.rowCount || 0
if (response == 0) {
res.json({ message: 'No USER Found', success: false })
}
else {
res.json({ message: 'Delete USER Success', success: true })
}
}
// pool.end()
})
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
else {
res.json({ Message: 'Field Missing', success: false })
}
});
router.post("/getUser", function (req, res, next) {
console.log('----REQ IN DB----', req.body)
var username = req.body.username
var system = req.body.system
if (username && system) {
var selectQuery = format('SELECT name,username,role,email FROM USERS WHERE username=%L AND system=%L', username, system)
const token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.get('secretKey'), function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
pool.query(selectQuery, (err, resp) => {
if (err) {
console.log('----ERROR IN DB----', err)
res.json({ message: 'DB Error', success: false, "Error": err.detail })
}
else {
console.log('----RESP IN DB----', resp)
var response = resp.rows.length != 0 && resp.rows || []
if (resp.rowCount == 0) {
res.json({ message: 'No USER Found', success: false, Roles: response })
}
else {
res.json({ message: 'Fetch Success', success: true, Roles: response })
}
}
// pool.end()
})
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
else {
res.json({ Message: 'Field Missing', success: false })
}
});
module.exports = router;
以上是关于javascript API CRUD AUTH JWT的主要内容,如果未能解决你的问题,请参考以下文章
javascript Graphql-yoga auth api的服务器初始化
Chrome 上的 Google Auth API Javascript idpiframe 初始化错误
如何在 Django CRUD 中自定义 auth.User 管理页面?