← back to the blog


Front End Widgets - Part 5 - Password Protecting the Artificial Back End

Posted in KeystoneJS, JavaScript

Table of Contents:

 

The front end side of things is pretty straightforward. The code in part 3 can be copy and pasted into any of the *.hbs Handlebar template files in the templates/views/ directory. These are the front end templates that KeystoneJS serves up. For instance, templates/views/index.hbs is the template for the home page.

You could do the same thing with the Artificial Back End, but then anyone with the URL will be able to maliciously update your widgets. I haven't figured out a way to password protect the API yet, so hopefully someone in the KeystoneJS group will chime in with a good way to do that. However, you can at least protect the Artificial Back End.

As an aside, here is what I've tried to password protect the API, but it didn't work. I have tried to change this line in routes/index.js:

app.all('/api/frontendwidget/:id/update', keystone.middleware.api, routes.api.frontendwidget.update);

to this:

app.all('/api/frontendwidget/:id/update', middleware.requireUser, routes.api.frontendwidget.update);

which seems to be the obvious way to password protect the API, but it errors out. We can however, do the same thing to password protect the page. In order to do that, add this line to routes/index.js:

// Setup Route Bindings
exports = module.exports = function(app) {
...
app.get('/updatefrontend', middleware.requireUser, routes.views.updatefrontend); };

 

That will create a password protected route to our new page. Now, create the file routes/views/updatefrontend.js and paste this code into it:

var keystone = require('keystone');

exports = module.exports = function(req, res) {

        var view = new keystone.View(req, res);
        var locals = res.locals;

        // Set locals
        locals.section = 'updatefrontend';

        // Load the galleries by sortOrder
        view.query('frontendcollections', keystone.list('FrontendWidget').model.find().sort('sortOrder'));

        // Render the view
        view.render('updatefrontend');

};

 

Finally, paste the html from Part 4 into the file templates/views/updatefrontend.hbs to complete the process. This hbs file is the html that KeystoneJS will serve. The page can be accessed from http://<your ip>:3000/updatefrontend and the page will require that you be loggined in as an Admin user.