Skip to content

Commit c5b0100

Browse files
committed
Diretorio build enviado para testes
1 parent ff795d8 commit c5b0100

23 files changed

+626
-1
lines changed

.gitignore

-1
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,3 @@ coverage
1919
/server/config/env/development.env.js
2020
/server/config/env/test.env.js
2121
.vscode/
22-
build

build/api/api.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"use strict";
2+
var express = require("express");
3+
var logger = require("morgan");
4+
var auth_1 = require("../auth");
5+
var routes_1 = require("./routes/routes");
6+
var bodyParser = require('body-parser');
7+
var Api = (function () {
8+
function Api() {
9+
this.express = express();
10+
this.auth = auth_1.default();
11+
this.middleware();
12+
this.router(this.express, this.auth);
13+
}
14+
Api.prototype.middleware = function () {
15+
this.express.use(logger('dev'));
16+
this.express.use(bodyParser.urlencoded({ extended: true }));
17+
this.express.use(bodyParser.json());
18+
this.express.use(this.auth.initialize());
19+
};
20+
Api.prototype.router = function (app, auth) {
21+
new routes_1.default(app, auth);
22+
};
23+
return Api;
24+
}());
25+
Object.defineProperty(exports, "__esModule", { value: true });
26+
exports.default = new Api().express;

build/api/errorHandlerApi.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
"use strict";
2+
var HTTPStatus = require("http-status");
3+
function errorHandlerApi(err, req, res, next) {
4+
console.error('API error handler was called: ', err);
5+
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).json({
6+
errorCode: 'ERR-001',
7+
message: 'Internal Server Error'
8+
});
9+
}
10+
exports.errorHandlerApi = errorHandlerApi;

build/api/responses/authSuccess.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"use strict";
2+
var jwt = require("jwt-simple");
3+
var HTTPStatus = require("http-status");
4+
var config = require('../../config/env/config')();
5+
var bcrypt = require('bcrypt');
6+
function authSuccess(res, creadentials, data) {
7+
var isMatch = bcrypt.compareSync(creadentials.password, data.password);
8+
if (isMatch) {
9+
var payload = { id: data.id };
10+
res.json({
11+
token: jwt.encode(payload, config.secret)
12+
});
13+
}
14+
else {
15+
res.sendStatus(HTTPStatus.UNAUTHORIZED);
16+
}
17+
}
18+
exports.authSuccess = authSuccess;
19+
function authFail(req, res) {
20+
res.sendStatus(HTTPStatus.UNAUTHORIZED);
21+
}
22+
exports.authFail = authFail;

build/api/responses/errorHandler.js

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
"use strict";
2+
var HTTPStatus = require("http-status");
3+
function onError(res, message, err) {
4+
console.log('Error: ', err);
5+
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).send();
6+
}
7+
exports.onError = onError;

build/api/responses/successHandler.js

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
"use strict";
2+
var HTTPStatus = require("http-status");
3+
function onSuccess(res, data) {
4+
res.status(HTTPStatus.OK).json({ payload: data });
5+
}
6+
exports.onSuccess = onSuccess;

build/api/routes/routes.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"use strict";
2+
var routes_1 = require("../../modules/User/routes");
3+
var auth_1 = require("../../modules/auth/auth");
4+
var Routes = (function () {
5+
function Routes(app, auth) {
6+
this.router = new routes_1.default();
7+
this.tokenRoute = new auth_1.default();
8+
this.auth = auth;
9+
this.getRoutes(app);
10+
}
11+
Routes.prototype.getRoutes = function (app) {
12+
app.route('/api/users/all').all(this.auth.authenticate()).get(this.router.index);
13+
app.route('/api/users/create').all(this.auth.authenticate()).post(this.router.create);
14+
app.route('/api/users/:id').all(this.auth.authenticate()).get(this.router.findOne);
15+
app.route('/api/users/:id/update').all(this.auth.authenticate()).put(this.router.update);
16+
app.route('/api/users/:id/destroy').all(this.auth.authenticate()).delete(this.router.destroy);
17+
app.route('/token').post(this.tokenRoute.auth);
18+
};
19+
return Routes;
20+
}());
21+
Object.defineProperty(exports, "__esModule", { value: true });
22+
exports.default = Routes;

