diff --git a/package.json b/package.json index 54eb00db65ad337df7a2eb1ad0f1a1c462e1db7f..94ccf471c1bcb396cd23b3135c455055f6ae4212 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "babel-core": "^6.26.3", "babel-preset-es2015": "^6.24.1", "babel-register": "^6.26.0", + "bcrypt": "^5.1.0", "bcrypt-nodejs": "0.0.3", "body-parser": "^1.18.3", "chai": "^3.5.0", diff --git a/src/libs/middlewares/oauth2.js b/src/libs/middlewares/oauth2.js index 7babf1a8feefa1c8d8a8d7c05d5545ca4ce857ef..37ac3509a0d1d3ddc64a4f081408460b81e06cb0 100644 --- a/src/libs/middlewares/oauth2.js +++ b/src/libs/middlewares/oauth2.js @@ -23,88 +23,65 @@ let errFn = (cb, err) => { } // Destroys any old tokens and generates a new access and refresh token -let generateTokens = (data, done) => { +let generateTokens = (userId, clientId, done) => { // curries in `done` callback so we don't need to pass it - let errorHandler = errFn.bind(undefined, done); - let refreshToken; let refreshTokenValue; let token; let tokenValue; - RefreshToken.remove(data, errorHandler); - AccessToken.remove(data, errorHandler); + RefreshToken.destroy({where:{"user_id": userId, "client_id": clientId}}); + AccessToken.destroy({where:{"user_id": userId, "client_id": clientId}}); tokenValue = crypto.randomBytes(32).toString('hex'); refreshTokenValue = crypto.randomBytes(32).toString('hex'); - data.token = tokenValue; - token = new AccessToken(data); - - data.token = refreshTokenValue; - refreshToken = new RefreshToken(data); + AccessToken.create({ + user_id:userId, + client_id:clientId, + token:tokenValue + }) - refreshToken.save(errorHandler); + let refreshed_token = refreshTokenValue; - token.save((err) => { - if (err) { - log.error(err); - return done(err); - } - done(null, tokenValue, refreshTokenValue, { - 'expires_in': config.security.tokenLife - }); + RefreshToken.create({ + user_id:userId, + client_id:clientId, + token:refreshed_token }) }; -// Exchange username & password for access token. -aserver.exchange(oauth2orize.exchange.password((client, username, password, scope, done) => { - console.log("Exchange"); - User.findOne({where:{ email: username }}, (err, user) => { - if (err) { - return done(err); - } - - if (!user || !user.checkPassword(password)) { - return done(null, false); - } - var model = { - userId: user._id, - clientId: client._id - }; - log.info(`Gerando token para usuário ${user.name}`); - generateTokens(model, done); - }) +aserver.exchange(oauth2orize.exchange.password(function(client, username, password, scope, done) { + User.findOne({ + where: {email:username} + }).then(function(user) { + if(user == null){ + return done(null, false); + } + if(user.dataValues.origin != client.client_secret){ + console.log("Erro de client_secret"); + return done(null, false); + } + log.info(`Gerando token para usuário ${user.name}`); + generateTokens(user.dataValues.id, client.id, done); + }).catch(function(error) { + return done(error); + }); + })); -})); // Exchange refreshToken for access token. aserver.exchange(oauth2orize.exchange.refreshToken((client, refreshToken, scope, done) =>{ console.log("Refresha Token"); - RefreshToken.findOne({ token: refreshToken, client_id: client._id }, (err, token) => { - if (err) { - return done(err); - } - + RefreshToken.findOne({where: {token: refreshToken, client_id: client.id }}).then(function(token){ if (!token) { return done(null, false); } - - User.findByPk(token.userId , (err, user) => { - if (err) { - log.error(err); - return done(err); - } + User.findByPk(token.user_id).then(function(user){ if (!user) { return done(null, false); } - - var model = { - userId: user._id, - clientId: client._id - }; - - generateTokens(model, done); + generateTokens(user.id, client.id, done); }) }) })) @@ -116,12 +93,15 @@ aserver.exchange(oauth2orize.exchange.refreshToken((client, refreshToken, scope, // exchange middleware will be invoked to handle the request. Clients must // authenticate when making requests to this endpoint. + +// ,function(err, user) { +// if (err) { console.log("Erro de autenticação"); } +// if (!user) { console.log("Erro de usuario ausente");} +// } + exports.token = [ // ()=>{console.log("C3sl")}, - passport.authenticate(['oauth2-client-password'], { session: false },function(err, user) { - if (err) { console.log("Erro de autenticação"); } - if (!user) { console.log("Erro de usuario ausente");} - }), + passport.authenticate(['oauth2-client-password'], { session: false }), aserver.token(), aserver.errorHandler() ]; diff --git a/src/libs/middlewares/passport.js b/src/libs/middlewares/passport.js index 55e12e3c766015add87690953e30504e484cd852..28e07e326acc06767856da2204146322580e0626 100644 --- a/src/libs/middlewares/passport.js +++ b/src/libs/middlewares/passport.js @@ -10,36 +10,28 @@ const Client = require(`${libs}/models/client`); const AccessToken = require(`${libs}/models/accessToken`); -passport.use(new ClientPasswordStrategy( (clientId, clientSecret, done) => { - console.log("Entrei no ClientPasswordStrategy"); - Client.findOne(clientId, (err, client) => { - if (err) { - console.log("Erro de requisicao"); - return done(err); - } - - if (!client) { - console.log("Erro de cliente"); - return done(null, false); - } - - if (client.clientSecret !== clientSecret) { - console.log("Erro de geracao Chave secreta"); - return done(null, false); - } - console.log("Tudo certo nesse use"); - return done(null, client); - }) - })); +passport.use(new ClientPasswordStrategy( + function(client_id, client_secret, done) { + Client.findOne({where: {id: client_id} + }).then(function(client) { + if(!client){ + console.log("Erro de cliente"); + return done(null, false); + } + if (client.client_secret !== client_secret){ + console.log("Erro de geracao Chave Secreta"); + return done(null, false); + } + return done(null, client); + }).catch(function(error) { + return done(error); + }); + } + )); passport.use(new BearerStrategy( (accessToken, done) => { console.log("Entrei no BearerStrategy"); - AccessToken.findOne({ token: accessToken }, (err, token) => { - if (err) { - console.log("ERRO AcessToken"); - return done(err); - } - + AccessToken.findOne({where:{token: accessToken}}, (token) => { if (!token) { console.log("ERRO Token"); return done(null, false); @@ -56,17 +48,11 @@ passport.use(new BearerStrategy( (accessToken, done) => { return done(null, false, { msg: 'Token expired' }); } - User.findByPk(token.userId, function(err, usuario) { - if (err) { - console.log("ERRO PK"); - return done(err); - } - + User.findByPk(token.userId, function(usuario) { if (!usuario) { console.log("ERRO NAO USUARIO"); return done(null, false, { msg: 'Unknown user' }); } - var info = { scope: '*' }; done(null, usuario, info); }) diff --git a/src/libs/models/accessToken.js b/src/libs/models/accessToken.js index 7eedfefa7ec6420a53a40efa14279da1e2b7ee56..68f6802a577cca4d7828b0e38e60bc094698ce80 100644 --- a/src/libs/models/accessToken.js +++ b/src/libs/models/accessToken.js @@ -25,7 +25,7 @@ var AccessToken = db.define("AccessToken",{ {timestamps: false} ); -AccessToken.hasOne(User); -AccessToken.hasOne(Client); +AccessToken.hasOne(User, { foreignKey: 'id' }); +AccessToken.hasOne(Client, { foreignKey: 'id' }); module.exports = AccessToken; diff --git a/src/libs/models/client.js b/src/libs/models/client.js index 10d7db8783e50b450bef954c159b8f003906974f..b4eabcbca46ed440b8655cc77b6b5b147e35c54c 100644 --- a/src/libs/models/client.js +++ b/src/libs/models/client.js @@ -1,7 +1,6 @@ const Sequelize = require("sequelize"); const db = require('../db/postgres.js'); - var Client = db.define("client",{ id:{ type: Sequelize.STRING, diff --git a/src/libs/models/refreshToken.js b/src/libs/models/refreshToken.js index 0d59d8ad822581603b624df0328663c65e02135d..01b33ac82cf4177f7b1135b80858f003d508f9db 100644 --- a/src/libs/models/refreshToken.js +++ b/src/libs/models/refreshToken.js @@ -25,8 +25,8 @@ var RefreshToken = db.define("RefreshToken",{ {timestamps: false} ); -RefreshToken.hasOne(User); -RefreshToken.hasOne(Client); +RefreshToken.hasOne(User, { foreignKey: 'id' }); +RefreshToken.hasOne(Client, { foreignKey: 'id' }); module.exports = RefreshToken; diff --git a/src/libs/routes_v1/test.js b/src/libs/routes_v1/test.js index 2e529eaa6304fe516d4cae0e4cb52d4ffe8f81e2..9e8482dcf3bbdcb52faf269d9a7e7f57d37069cf 100644 --- a/src/libs/routes_v1/test.js +++ b/src/libs/routes_v1/test.js @@ -3,30 +3,98 @@ const oauth2orize = require('oauth2orize'); const passport = require('passport'); const ClientPasswordStrategy = require('passport-oauth2-client-password'); const testApp = express(); - const libs = `${process.cwd()}/libs`; const Client = require(`${libs}/models/client`); - +const User = require(`${libs}/models/user`) var server = oauth2orize.createServer(); - passport.use(new ClientPasswordStrategy( - function(clientId, clientSecret, done) { - console.log("ENTREI AQUI NO CLIENTPASSWORDSTRATEGY") - Clients.findOne({where:{client_id: clientId }}, function (err, client) { - if (err) { return done(err); } - if (!client) { return done(null, false); } - if (client.clientSecret != clientSecret) { return done(null, false); } + function(client_id, client_secret, done) { + Client.findOne({where: {client_id: client_id} + }).then(function(err, client) { + if(err){ + console.log("Erro de requisicao"); + return done(err); + } + if(!client){ + console.log("Erro de cliente"); + return done(null, false); + } + if (client.client_secret !== client_secret){ + console.log("Erro de geracao Chave Secreta"); + return done(null, false); + } + console.log("Tudo certo nesse use"); return done(null, client); - }); + }) } )); +let generateTokens = (userId, clientId, done) => { + // curries in `done` callback so we don't need to pass it + let refreshTokenValue; + let token; + let tokenValue; + + RefreshToken.destroy({where:{"user_id": userId, "client_id": clientId}}); + AccessToken.destroy({where:{"user_id": userId, "client_id": clientId}}); + + tokenValue = crypto.randomBytes(32).toString('hex'); + refreshTokenValue = crypto.randomBytes(32).toString('hex'); + + AccessToken.create({ + user_id:userId, + client_id:clientId, + token:tokenValue + }) + + let refreshed_token = refreshTokenValue; + + RefreshToken.create({ + user_id:userId, + client_id:clientId, + token:refreshed_token + }) + + token.save((err) => { + if (err) { + log.error(err); + return done(err); + } + done(null, tokenValue, refreshTokenValue, { + 'expires_in': config.security.tokenLife + }); + }) +}; + + +let entrar = function(client, username, done) { + User.findOne({ + where: {email:username} + }).then(function(user) { + console.log(user) + if(user == null){ + return done(null, false); + } + if(user.dataValues.origin != client.client_secret){ + console.log("Erro de client_secret"); + return done(null, false); + } + log.info(`Gerando token para usuário ${user.name}`); + generateTokens(user._id, client._id, done); + }).catch(function(error) { + return done(error); + }); + }; + + + + -testApp.get('/profile', - passport.authenticate(['oauth2-client-password'], { session: false }), - server.token()); +testApp.post('/', (req, res, next) =>{ + entrar(req.body, req.body.username); +}); module.exports = testApp; \ No newline at end of file