add user api
This commit is contained in:
@@ -1,8 +1,61 @@
|
||||
const Router = require('koa-router');
|
||||
const router = new Router();
|
||||
const koaBody = require('koa-body');
|
||||
|
||||
router.get('/', (c, n) => {
|
||||
c.body = "API Root";
|
||||
// import tools
|
||||
const mysql = require('../../libs/mysql_pool.js');
|
||||
const config = require('../../config.json');
|
||||
|
||||
// routes
|
||||
const user_api = require('./user.js');
|
||||
|
||||
// api response handler
|
||||
router.use(async(c, n) => {
|
||||
c.db = await mysql.getConn();
|
||||
c.syncQuery = (query, param = null) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (param != null) {
|
||||
c.db.query(query, param, (err, row) => {
|
||||
if (err) return reject(err);
|
||||
return resolve(row)
|
||||
});
|
||||
} else {
|
||||
c.db.query(query, (err, row) => {
|
||||
if (err) return reject(err);
|
||||
return resolve(row)
|
||||
});
|
||||
}
|
||||
})
|
||||
}
|
||||
await n();
|
||||
if ('db' in c && typeof c.db == 'object' && 'release' in c.db && typeof c.db.release == 'function') c.db.release();
|
||||
switch (typeof c.body) {
|
||||
case 'undefined':
|
||||
c.body = { errorCode: 'ERR9999', status: 0 };
|
||||
case 'string':
|
||||
c.body = { errorCode: c.body, status: 0 };
|
||||
default:
|
||||
c.body = {
|
||||
data: c.body,
|
||||
status: 1
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
// enable bodyParser
|
||||
router.all('*', koaBody({
|
||||
multipart: true,
|
||||
// upload file size 10mb
|
||||
maxFieldSize: 10 * 1024 * 1024
|
||||
}), async(c, n) => { await n(); })
|
||||
|
||||
router
|
||||
.get('/', async(c, n) => {
|
||||
c.body = {
|
||||
msg: 'API Endpoint'
|
||||
};
|
||||
})
|
||||
.use('/user', user_api.routes())
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,30 @@
|
||||
const Router = require('koa-router');
|
||||
const router = new Router();
|
||||
|
||||
// import tools
|
||||
const crypto = require('../../libs/crypto.js');
|
||||
|
||||
router
|
||||
.post('/login', async(c, n) => {
|
||||
let arr = c.request.body;
|
||||
if (!arr.data) return c.body = 'ERR0000';
|
||||
if (!arr.data.account) return c.body = 'ERR0001';
|
||||
if (!arr.data.password) return c.body = 'ERR0002';
|
||||
try {
|
||||
let user = await c.syncQuery('select `uid`,`account`,`password`,`name`,`email` from ??.?? where `account` = ?', ['lora', 'user', arr.data.account])
|
||||
|
||||
if (user.length == 0) return c.body = 'user not exists';
|
||||
|
||||
if (!crypto.comparePass(arr.data.password, user[0].password)) return c.body = 'password not match';
|
||||
|
||||
delete user[0].password;
|
||||
|
||||
c.body = {
|
||||
record: user
|
||||
}
|
||||
} catch (err) {
|
||||
return c.body = 'DB Query Error';
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user