build/auth.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"use strict";
2+
var passport = require("passport");
3+
var service_1 = require("./modules/User/service");
4+
var passport_jwt_1 = require("passport-jwt");
5+
var config = require('./config/env/config')();
6+
function AuthConfig() {
7+
var UserService = new service_1.User();
8+
var opts = {
9+
secretOrKey: config.secret,
10+
jwtFromRequest: passport_jwt_1.ExtractJwt.fromAuthHeader()
11+
};
12+
passport.use(new passport_jwt_1.Strategy(opts, function (jwtPayload, done) {
13+
UserService.getById(jwtPayload.id)
14+
.then(function (user) {
15+
if (user) {
16+
return done(null, {
17+
id: user.id,
18+
email: user.email
19+
});
20+
}
21+
return done(null, false);
22+
})
23+
.catch(function (error) { return done(error, null); });
24+
}));
25+
return {
26+
initialize: function () { return passport.initialize(); },
27+
authenticate: function () { return passport.authenticate('jwt', { session: false }); },
28+
};
29+
}
30+
Object.defineProperty(exports, "__esModule", { value: true });
31+
exports.default = AuthConfig;

build/config/dbErrorHandler.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
"use strict";
2+
var HTTPStatus = require("http-status");
3+
var hri = require('human-readable-ids').hri;
4+
function dbErrorHandler(res, err) {
5+
var id = hri.random();
6+
console.error("Database error ocurred: ", id, err);
7+
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).json({
8+
code: 'ERR-002',
9+
message: "Creation of user failed, error code " + id
10+
});
11+
}
12+
exports.dbErrorHandler = dbErrorHandler;

build/config/env/config.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module.exports = function () { return require("../env/" + process.env.NODE_ENV + ".env.js"); };

build/config/env/development.env.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
module.exports = {
2+
env: "development",
3+
db: "api",
4+
dialect: "postgres",
5+
username: "postgres",
6+
password: "pgroot",
7+
host: "localhost",
8+
server_port: 3000,
9+
pg_port: 5432,
10+
db_url: "postgres://postgres:pgroot@localhost:5432/api",
11+
secret: "secret",
12+
};

build/config/env/test.env.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
module.exports = {
2+
env: "test",
3+
db: "api",
4+
dialect: "postgres",
5+
username: "postgres",
6+
password: "pgroot",
7+
host: "localhost",
8+
server_port: 3000,
9+
pg_port: 5432,
10+
db_url: "postgres://postgres:pgroot@localhost:5432/api",
11+
secret: "secret",
12+
};

build/config/tests/config/helpers.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
'use strict';
2+
var Chai = require("chai");
3+
var supertest = require('supertest');
4+
var td = require("testdouble");
5+
var api_1 = require("../../../api/api");
6+
var app = api_1.default;
7+
exports.app = app;
8+
var request = supertest;
9+
exports.request = request;
10+
var expect = Chai.expect;
11+
exports.expect = expect;
12+
var testDouble = td;
13+
exports.testDouble = testDouble;

build/models/index.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
var fs = require('fs');
2+
var path = require('path');
3+
var Sequelize = require('sequelize');
4+
var basename = path.basename(module.filename);
5+
var config = require('../config/env/config')();
6+
var env = config.env || 'development';
7+
var db = {};
8+
var sequelize;
9+
if (config.db_url) {
10+
sequelize = new Sequelize(config.db_url);
11+
}
12+
else {
13+
sequelize = new Sequelize(config.db, config.username, config.password);
14+
}
15+
fs
16+
.readdirSync(__dirname)
17+
.filter(function (file) {
18+
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
19+
})
20+
.forEach(function (file) {
21+
var model = sequelize['import'](path.join(__dirname, file));
22+
db[model.name] = model;
23+
});
24+
Object.keys(db).forEach(function (modelName) {
25+
if (db[modelName].associate) {
26+
db[modelName].associate(db);
27+
}
28+
});
29+
db.sequelize = sequelize;
30+
db.Sequelize = Sequelize;
31+
module.exports = db;

