Castle

This add-on is operated by Userbin Sweden AB

Stop bad people from logging in to your website

Castle

Last Updated: 05 March 2015

The Castle add-on is currently in beta.

Table of Contents

Userbin is the easiest way to setup, use and maintain a secure user authentication system for both your web and mobile apps, while keeping the users in your own database.

Userbin provides a set of login, signup, and password reset forms that drop right into your application without any need of styling or writing markup. Connect your users via traditional logins or third party social networks. We take care of linking accounts across networks, resetting passwords and sending out necessary emails, while keeping everything safe and secure.

Provisioning the add-on

Userbin can be attached to a Heroku application via the CLI:

A list of all plans available can be found here.

$ heroku addons:add userbin
-----> Adding userbin to sharp-mountain-4005... done, v18 (free)

Once Userbin has been added, a USERBIN_APP_ID setting will be available in the app configuration and is used publicly when Userbin.js is communicating with the cloud service. The USERBIN_API_SECRET setting will be used when your server interacts with the Userbin API and must not be shared. These settings can be confirmed using the heroku config:get command.

$ heroku config:get USERBIN_API_SECRET
vnyhJOWp3oOV942zur3DgA1hA0eMao1Q

After installing Userbin the application should be configured to fully integrate with the add-on.

Local setup

After provisioning the add-on it’s necessary to locally replicate the config vars so your development environment can operate against the service.

Though less portable it’s also possible to set local environment variables using export USERBIN_API_SECRET=value.

Use Foreman to configure, run and manage process types specified in your app’s Procfile. Foreman reads configuration variables from an .env file. Use the following command to add the Userbin credentials retrieved from heroku config to .env.

$ heroku config -s | grep USERBIN_ >> .env
$ more .env

Credentials and other sensitive configuration values should not be committed to source-control. In Git exclude the .env file with: echo .env >> .gitignore.

Using with Ruby on Rails

Installation and configuration

Add the userbin gem to your Gemfile

gem "userbin"

Install the gem

bundle install

Create config/initializers/userbin.rb and configure your credentials.

If you don’t configure the app_id and api_secret, the Userbin module will read the USERBIN_APP_ID and USERBIN_API_SECRET environment variables.

Userbin.configure do |config|
  config.app_id = "YOUR_APP_ID"
  config.api_secret = "YOUR_API_SECRET"
end

Implement getter and setter for your user model. For more information about the available attributes in the profile see the Userbin profile documentation.

config.find_user = -> (userbin_id) do
  User.find_by_userbin_id(userbin_id)
end

# will be called when a user signs up
config.create_user = -> (profile) do
  User.create! do |user|
    user.userbin_id = profile.id
    user.email      = profile.email
    user.photo      = profile.image
  end
end

Migrate your users to include a reference to the Userbin profile:

rails g migration AddUserbinIdToUsers userbin_id:integer:index
rake db:migrate

Authenticating users

Userbin keeps track of the currently logged in user which can be accessed through current_user in controllers, views, and helpers. This automatically taps into libraries such as the authorization library CanCan.

<% if current_user %>
  <%= current_user.email %>
<% else %>
  Not logged in
<% end %>

To set up a controller with user authentication, just add this before_filter:

class ArticlesController < ApplicationController
  before_filter :authorize!

  def index
    current_user.articles
  end
end

You can always access the Userbin profile for the logged in user as current_profile when you need to access information that you haven’t persisted in your user model.

Using with Node.js

Installation and configuration

Install the userbin package.

$ npm install userbin

Include the Userbin node packages in your app.js or server.js.

var userbin = require('userbin');

Configure the Userbin module with the credentials you got from signing up.

userbin.config({
  appId: 'YOUR_APP_ID',
  apiSecret: 'YOUR_API_SECRET'
});

If you don’t configure the appId and apiSecret, the Userbin module will read the USERBIN_APP_ID and USERBIN_API_SECRET environment variables.

Insert the Userbin authentication middleware after the cookieParser (and add the cookieParser if not present):

app.use(connect.cookieParser()); // or express.cookieParser()
app.use(userbin.authenticate());

Implement getter and setter for your user model. For more information about the available attributes in the profile see the Userbin profile documentation.

userbin.config({
  findUser: function(userbinId, done) {
    User.findOne({ userbinId: userbinId }, function(err, user) {
      done(user);
    });
  },

  createUser: function(profile, done) {
    var user = User.new({
      userbinId : profile.id,
      email     : profile.email,
      photo     : profile.image
    });
    user.save(function(err, user) {
      done(user);
    });
  }
})

Authenticating users

Userbin keeps track of the currently logged in user which can be accessed in your controllers and views through the req.currentUser property which needs to be explicitly passed to your views.

