git clone https://github.com/agelessman/ntask-api
npm install
npm start
import express from "express"
import consign from "consign"
const app = express();
/// 在使用include或者then的时候,是有顺序的,如果传入的参数是一个文件夹
/// 那么他会按照文件夹中文件的顺序进行加载
consign({verbose: false})
.include("libs/config.js")
.then("db.js")
.then("auth.js")
.then("libs/middlewares.js")
.then("routers")
.then("libs/boot.js")
.into(app);
module.exports = app;
app.db app.auth app.libs....
import bcrypt from "bcrypt"
module.exports = (sequelize, DataType) => {
"use strict";
const Users = sequelize.define("Users", {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
password: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
email: {
type: DataType.STRING,
unique: true,
allowNull: false,
validate: {
notEmpty: true
}
}
}, {
hooks: {
beforeCreate: user => {
const salt = bcrypt.genSaltSync();
user.password = bcrypt.hashSync(user.password, salt);
}
}
});
Users.associate = (models) => {
Users.hasMany(models.Tasks);
};
Users.isPassword = (encodedPassword, password) => {
return bcrypt.compareSync(password, encodedPassword);
};
return Users;
};
module.exports = (sequelize, DataType) => {
"use strict";
const Tasks = sequelize.define("Tasks", {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true
},
title: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
done: {
type: DataType.BOOLEAN,
allowNull: false,
defaultValue: false
}
});
Tasks.associate = (models) => {
Tasks.belongsTo(models.Users);
};
return Tasks;
};
Tasks.associate = (models) => {
Tasks.belongsTo(models.Users);
};
Users.associate = (models) => {
Users.hasMany(models.Tasks);
};
Users.isPassword = (encodedPassword, password) => {
return bcrypt.compareSync(password, encodedPassword);
};
import fs from "fs"
import path from "path"
import Sequelize from "sequelize"
let db = null;
module.exports = app => {
"use strict";
if (!db) {
const config = app.libs.config;
const sequelize = new Sequelize(
config.database,
config.username,
config.password,
config.params
);
db = {
sequelize,
Sequelize,
models: {}
};
const dir = path.join(__dirname, "models");
fs.readdirSync(dir).forEach(file => {
const modelDir = path.join(dir, file);
const model = sequelize.import(modelDir);
db.models[model.name] = model;
});
Object.keys(db.models).forEach(key => {
db.models[key].associate(db.models);
});
}
return db;
};
module.exports = app => {
"use strict";
const Tasks = app.db.models.Tasks;
app.route("/tasks")
.all(app.auth.authenticate())
.get((req, res) => {
console.log(`req.body: ${req.body}`);
Tasks.findAll({where: {user_id: req.user.id} })
.then(result => res.json(result))
.catch(error => {
res.status(412).json({msg: error.message});
});
})
.post((req, res) => {
req.body.user_id = req.user.id;
Tasks.create(req.body)
.then(result => res.json(result))
.catch(error => {
res.status(412).json({msg: error.message});
});
});
app.route("/tasks/:id")
.all(app.auth.authenticate())
.get((req, res) => {
Tasks.findOne({where: {
id: req.params.id,
user_id: req.user.id
}})
.then(result => {
if (result) {
res.json(result);
} else {
res.sendStatus(412);
}
})
.catch(error => {
res.status(412).json({msg: error.message});
});
})
.put((req, res) => {
Tasks.update(req.body, {where: {
id: req.params.id,
user_id: req.user.id
}})
.then(result => res.sendStatus(204))
.catch(error => {
res.status(412).json({msg: error.message});
});
})
.delete((req, res) => {
Tasks.destroy({where: {
id: req.params.id,
user_id: req.user.id
}})
.then(result => res.sendStatus(204))
.catch(error => {
res.status(412).json({msg: error.message});
});
});
};
module.exports = app => {
"use strict";
const Users = app.db.models.Users;
app.route("/user")
.all(app.auth.authenticate())
.get((req, res) => {
Users.findById(req.user.id, {
attributes: ["id", "name", "email"]
})
.then(result => res.json(result))
.catch(error => {
res.status(412).json({msg: error.message});
});
})
.delete((req, res) => {
console.log(`delete..........${req.user.id}`);
Users.destroy({where: {id: req.user.id}})
.then(result => {
console.log(`result: ${result}`);
return res.sendStatus(204);
})
.catch(error => {
console.log(`resultfsaddfsf`);
res.status(412).json({msg: error.message});
});
});
app.post("/users", (req, res) => {
Users.create(req.body)
.then(result => res.json(result))
.catch(error => {
res.status(412).json({msg: error.message});
});
});
};
import jwt from "jwt-simple"
module.exports = app => {
"use strict";
const cfg = app.libs.config;
const Users = app.db.models.Users;
app.post("/token", (req, res) => {
const email = req.body.email;
const password = req.body.password;
if (email && password) {
Users.findOne({where: {email: email}})
.then(user => {
if (Users.isPassword(user.password, password)) {
const payload = {id: user.id};
res.json({
token: jwt.encode(payload, cfg.jwtSecret)
});
} else {
res.sendStatus(401);
}
})
.catch(error => res.sendStatus(401));
} else {
res.sendStatus(401);
}
});
};
import passport from "passport";
import {Strategy, ExtractJwt} from "passport-jwt";
module.exports = app => {
const Users = app.db.models.Users;
const cfg = app.libs.config;
const params = {
secretOrKey: cfg.jwtSecret,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
};
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("JWT");
opts.secretOrKey = cfg.jwtSecret;
const strategy = new Strategy(opts, (payload, done) => {
Users.findById(payload.id)
.then(user => {
if (user) {
return done(null, {
id: user.id,
email: user.email
});
}
return done(null, false);
})
.catch(error => done(error, null));
});
passport.use(strategy);
return {
initialize: () => {
return passport.initialize();
},
authenticate: () => {
return passport.authenticate("jwt", cfg.jwtSession);
}
};
};
.all(app.auth.authenticate())
.get((req, res) => {
console.log(`req.body: ${req.body}`);
Tasks.findAll({where: {user_id: req.user.id} })
.then(result => res.json(result))
.catch(error => {
res.status(412).json({msg: error.message});
});
})
import bodyParser from "body-parser"
import express from "express"
import cors from "cors"
import morgan from "morgan"
import logger from "./logger"
import compression from "compression"
import helmet from "helmet"
module.exports = app => {
"use strict";
app.set("port", 3000);
app.set("json spaces", 4);
console.log(`err ${JSON.stringify(app.auth)}`);
app.use(bodyParser.json());
app.use(app.auth.initialize());
app.use(compression());
app.use(helmet());
app.use(morgan("common", {
stream: {
write: (message) => {
logger.info(message);
}
}
}));
app.use(cors({
origin: ["http://localhost:3001"],
methods: ["GET", "POST", "PUT", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"]
}));
app.use((req, res, next) => {
// console.log(`header: ${JSON.stringify(req.headers)}`);
if (req.body && req.body.id) {
delete req.body.id;
}
next();
});
app.use(express.static("public"));
};
import jwt from "jwt-simple"
describe("Routes: Users", () => {
"use strict";
const Users = app.db.models.Users;
const jwtSecret = app.libs.config.jwtSecret;
let token;
beforeEach(done => {
Users
.destroy({where: {}})
.then(() => {
return Users.create({
name: "Bond",
email: "Bond@mc.com",
password: "123456"
});
})
.then(user => {
token = jwt.encode({id: user.id}, jwtSecret);
done();
});
});
describe("GET /user", () => {
describe("status 200", () => {
it("returns an authenticated user", done => {
request.get("/user")
.set("Authorization", `JWT ${token}`)
.expect(200)
.end((err, res) => {
expect(res.body.name).to.eql("Bond");
expect(res.body.email).to.eql("Bond@mc.com");
done(err);
});
});
});
});
describe("DELETE /user", () => {
describe("status 204", () => {
it("deletes an authenticated user", done => {
request.delete("/user")
.set("Authorization", `JWT ${token}`)
.expect(204)
.end((err, res) => {
console.log(`err: ${err}`);
done(err);
});
});
});
});
describe("POST /users", () => {
describe("status 200", () => {
it("creates a new user", done => {
request.post("/users")
.send({
name: "machao",
email: "machao@mc.com",
password: "123456"
})
.expect(200)
.end((err, res) => {
expect(res.body.name).to.eql("machao");
expect(res.body.email).to.eql("machao@mc.com");
done(err);
});
});
});
});
});
import supertest from "supertest" import chai from "chai" import app from "../index" global.app = app; global.request = supertest(app); global.expect = chai.expect;
"test": "NODE_ENV=test mocha test/**/*.js",
/**
* @api {get} /tasks List the user's tasks
* @apiGroup Tasks
* @apiHeader {String} Authorization Token of authenticated user
* @apiHeaderExample {json} Header
* {
* "Authorization": "xyz.abc.123.hgf"
* }
* @apiSuccess {Object[]} tasks Task list
* @apiSuccess {Number} tasks.id Task id
* @apiSuccess {String} tasks.title Task title
* @apiSuccess {Boolean} tasks.done Task is done?
* @apiSuccess {Date} tasks.updated_at Update's date
* @apiSuccess {Date} tasks.created_at Register's date
* @apiSuccess {Number} tasks.user_id The id for the user's
* @apiSuccessExample {json} Success
* HTTP/1.1 200 OK
* [{
* "id": 1,
* "title": "Study",
* "done": false,
* "updated_at": "2016-02-10T15:46:51.778Z",
* "created_at": "2016-02-10T15:46:51.778Z",
* "user_id": 1
* }]
* @apiErrorExample {json} List error
* HTTP/1.1 412 Precondition Failed
*/
/**
* @api {post} /users Register a new user
* @apiGroup User
* @apiParam {String} name User name
* @apiParam {String} email User email
* @apiParam {String} password User password
* @apiParamExample {json} Input
* {
* "name": "James",
* "email": "James@mc.com",
* "password": "123456"
* }
* @apiSuccess {Number} id User id
* @apiSuccess {String} name User name
* @apiSuccess {String} email User email
* @apiSuccess {String} password User encrypted password
* @apiSuccess {Date} update_at Update's date
* @apiSuccess {Date} create_at Rigister's date
* @apiSuccessExample {json} Success
* {
* "id": 1,
* "name": "James",
* "email": "James@mc.com",
* "updated_at": "2016-02-10T15:20:11.700Z",
* "created_at": "2016-02-10T15:29:11.700Z"
* }
* @apiErrorExample {json} Rergister error
* HTTP/1.1 412 Precondition Failed
*/
app.use(cors({
origin: ["http://localhost:3001"],
methods: ["GET", "POST", "PUT", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"]
}));
import fs from "fs"
import winston from "winston"
if (!fs.existsSync("logs")) {
fs.mkdirSync("logs");
}
module.exports = new winston.Logger({
transports: [
new winston.transports.File({
level: "info",
filename: "logs/app.log",
maxsize: 1048576,
maxFiles: 10,
colorize: false
})
]
});
{"level":"info","message":"::1 - - [26/Sep/2017:11:16:23 +0000] \"GET /tasks HTTP/1.1\" 200 616\n","timestamp":"2017-09-26T11:16:23.089Z"}
{"level":"info","message":"::1 - - [26/Sep/2017:11:16:43 +0000] \"OPTIONS /user HTTP/1.1\" 204 0\n","timestamp":"2017-09-26T11:16:43.583Z"}
{"level":"info","message":"Tue Sep 26 2017 19:16:43 GMT+0800 (CST) Executing (default): SELECT `id`, `name`, `password`, `email`, `created_at`, `updated_at` FROM `Users` AS `Users` WHERE `Users`.`id` = 342;","timestamp":"2017-09-26T11:16:43.592Z"}
{"level":"info","message":"Tue Sep 26 2017 19:16:43 GMT+0800 (CST) Executing (default): SELECT `id`, `name`, `email` FROM `Users` AS `Users` WHERE `Users`.`id` = 342;","timestamp":"2017-09-26T11:16:43.596Z"}
{"level":"info","message":"::1 - - [26/Sep/2017:11:16:43 +0000] \"GET /user HTTP/1.1\" 200 73\n","timestamp":"2017-09-26T11:16:43.599Z"}
{"level":"info","message":"::1 - - [26/Sep/2017:11:16:49 +0000] \"OPTIONS /user HTTP/1.1\" 204 0\n","timestamp":"2017-09-26T11:16:49.658Z"}
{"level":"info","message":"Tue Sep 26 2017 19:16:49 GMT+0800 (CST) Executing (default): SELECT `id`, `name`, `password`, `email`, `created_at`, `updated_at` FROM `Users` AS `Users` WHERE `Users`.`id` = 342;","timestamp":"2017-09-26T11:16:49.664Z"}
{"level":"info","message":"Tue Sep 26 2017 19:16:49 GMT+0800 (CST) Executing (default): DELETE FROM `Users` WHERE `id` = 342","timestamp":"2017-09-26T11:16:49.669Z"}
{"level":"info","message":"::1 - - [26/Sep/2017:11:16:49 +0000] \"DELETE /user HTTP/1.1\" 204 -\n","timestamp":"2017-09-26T11:16:49.714Z"}
{"level":"info","message":"::1 - - [26/Sep/2017:11:17:04 +0000] \"OPTIONS /token HTTP/1.1\" 204 0\n","timestamp":"2017-09-26T11:17:04.905Z"}
{"level":"info","message":"Tue Sep 26 2017 19:17:04 GMT+0800 (CST) Executing (default): SELECT `id`, `name`, `password`, `email`, `created_at`, `updated_at` FROM `Users` AS `Users` WHERE `Users`.`email` = 'xiaoxiao@mc.com' LIMIT 1;","timestamp":"2017-09-26T11:17:04.911Z"}
{"level":"info","message":"::1 - - [26/Sep/2017:11:17:04 +0000] \"POST /token HTTP/1.1\" 401 12\n","timestamp":"2017-09-26T11:17:04.916Z"}
import cluster from "cluster"
import os from "os"
const CPUS = os.cpus();
if (cluster.isMaster) {
// Fork
CPUS.forEach(() => cluster.fork());
// Listening connection event
cluster.on("listening", work => {
"use strict";
console.log(`Cluster ${work.process.pid} connected`);
});
// Disconnect
cluster.on("disconnect", work => {
"use strict";
console.log(`Cluster ${work.process.pid} disconnected`);
});
// Exit
cluster.on("exit", worker => {
"use strict";
console.log(`Cluster ${worker.process.pid} is dead`);
cluster.fork();
});
} else {
require("./index");
}
app.use(compression());
import https from "https"
import fs from "fs"
module.exports = app => {
"use strict";
if (process.env.NODE_ENV !== "test") {
const credentials = {
key: fs.readFileSync("44885970_www.localhost.com.key", "utf8"),
cert: fs.readFileSync("44885970_www.localhost.com.cert", "utf8")
};
app.db.sequelize.sync().done(() => {
https.createServer(credentials, app)
.listen(app.get("port"), () => {
console.log(`NTask API - Port ${app.get("port")}`);
});
});
}
};
app.use(helmet());
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有