build/models/user.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"use strict";
2+
var bcrypt = require("bcrypt");
3+
function default_1(sequelize, DataTypes) {
4+
var User = sequelize.define('User', {
5+
id: {
6+
type: DataTypes.INTEGER,
7+
primaryKey: true,
8+
autoIncrement: true
9+
},
10+
name: {
11+
type: DataTypes.STRING,
12+
allowNull: false,
13+
validate: {
14+
notEmpty: true
15+
}
16+
},
17+
email: {
18+
type: DataTypes.STRING,
19+
allowNull: false,
20+
validate: {
21+
notEmpty: true,
22+
}
23+
},
24+
password: {
25+
type: DataTypes.STRING,
26+
allowNull: false,
27+
validate: {
28+
notEmpty: true,
29+
}
30+
}
31+
}, {
32+
classMethods: {
33+
validatePassword: function (encryptedPassword, password) { return bcrypt.compareSync(password, encryptedPassword); }
34+
}
35+
});
36+
User.beforeCreate(function (user) { return hashPass(user); });
37+
User.beforeUpdate(function (user) { return hashPass(user); });
38+
function hashPass(user) {
39+
var salt = bcrypt.genSaltSync(10);
40+
user.set('password', bcrypt.hashSync(user.password, salt));
41+
console.log("Password " + user.password);
42+
}
43+
return User;
44+
}
45+
Object.defineProperty(exports, "__esModule", { value: true });
46+
exports.default = default_1;
47+
;

build/modules/User/controller.js

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"use strict";
2+
var _ = require("lodash");
3+
var errorHandler_1 = require("../../api/responses/errorHandler");
4+
var successHandler_1 = require("../../api/responses/successHandler");
5+
var dbErrorHandler_1 = require("../../config/dbErrorHandler");
6+
var service_1 = require("./service");
7+
var UserController = (function () {
8+
function UserController() {
9+
this.UserService = new service_1.User();
10+
}
11+
UserController.prototype.getAll = function (req, res) {
12+
this.UserService.getAll()
13+
.then(_.partial(successHandler_1.onSuccess, res))
14+
.catch(_.partial(errorHandler_1.onError, res, 'Find all users failed'));
15+
};
16+
UserController.prototype.createUser = function (req, res) {
17+
this.UserService.create(req.body)
18+
.then(_.partial(successHandler_1.onSuccess, res))
19+
.catch(_.partial(dbErrorHandler_1.dbErrorHandler, res))
20+
.catch(_.partial(errorHandler_1.onError, res, "Could not create user"));
21+
};
22+
UserController.prototype.getById = function (req, res) {
23+
var userId = parseInt(req.params.id);
24+
this.UserService.getById(userId)
25+
.then(_.partial(successHandler_1.onSuccess, res))
26+
.catch(_.partial(errorHandler_1.onError, res, 'Not found'));
27+
};
28+
UserController.prototype.updateUser = function (req, res) {
29+
var userId = parseInt(req.params.id);
30+
var props = req.body;
31+
this.UserService.update(userId, props)
32+
.then(_.partial(successHandler_1.onSuccess, res))
33+
.catch(_.partial(errorHandler_1.onError, res, 'Update User failed'));
34+
};
35+
UserController.prototype.deleteUser = function (req, res) {
36+
var userId = req.params.id;
37+
this.UserService.delete(userId)
38+
.then(_.partial(successHandler_1.onSuccess, res))
39+
.catch(_.partial(errorHandler_1.onError, res, 'An error ocurred to delete an User'));
40+
};
41+
return UserController;
42+
}());
43+
Object.defineProperty(exports, "__esModule", { value: true });
44+
exports.default = UserController;

0 commit comments

Comments
 (0)