     @login = undefined
     @password = undefined
 
+    # Add HTTP Basic Authentication header to request
+    addAuthHeader = (r) =>
+        r.setRequestHeader 'Authorization', makeBasicAuth @login, @password
+
+    # Common handlers for response status codes
+    # Todo: It is unfortunate that we need the context here to call partial...
+    statusHandlers = (context) ->
+        401: -> context.partial '/templates/401.mustache'
+
     # Index
     @get '/', ->
         @$element().html 'Haha, this is the index :)'

# Create HTTP Basic Authentication header value
makeBasicAuth = (login, password) ->
    'Basic ' + $.base64.encode (login + ':' + password)


# Set authentication state
setAuthentication = (user) ->
    clearAuthentication()
    if user?
        state = 'success'
        showUser user
    else
        state = 'fail'
    $('#form-authenticate').addClass state


# Clear authentication state
clearAuthentication = ->
    $('#form-authenticate').removeClass 'success fail'
    $('#userbar').empty()


# Show user in sidebar
showUser = (user) ->
    $('#userbar').empty().append $("<h3>#{ user.name }</h3><p>Roles: #{ user.roles.join ', ' }</p>")


# Our Sammy application

    # List samples
    @get '/samples', ->
        $.ajax '/api/v1/samples',
            beforeSend: addAuthHeader
            success: (r) => @partial '/templates/samples.mustache', r
            statusCode: statusHandlers this
            dataType: 'json'

    # Show sample
    @get '/samples/:sample', ->
        $.ajax "/api/v1/samples/#{ @params['sample'] }",
            beforeSend: addAuthHeader
            success: (r) => @partial '/templates/sample.mustache', r
            statusCode: statusHandlers this
            dataType: 'json'

    # Authentication event
    @bind 'authentication', =>
        $('#form-authenticate').removeClass 'success fail'
        $('#userbar').empty()
        if @user?
            state = 'success'
            $('#userbar').append $("<h3>#{ @user.name }</h3>
                                    <p>Roles: #{ @user.roles.join ', ' }</p>")
        else
            state = 'fail'
        $('#form-authenticate').addClass state
        @refresh()


