Skip to content

Instantly share code, notes, and snippets.

@Ravenstine
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ravenstine/aa316bbadbfef108dbbe to your computer and use it in GitHub Desktop.
Save Ravenstine/aa316bbadbfef108dbbe to your computer and use it in GitHub Desktop.
couchbase_and_pouchdb

todo.js.coffee

startListening = () ->
  db = new PouchDB('http://localhost:4984/divisionx/')
  todos = document.querySelector('#todos')

  sync = ->
    opts = live: true
    db.replicate.to true, opts, syncError
    db.replicate.from true, opts, syncError

  showTodos = ->
    # This cheaply gets and renders all the documents any time there's an update.
    # Nothing too fine-grained here.
    todos.innerHTML = ''
    db.allDocs {
      include_docs: true
      descending: true
    }, (err, doc) ->
      if doc
        i = 0
        len = doc?.rows?.length or 0
        todos.innerHTML = ""
        while i < len
          todos.innerHTML = todos.innerHTML + '<li>' + doc.rows[i].doc.text + '</li>'
          i++

  syncError = ->
    alert 'cannot sync'

  db.changes(
    since: 'now'
    live: true).on 'change', showTodos

  showTodos()
  sync()


$(document).ready ->
  # This is where be propmt the user for a username and password.
  # We then send those credentials to SCPRv4, which authenticates
  # these credentials.  On authentication, a user is created in
  # the sync gateway and the gateway returns a session ID, which 
  # SCPRv4 adds to a cookie.
  # The cookie allows the code under the startListening function
  # to be authenticated directly against the sync gateway.
  if document.querySelector("ul#todos")
    username = prompt("Enter your username")
    password = prompt("Enter your password")

    $.ajax(
      url: '/api/v3/sign-in'
      method: "POST"
      data: 
        username: username
        password: password
      dataType: "json"
      context: document.body).done (response) ->
        startListening()

sign_in_controller.rb

module Api::Public::V3
  class SignInController < BaseController
    require 'net/http'
    def authenticate
      ## The line below is our dummy authentication.
      if params[:username] == "fakeuser" && params[:password] == "fakepassword"
        create_user_from params[:username]
        session = create_session_for params[:username]
        cookies[session['cookie_name']] = {value: session['session_id'], expires: Time.parse(session['expires'])}
        render json: {}, status: "200"
      else
        render json: {error: "Invalid username or password"}, status: "403"
      end
    end
  private
    def create_session_for username
      send_post_to_gateway("localhost", "http://localhost:4985/divisionx/_session", {
        name: username,
      })
    end
    def create_user_from username
      send_post_to_gateway("localhost", "http://localhost:4985/divisionx/_user/", {
        name: username,
        password: SecureRandom.urlsafe_base64,
      })
    end
    def send_post_to_gateway host, path, data
      req = Net::HTTP::Post.new(path, initheader = { 'Content-Type' => 'application/json'})
      req.body = data.to_json
      response = Net::HTTP.new(host, 4985).start {|http| http.request(req) }
      JSON.parse(response.body)
    rescue JSON::ParserError
      {}         
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment