Skip to content

Commit

Permalink
authenticação com passport, ajustes no eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
joaopaulogse committed Dec 30, 2017
1 parent 3d5cd3f commit 3264f30
Show file tree
Hide file tree
Showing 11 changed files with 128 additions and 23 deletions.
14 changes: 14 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/src/server.js"
}
]
}
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"test-integration-jest": "cross-env NODE_ENV=test jest --forceExit",
"test-coverage": "cross-env NODE_ENV=test istanbul cover jest",
"test-integration:mocha": "cross-env NODE_ENV=test mocha --opts ./src/api/tests/integration/mocha.opts ./src/api/tests/integration/**/*.js",
"docker:dev":"docker-compose -f docker-compose.dev.yml up"
"docker:dev": "docker-compose -f docker-compose.dev.yml up"
},
"engines": {
"node": "^8.2.1"
Expand All @@ -25,6 +25,7 @@
},
"dependencies": {
"apidoc": "^0.17.6",
"bcrypt": "^1.0.3",
"bcrypt-nodejs": "^0.0.3",
"body-parser": "^1.17.2",
"compression": "^1.7.0",
Expand All @@ -37,13 +38,14 @@
"express-session": "^1.15.5",
"express-validation": "^1.0.2",
"global": "^4.3.2",
"helmet": "^3.8.2",
"graphql": "^0.11.7",
"helmet": "^3.8.2",
"http-status": "^1.0.1",
"joi": "^10.6.0",
"mongoose": "^4.11.12",
"morgan": "^1.8.2",
"passport": "^0.4.0",
"passport-local": "^1.0.0",
"pg": "^7.0.2",
"pg-hstore": "^2.3.2",
"pm2": "^2.7.1",
Expand Down
4 changes: 2 additions & 2 deletions src/api/controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const HttpStatus = require("http-status");
// mongodb
const Users = require("../models/users.model");

exports.create = function(req, res) {
exports.create = (req, res) => {
const { username, password, email, tipo } = req.body;
Users.create({ username, password, email, tipo })
.then((users) => {
Expand All @@ -25,7 +25,7 @@ exports.loadUser = (req, res) => {
Users.findById(req.params.id)
.then(user => res.status(HttpStatus.OK).send(user))
.catch((err) => {
res.status(HttpStatus.NOT_FOUND).send("não achado!");
res.status(HttpStatus.NOT_FOUND).json({error:"não achado!"});
console.error(err.message);
});
};
Expand Down
22 changes: 21 additions & 1 deletion src/api/models/users.model.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
const mongoose = require("../../config/mongodb");
const bcrypt = require("bcrypt-nodejs");

const SALT_WORK_FACTOR = 10;

const Users = mongoose.Schema({
username: {
type: String,
required: true,
required: [true, "Username is required"],
unique: [true, "Username ja existe"],
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
Expand All @@ -24,5 +29,20 @@ const Users = mongoose.Schema({
required: true,
},
});
Users.pre("save", function (next) {
if (this.password) {
this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(SALT_WORK_FACTOR, null));
}
next();
});
// methods ======================
// generating a hash
Users.methods.generateHash = password =>
bcrypt.hashSync(password, bcrypt.genSaltSync(SALT_WORK_FACTOR, null));

// checking if password is valid
Users.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};

module.exports = mongoose.model("users", Users);
6 changes: 4 additions & 2 deletions src/api/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ const { registrar } = require("../validations/user.validation");
const routerUser = require("./user.routes");
const graphqlHTTP = require("express-graphql");
const { schema } = require("../models/UserSchema");
const login = require("./login.routes");

const router = express.Router();

router.use("/users", routerUser);
router.use("/graphql", graphqlHTTP({
schema : schema ,
graphiql : true,
schema,
graphiql: true,
}));
router.post("/cadastro", validate(registrar), create);
router.use("/auth", login);

module.exports = router;
14 changes: 14 additions & 0 deletions src/api/routes/login.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const express = require("express");
const passport = require("passport");

const router = express.Router();

router
.post("/login", passport.authenticate("local",
{ successRedirect: "/users",
failureRedirect: "/",
failureFlash: false,
},
));

module.exports = router;
1 change: 1 addition & 0 deletions src/api/routes/user.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const express = require("express");
const { listarUsuarios, loadUser, get, deleteUser, update } = require("../controllers/user.controller");
const validate = require("express-validation");
const { registrar } = require("../validations/user.validation");

const router = express.Router();


Expand Down
19 changes: 11 additions & 8 deletions src/config/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,34 @@ const bodyParser = require("body-parser");
const helmet = require("helmet");
const routes = require("../api/routes");
const logger = require("morgan");
const session = require("express-session")
const session = require("express-session");
const cors = require("./cors");
const { secret } = require("./vars")
const { secret } = require("./vars");
const { error404, error400 } = require("../api/middleware/error");
const passport = require("passport");

const app = express();

/** Cors */
app.use(cors);

app.use(helmet());
app.use(logger("[:date] - :method :url :status :response-time ms - :res[content-length]"));
app.use(logger("[:date] - :method :url :status :response-time ms - :res[content-length]", { immediate: true }));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(session({
secret:secret,
resave:false,
saveUninitialized:true
}))
secret,
resave: false,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
require("./passport");

app.use(routes);


/** Middlewares de error */
app.use(error404);
app.use(error400);
Expand Down
36 changes: 36 additions & 0 deletions src/config/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const passport = require("passport");
const LocalStratagy = require("passport-local").Strategy;
const User = require("../api/models/users.model");

passport.serializeUser((user, done) => {
done(null, user.id);
});

passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});

passport.use(new LocalStratagy({
usernameField: "username",
passwordField: "password",
},
(username, password, done) => {
console.log(password);
User.findOne({ username }, (err, user) => {
if (err) return done(err);

if (!user) {
return done(null, false, { message: "Usuário não existe" });
}

if (!user.validPassword(password)) {
return done(null, false, { message: "Senha Incorreta" });
}
return done(null, user);
});
},
));

module.export = passport;
12 changes: 6 additions & 6 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
*/

// server https
const server_https = https.createServer({
key:readFileSync("./localhost-privkey.pem"),
cert:readFileSync("./localhost-cert.pem")
},app).listen(port_https, "0.0.0.0",() => {
console.log(`Server https up, ${server_https.address().address}:${server_https.address().port}
Family:${server_https.address().family}
const serverHttps = https.createServer({
key: readFileSync("./localhost-privkey.pem"),
cert: readFileSync("./localhost-cert.pem"),
}, app).listen(port_https, "0.0.0.0", () => {
console.log(`Server https up, ${serverHttps.address().address}:${serverHttps.address().port}
Family:${serverHttps.address().family}
Ambiente: ${env}`);

// server http
Expand Down
17 changes: 15 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,13 @@ bcrypt-pbkdf@^1.0.0:
dependencies:
tweetnacl "^0.14.3"

bcrypt@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/bcrypt/-/bcrypt-1.0.3.tgz#b02ddc6c0b52ea16b8d3cf375d5a32e780dab548"
dependencies:
nan "2.6.2"
node-pre-gyp "0.6.36"

binary-extensions@^1.0.0:
version "1.9.0"
resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.9.0.tgz#66506c16ce6f4d6928a5b3cd6a33ca41e941e37b"
Expand Down Expand Up @@ -3515,7 +3522,7 @@ [email protected], mute-stream@~0.0.4:
version "0.0.7"
resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.7.tgz#3075ce93bc21b8fab43e1bc4da7e8115ed1e7bab"

nan@^2.3.0:
nan@2.6.2, nan@^2.3.0:
version "2.6.2"
resolved "https://registry.yarnpkg.com/nan/-/nan-2.6.2.tgz#e4ff34e6c95fdfb5aecc08de6596f43605a7db45"

Expand Down Expand Up @@ -3561,7 +3568,7 @@ node-notifier@^5.0.2:
shellwords "^0.1.0"
which "^1.2.12"

node-pre-gyp@^0.6.36:
node-pre-gyp@0.6.36, node-pre-gyp@^0.6.36:
version "0.6.36"
resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.6.36.tgz#db604112cb74e0d477554e9b505b17abddfab786"
dependencies:
Expand Down Expand Up @@ -3813,6 +3820,12 @@ parseurl@~1.3.2:
version "1.3.2"
resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.2.tgz#fc289d4ed8993119460c156253262cdc8de65bf3"

passport-local@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/passport-local/-/passport-local-1.0.0.tgz#1fe63268c92e75606626437e3b906662c15ba6ee"
dependencies:
passport-strategy "1.x.x"

[email protected]:
version "1.0.0"
resolved "https://registry.yarnpkg.com/passport-strategy/-/passport-strategy-1.0.0.tgz#b5539aa8fc225a3d1ad179476ddf236b440f52e4"
Expand Down

0 comments on commit 3264f30

Please sign in to comment.