Insert the userbin.authorize() middleware to protect a route fron non-logged in users.

app.get('/account', userbin.authorize(), function(req, res) {
  res.render('account', {currentUser: req.currentUser});
});

You can always access the Userbin profile for the logged in user as req.currentProfile when you need to access information that you haven’t persisted in your user model.

Using with PHP

Installation and configuration

Download Userbin into your project:

$ curl -O https://raw.github.com/userbin/userbin-php/master/userbin.php

All you need to is to include userbin.php at the top of your files, configure it with you App ID and API secret, and finally run the Userbin authentication sync. The authenticate method will make sure that the user session is refreshed when it expires.

If you’re not using output buffering this needs to be done before any output has been written since Userbin will modify headers.

<?php
require_once('userbin.php');

Userbin::set_app_id('YOUR_APP_ID');
Userbin::set_api_secret('YOUR_API_SECRET');

Userbin::authenticate();
?>

Include Userbin.js at the bottom of all your web pages to enable form helpers and session handling.

      ...
      <?= Userbin::javascript_include_tag(); ?>
  </body>
</html>

Authenticating users

Userbin keeps track of the currently logged in user:

<? if (Userbin::current_user()): ?>
  <? $user = Userbin::current_user() ?>
  Welcome to your account, <?= $user['email'] ?>
<? else: ?>
  Not logged in
<? endif; ?>

Put the authorize method at the top of a file to halt the execution and render a login page if the user is not logged in:

<?php Userbin::authorize(); ?>

You can always access the Userbin profile for the logged in user as Userbin::current_profile() when you need to access information that you haven’t persisted in your user model.

Using with mobile

Please see the documentation for iOS and Android on how to get started with Userbin in mobile apps.

Forms

Once you have set up authentication it’s time to choose among the different ways of integrating Userbin into your application.

Ready-made forms

The easiest and fastest way to integrate login and signup forms is to use the Userbin Widget, which provides a set of ready-made views which can be customized to blend in with your current user interface. These views open up in a popup, and on mobile browsers they open up a new window tailored for smaller devices.

rel specifies action; possible options are login and logout.

<a href="/account" rel="login">Log in</a>
<a href="/account" rel="signup">Sign up</a>

Social buttons

Instead of signing up your users with a username and password, you can offer them to connect with a social identity like Facebook or LinkedIn. To use these button you must first configure your social identiy providers from the dashboard. It is also possible to connect a social identity to an already logged in user and the two accounts will be automatically linked.

rel determines action. If the user didn’t exist before, it’s created, otherwise it’s logged in.

<a href="/account" rel="connect-facebook">Connect with Facebook</a>
<a href="/account" rel="connect-linkedin">Connect with LinkedIn</a>

Custom forms

The ready-made forms are fairly high level, so you might prefer to use Userbin with your own markup to get full control over looks and behavior.

If you create a form with name set to login or signup, the user will be sent to the URL specified by action after being successfully processed at Userbin.

Inputs with name email and password are processed, others are ignored.

If you add an element with the class error-messages, it will be automatically set to display: block and populated with a an error message when something goes wrong. So make sure to it is display: hidden by default.

<form action="/account" name="signup">
  <span class="error-messages"></span>
  <div class="row">
    <label>E-mail</label>
    <input name="email" type="text"></input>
  </div>
  <div class="row">
    <label>Password</label>
    <input name="password" type="password"></input>
  </div>
  <button type="submit">Sign up</button>
</form>

Log out

Clears the session and redirects the user to the specified URL.

<a href="/" rel="logout">Log out</a>

Dashboard

With Userbin you get an admin dashboard out of the box.

  • Invite, update, remove and ban users
  • Log in as any of your users for debugging
  • Configure user validation, access rights and login methods
  • See who is using your web or mobile app in real-time.
  • Customize copy and appearance of your transactional emails.

The dashboard can be accessed via the CLI:

$ heroku addons:open userbin
Opening userbin for sharp-mountain-4005…

or by visiting the Heroku apps web interface and selecting Userbin from the Add-ons menu.

Removing the add-on

Userbin can be removed via the CLI.

This will destroy all associated data and cannot be undone!

$ heroku addons:remove userbin
-----> Removing userbin from sharp-mountain-4005... done, v20 (free)

Before removing Userbin a data export can be performed by visiting your dashboard and export your data as JSON or CSV.

Going further

Hopefully this has given you a taste of the great stuff you can do with Userbin. We recommend having a look through our Userbin documentation to get an idea of what else is available.

Support & feedback

All Userbin support and runtime issues should be submitted via on of the Heroku Support channels. Any non-support related issues or product feedback is welcome by email.