Skip to content

Fix #37 - Authenticated User Routes #54

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 51 additions & 58 deletions 17-user-crm/app/routes/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ module.exports = function(app, express) {
if (!user) {
var sampleUser = new User();

sampleUser.name = 'Chris';
sampleUser.username = 'chris';
sampleUser.name = 'Chris';
sampleUser.username = 'chris';
sampleUser.password = 'supersecret';

sampleUser.save();
Expand All @@ -37,6 +37,27 @@ module.exports = function(app, express) {

});

// create a user (accessed at POST http://localhost:8080/users)
apiRouter.post('/users', function(req, res) {
var user = new User(); // create a new instance of the User model
user.name = req.body.name; // set the users name (comes from the request)
user.username = req.body.username; // set the users username (comes from the request)
user.password = req.body.password; // set the users password (comes from the request)

user.save(function(err) {
if (err) {
// duplicate entry
if (err.code == 11000)
return res.json({ success: false, message: 'A user with that username already exists. '});
else
return res.send(err);
}

// return a message
res.json({ message: 'User created!' });
});
});

// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRouter.post('/authenticate', function(req, res) {

Expand All @@ -49,18 +70,18 @@ module.exports = function(app, express) {

// no user with that username was found
if (!user) {
res.json({
success: false,
message: 'Authentication failed. User not found.'
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
} else if (user) {

// check if password matches
var validPassword = user.comparePassword(req.body.password);
if (!validPassword) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
} else {

Expand All @@ -79,14 +100,14 @@ module.exports = function(app, express) {
message: 'Enjoy your token!',
token: token
});
}
}

}

});
});

// route middleware to verify a token
// route middleware to verify a token for all reqs that happen after this point
apiRouter.use(function(req, res, next) {
// do logging
console.log('Somebody just came to our app!');
Expand All @@ -98,17 +119,17 @@ module.exports = function(app, express) {
if (token) {

// verifies secret and checks exp
jwt.verify(token, superSecret, function(err, decoded) {
jwt.verify(token, superSecret, function(err, decoded) {

if (err) {
res.status(403).send({
success: false,
message: 'Failed to authenticate token.'
});
} else {
res.status(403).send({
success: false,
message: 'Failed to authenticate token.'
});
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;

next(); // make sure we go to the next routes and don't stop here
}
});
Expand All @@ -117,57 +138,29 @@ module.exports = function(app, express) {

// if there is no token
// return an HTTP response of 403 (access forbidden) and an error message
res.status(403).send({
success: false,
message: 'No token provided.'
res.status(403).send({
success: false,
message: 'No token provided.'
});

}
});

// test route to make sure everything is working
// test route to make sure everything is working
// accessed at GET http://localhost:8080/api
apiRouter.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
res.json({ message: 'hooray! welcome to our api!' });
});

// on routes that end in /users
// ----------------------------------------------------
apiRouter.route('/users')

// create a user (accessed at POST http://localhost:8080/users)
.post(function(req, res) {

var user = new User(); // create a new instance of the User model
user.name = req.body.name; // set the users name (comes from the request)
user.username = req.body.username; // set the users username (comes from the request)
user.password = req.body.password; // set the users password (comes from the request)

user.save(function(err) {
if (err) {
// duplicate entry
if (err.code == 11000)
return res.json({ success: false, message: 'A user with that username already exists. '});
else
return res.send(err);
}

// return a message
res.json({ message: 'User created!' });
});

})

// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function(req, res) {

User.find({}, function(err, users) {
if (err) res.send(err);
// get all the users (accessed at GET http://localhost:8080/api/users)
apiRouter.get('/users', function(req, res) {
User.find({}, function(err, users) {
if (err) res.send(err);

// return the users
res.json(users);
});
// return the users
res.json(users);
});
});

// on routes that end in /users/:user_id
// ----------------------------------------------------
Expand Down
8 changes: 4 additions & 4 deletions 17-user-crm/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ app.use(bodyParser.json());
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization');
next();
});

// log all requests to the console
// log all requests to the console
app.use(morgan('dev'));

// connect to our database (hosted on modulus.io)
mongoose.connect(config.database);
mongoose.connect(config.database);

// set static files location
// used for requests that our frontend will make
Expand All @@ -41,7 +41,7 @@ app.use(express.static(__dirname + '/public'));
var apiRoutes = require('./app/routes/api')(app, express);
app.use('/api', apiRoutes);

// MAIN CATCHALL ROUTE ---------------
// MAIN CATCHALL ROUTE ---------------
// SEND USERS TO FRONTEND ------------
// has to be registered after API ROUTES
app.get('*', function(req, res) {
Expand Down