Skip to content

Commit

Permalink
Oauth implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
Hemil96 committed Aug 13, 2018
1 parent 9d6a5c1 commit da31b96
Show file tree
Hide file tree
Showing 12 changed files with 747 additions and 95 deletions.
6 changes: 3 additions & 3 deletions config/database.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
database: 'mongodb://localhost:27017/oath-nodejs',
secret: 'yoursecret'
};
database: 'mongodb://localhost:27017/oauth2',
secret: 'yoursecret',
};
20 changes: 20 additions & 0 deletions helper/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const bcrypt = require('bcrypt');
const User = require('../model/user');

const comparePassword = (textPassword, hash) => {
return new Promise((resolve, reject) => {
bcrypt.compare(textPassword, hash)
.then((res) => {
resolve(res);
})
.catch((err) => {
console.log(err);
reject(err);
});
});
};

const utils = {
comparePassword,
};
module.exports = utils;
88 changes: 44 additions & 44 deletions methods/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,59 +2,54 @@ const jwt = require('jwt-simple');
const User = require('../model/user');
const Book = require('../model/book');
const config = require('../config/database');
const utils = require('../helper/utils');

const authenticate = (req, res) => {
User.findOne({
name: req.body.name,
}, (err, user) => {
if (err) throw err;

if (!user) {
res.status(403).send({ success: false, msg: 'Authentication failed, User not found' });
} else {
user.comparePassword(req.body.password, (err, isMatch) => {
if (isMatch && !err) {
const token = jwt.encode(user, config.secret);
res.json({ success: true, token: token });
} else {
return res.status(403).send({ success: false, msg: 'Authenticaton failed, wrong password.' });
}
});
}
});
User.findOne({ name: req.body.name })
.then((user) => {
this.user = user;
if (!user) return res.status(403).send({ success: false, msg: 'Authentication failed, User not found' });
return utils.comparePassword(req.body.password, user.password);
})
.then((isMatch) => {
if (!isMatch) return res.status(403).send({ success: false, msg: 'Authenticaton failed, wrong password.' });
const token = jwt.encode(this.user, config.secret);
return res.json({ success: true, token: token });
})
.catch((err) => {
console.log(err);
return res.status(500).send({ success: false, error: err });
});
};

const addNew = (req, res) => {
if ((!req.body.name) || (!req.body.password)) {
console.log(req.body.name);
console.log(req.body.password);

res.json({ success: false, msg: 'Enter all values' });
} else {
const userToCreate = {
name: req.body.name,
password: req.body.password,
};
const newUser = new User(userToCreate);
return res.status(400).json({ success: false, msg: 'Enter all values' });
}
const userToCreate = {
name: req.body.name,
password: req.body.password,
};
const newUser = new User(userToCreate);

newUser.save((err, newUser) => {
if (err) {
res.json({ success: false, msg: 'Failed to save' });
} else {
res.json({ success: true, msg: 'Successfully saved' });
}
newUser.save()
.then((createdUser) => {
if (!createdUser) return res.status(500).json({ success: false, msg: 'Failed to save' });
return res.status(201).json({ success: true, msg: 'Successfully saved' });
})
.catch((err) => {
console.log(err);
return res.status(500).json({ success: false, msg: 'Failed to save' });
});
}
};

const getinfo = (req, res) => {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
const token = req.headers.authorization.split(' ')[1];
const decodedtoken = jwt.decode(token, config.secret);
return res.json({ success: true, msg: `hello ${decodedtoken.name}` });
return res.status(200).json({ success: true, msg: `hello ${decodedtoken.name}` });
}

return res.json({ success: false, msg: 'No header' });
return res.status(400).json({ success: false, msg: 'No header' });
};

const addBook = (req, res) => {
Expand All @@ -64,21 +59,26 @@ const addBook = (req, res) => {
userId: req.user_id,
};
const newBook = new Book(bookToCreate);
newBook.save(((err, bookCreated) => {
if (err) console.log(err);
else return res.json({ message: 'New Book Added to the locker:', data: bookCreated });
}));
newBook.save()
.then((createdBook) => {
if (!createdBook) return res.json({ success: false, msg: 'Failed to save' });
return res.status(200).json({ success: true, msg: 'Successfully saved' });
})
.catch((err) => {
console.log(err);
return res.status(500).json({ success: false, msg: 'Failed to save' });
});
};

const getBook = (req, res) => {
Book.find({ userId: req.user_id })
.then((foundBook) => {
if (!foundBook) return res.json({ error: 'Book not found' });
if (!foundBook) return res.status(404).json({ error: 'Book not found' });
return res.json({ message: 'Book found', data: foundBook });
})
.catch((err) => {
console.log(err);
return res.json({ error: err });
return res.status(500).json({ error: err });
});
};

Expand Down
7 changes: 3 additions & 4 deletions methods/auth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const JwtStrategy = require('passport-jwt').Strategy;
const passport = require('passport').initialize();
// const passport = require('passport').initialize();
const passport = require('passport');
const { ExtractJwt } = require('passport-jwt');
const JwtBearerStrategy = require('passport-http-jwt-bearer');
const { BasicStrategy } = require('passport-http');
Expand All @@ -8,10 +9,9 @@ const User = require('../model/user');
const Token = require('../model/token');
const Client = require('../model/client');


const opts = {};
opts.secretOrKey = config.secret;
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();

passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.find({ id: jwt_payload.id }, (err, user) => {
Expand Down Expand Up @@ -44,7 +44,6 @@ passport.use(new JwtBearerStrategy(
Token.findById(token._id, (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false); }
// console.log(user);
return done(null, user, token);
});
},
Expand Down
29 changes: 19 additions & 10 deletions methods/client.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Load required packages
var Client = require('../model/client');

// Create endpoint /api/client for POST
// /client for POST
const postClients = (req, res) => {
// Set the client properties that came from the POST data
const clientToCreate = {
Expand All @@ -13,22 +13,31 @@ const postClients = (req, res) => {

// Create a new instance of the Client model
var client = new Client(clientToCreate);
console.log(client);

// Save the client and check for errors
client.save((err) => {
if (err) { res.send(err); }
return res.json({ message: 'Client added to the locker!', data: client });
});
client.save()
.then((createdClient) => {
if (!createdClient) return res.status(500).json({ error: 'Failed to create' });
return res.json({ message: 'Client added to the locker!', data: client });
})
.catch((err) => {
console.log(err);
return res.status(500).json({ error: 'Failed to create' });
});
};

// Create endpoint /api/clients for GET
const getClients = (req, res) => {
// Use the Client model to find all clients
Client.find({ userId: req.body.userId }, (err, clients) => {
if (err) { res.send(err); }
return res.json(clients);
});
Client.find({ userId: req.query.userId })
.then((foundClient) => {
if (!foundClient) return res.status(404).json({ error: 'Client not found' });
return res.json({ message: 'Client found', data: foundClient });
})
.catch((err) => {
console.log(err);
return res.status(500).json({ error: 'Failed to find' });
});
};

const clientMethods = {
Expand Down
109 changes: 109 additions & 0 deletions methods/oauth2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Load required packages
var oauth2orize = require('oauth2orize');
var jwt = require('jwt-simple');
var Client = require('../model/client');
var Token = require('../model/token');
var Code = require('../model/code');
var config = require('../config/database');

var server = oauth2orize.createServer();


const getRandomInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};

const uid = (len) => {
var buf = [];
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charlen = chars.length;

for (let i = 0; i < len; i++) {
buf.push(chars[getRandomInt(0, charlen - 1)]);
}
return buf.join('');
};

// Register serialialization function
server.serializeClient((client, callback) => {
return callback(null, client._id);
});

// Register deserialization function
server.deserializeClient((id, callback) => {
Client.findOne({ _id: id }, (err, client) => {
if (err) { return callback(err); }
return callback(null, client);
});
});

// Register authorization code grant type
server.grant(oauth2orize.grant.code((client, redirectUri, user, ares, callback) => {
// Create a new authorization code
var code = new Code({
value: uid(16),
clientId: client._id,
redirectUri: redirectUri,
userId: client.userId,
});

// Save the auth code and check for errors
code.save((err) => {
if (err) { return callback(err); }

callback(null, code.value);
});
}));

server.exchange(oauth2orize.exchange.code((client, code, redirectUri, callback) => {
Code.findOne({ value: code }, (err, authCode) => {
if (err) { return callback(err); }
if (authCode === undefined) { return callback(null, false); }
if (client._id.toString() !== authCode.clientId) { return callback(null, false); }
if (redirectUri !== authCode.redirectUri) { return callback(null, false); }

// Delete auth code now that it has been used
authCode.remove((err) => {
if (err) { return callback(err); }

// Create a new access token
const token = new Token({
value: uid(256),
clientId: authCode.clientId,
userId: authCode.userId,
});

// Save the access token and check for errors
token.save((err) => {
if (err) { return callback(err); }
const enctoken = jwt.encode(token, config.secret);
callback(null, enctoken);
});
});
});
}));

// User authorization endpoint
exports.authorization = [
server.authorization((clientId, redirectUri, callback) => {
Client.findOne({ id: clientId }, (err, client) => {
if (err) { return callback(err); }

return callback(null, client, redirectUri);
});
}),
(req, res) => {
console.log(config.userid);
res.render('dialog', { transactionID: req.oauth2.transactionID, user: config.userid, client: req.oauth2.client });
},
];

exports.decision = [
server.decision(),
];

// Application client token exchange endpoint
exports.token = [
server.token(),
server.errorHandler(),
];
Loading

0 comments on commit da31b96

Please sign in to comment.