Researching MeteorJS – Authentication

As the 2nd Rate Geniuses told me, authentication with MeteorJS was a piece of cake.

Here’s how it went down.

As you may recall (previous post), we’ve setup a simple multi-page app. It’s got 2 pages. One for viewing and one for administration. The view page should be available with no login. Admin is for logged in users only.

Setting Up a Login System (Authentication)

To setup Meteor auth, I removed the insecure package (turned on by default) and added the accounts packages: accounts-ui-unstyled and accounts-github. This will allow login to happen via Github’s Oauth service.

meteor remove insecure
meteor add accounts-ui-unstyled
meteor add accounts-github

As a first cut, we can add the login form to the index template which will allow signin from anywhere. For my app, the main layout is /app.html. So I started with the following:

<body>
  <div class='login">
    {{loginButtons}}
  </div>
  {{#if currentUser}}
    Welcome, {{currentUser.profile.name}}
  {{/if}}
  <section> 
    {{renderPage}}
  </section>
</body>

This gives you the unstyled (because we’re using accounts-ui-unstyled) login form. From here you’re given a link that tells you as the site-administrator to link in to Github’s Oauth. It involves setting up an API key and secret for the app and a couple of callback URLs. You can follow the instructions from Meteor. Once those keys and callbacks are setup, the {{loginButtons}} partial gives you a ‘Sign in via Github’ link. Easy peasy.

From there, we can start modifying templates to do the right thing based on the state of the current user. If you’re in client/server code, use

if (Meteor.user()) {
 // users only get this
}
else {
 // plain ol' visitors get this
}

and in the templates, there’s a helper attribute/method called currentUser

  <section>
    {{#if currentUser}}
       <div class="for_logged_in_users_only">
       </div>
    {{/if}}
  </section>

One of the downsides (as I see it) is that their built in template for login allows user creation with no email validation (from what i can tell). More importantly, there is no easy way to customize the template to not show the ‘sign up’ link and only have a ‘sign in’ link. For my purposes, I’d love to seed the database with the users that I want, and send them a login invite. Because my “users” are going to be full site editors and should have mostly full reign. And everyone else should not need an account.

To accomplish this, I decided to build a route to a sign in/sign up page which is protected only by obsurity (imagine a login link that is called /you_hit_this_path_to_login). I think it’ll work for now.

Here’s how I setup the routes:

if Meteor.isClient

  Meteor.Router.add
    '/': 'index'
    '/admin': 'admin'
    '/obscure_login_link': 'obscure_login_link'

  Meteor.Router.filters
    'checkLoggedIn': (page) ->
      if Meteor.loggingIn()
        'loading';
      else if Meteor.user()
        page
      else
        'index'

  Meteor.Router.filter 'checkLoggedIn', { except:['obscure_login_link','index'] }

This pushes non-logged in users to the index page and sets up the obscured login path.

Then I moved the {{loginButtons}} bit so it only shows up in the admin and obscure_login_link templates. The only way to create an account is to hit the obscure_login_link which has no external pointers to it, and only allows Github connections, so there are a few hurdles to get over.

Restricted Access based on Login Status (Authorization)

Now, we can assume that there are user accounts in the system. We can use the built-in allow/deny methods in Meteor to restrict data modification.

In our Block model (again, check the previous post to read about the app’s model), we can add the following to models/blocks.coffee

Blocks.allow
  insert: (userId, block) ->
    user = Meteor.user()
    if user
      block.user = user
    user

After this, blocks can only be added by a logged in user. To verify, I ran a couple insert/update requests on the browser console and happily was thwarted by the auth engine.

> Blocks.insert({title:'newblock', color:'olive'})
"f26fa3f8-8400-4ae7-ac94-b6346d6011cf"
insert failed: Access denied

> Blocks.update(Blocks.findOne(), {title:'whatever yo'})
undefined
logging.js:30update failed: Access denied. Can't replace document in restricted collection.

With this small amount of code/config, we’ve now got an app that allows login via Github Oauth and restricts database access to logged in users.

Next steps: getting a test framework setup.

Advertisements

Researching MeteorJS

I’ve been looking to upgrade one of my old sites and learn some more Javascript tricks. The basic site requirements are:

  • easily add blocks of content
  • content blocks should include (optionally) background images, color theme, title, content (markdown or similar) and some metadata
  • admin-only access to edit/update methods
  • test framework should be Jasmine or Mocha

It seemed like this might be a perfect small-ish project to investigate some of the new Javascript web-app frameworks. This post will serve to share some of my findings. Though there are piles of frameworks to choose from (and framework combos), I started off looking into MeteorJS – http://meteorjs.org.

Getting Started

curl https://install.meteor.com | /bin/sh
meteor create /projects/myapp_meteor
cd /projects/myapp_meteor
meteor

At this point, we’ve got a webserver listening at localhost:3000.

Building out the app

I added a Block collection in models/block.coffee; setup admin and index templates under the client/ directory. Then after adding a form admin template, a block template and a loop on the index page to draw all blocks, the basic app was almost in place. The final step was adding meteorite to my system (seems like a must have – think bundler for meteor) and added the meteor-router package to the project (this makes it easy to build out a multi-page app). Finally wuth a bit of file reorg to give the project a semblance of structure, I ended up with a directory tree that looked like this (ignoring .meteor/):


main.html
routes.coffee
client/
  client.coffee
  admin.template.coffee
  index.template.coffee
models/
  blocks.coffee
server/
  server.coffee
stylesheets/
  main.css
views/
  admin.html
  index.html
  block.html

Meteor picked up these changes with out a hiccup – live updates are pretty cool.

Here’s a couple of snippets of the code to see how simple things are:

A collection:

# models/blocks.coffee
Blocks = new Meteor.Collection('blocks')

The template for the block:

<!-- in views/block.html -->
<template name="block">
  <div class="block {{selected}} {{color}}">
    <span class="title">{{title}}</span>
    <div class="content">{{content}}</span>
    <span class="link">{{link}}</span>

    <div class="delete" id="{{id}}"><a href='#'>x</a></div>
  </div>
</template>

The admin template with an input form:

<!-- in views/admin.html - DOM here is bootstrap ready -->
<template name="add_block_inputs">
  <div class="add_block_inputs">
    <div class="row">
      <label>title</label>
      <input id="block_title" type="text" placeholder="enter a title"/>
    </div>
    <div class="row">
      <label>content</label>
      <textarea id="block_content" placeholder="enter some content"></textarea>
    </div>
    <div class="row">
      <label>link</label>
      <input id="block_link" type="text" placeholder="enter link"/>
    </div>
    <div class="row">
      <label>color</label>
      <select id="block_color">
        <option value='dark_purple'>dark purple</option>
        <option value='burgundy'>burgundy</option>
        <option value='olive'>olive</opiton>
      </select>
    </div>
    <input class="btn add_block" type="button" value="add block" />
  </div>
</template>

In the client, we bind the button to submit the new data, and bind a “remove” action on the X for each block.

# in admin.template.coffee
if Meteor.isClient

  Template.admin.blocks = ->
    Blocks.find {},
      sort:
        title: 1

  Template.admin.events
    "click input.add_block": ->
      # template data, if any, is available in 'this'
      tt = @document.getElementById("block_title").value
      md = @document.getElementById("block_content").value
      lk = @document.getElementById("block_link").value
      cl = @document.getElementById("block_color").value
      Blocks.insert title: tt, content: md, link: lk, color: cl if tt || md || lk || cl
      false

    "click .block .delete": ->
      Blocks.remove(this)
      false

And that’s basically it. At this point, Meteor is showing me all my blocks and allows me to add and remove blocks with ease. The collection is auto-tied into a MongoDB instance which is setup automagically (assuming you have MongoDB installed and running on your machine).

The next steps are to figure out authorization to control read/write access to the database and figure out how to get a test framework up and running.

I had lunch with the 2nd Rate Genius team who’ve recently been down this same road. From there investigations, it seems that the Meteor auth stuff has been pretty well developed and should be easy to hook in. And their system of allow/deny on collections should be pretty easy to set up to help control data access.

I’m looking forward to some more learning with this Javascript full-stack solution. As I learn more, I’ll share what I can.

Quick method performance checker

With ruby there are often many ways to perform the same operation. Recently I learned that the * operator can act like join for strings.
I wanted to do a little performance check to see if one is faster than the other.

Using ruby blocks, I wrote up a timed_run method:

def timed_run(*args, &block)
  t = Time.now
  block.call
  dt = (Time.now - t)
  puts "[#{args.first}] #{dt}msec"
end

With this helper, I then wrote up several methods to test joining strings with separators:

def join_with_join(arr, sep)
  arr.join sep
end

def join_with_times(arr, sep)
  arr * sep
end

def join_with_plus(arr, sep)
  val = ''
  arr.each{|a| val += sep if val.length > 0; val += a }
  val
end

def join_with_append(arr, sep)
  val = ''
  arr.each{|a| val << sep if val.length > 0; val << a }
  val
end

Putting this all together, I was able to test my different join implementations for performance:

def gen_random_string
  # exercise for reader
end

num_runs = 100000
arr = (25 + rand(4)).times.map{ gen_random_string }
sep = " , "
%w(join_with_plus join_with_times join_with_join join_with_append).each do |meth|
  timed_run(meth) { num_runs.times { send(meth, arr, sep) }}
end

and very quickly see that the * and join operators are basically the same
in terms of performance. And I learned that the << is slow but much faster than +.

[join_with_append] 1.19829msec
[join_with_join] 0.436115msec
[join_with_times] 0.431106msec
[join_with_plus] 4.26063msec

It's a nice usage of the call method and Ruby blocks. I learned a few tricks and now i have a nice little timer script that I can use to test other implementations of other algorithms.