carolineschnapp
12/6/2009 - 1:56 AM

login_controller.rb

class LoginController < ApplicationController
  def index
    # Ask user for their #{shop}.myshopify.com address
  end

  def authenticate
    redirect_to ShopifyAPI::Session.new(params[:shop].chomp('/')).create_permission_url
  end

  # Shopify redirects the logged-in user back to this action along with
  # the authorization token t.
  # 
  # This token is later combined with the developer's shared secret to form
  # the password used to call API methods.
  def finalize
    shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t], params)
    if shopify_session.valid?
      session[:shopify] = shopify_session
      flash[:notice] = "Logged in to shopify store."
      
      unless Shop.find_by_url(current_shop.url)
        # Saving the shop ID to our database.
        ShopifyAPI::Base.site = current_shop.site
        Shop.create(:url => current_shop.url, :shop_id => current_shop.shop.id)
        # Registering our webhook.
        webhook = ShopifyAPI::Webhook.create(
          :address => 'http://localhost:3000/orders/create',
          :topic => 'orders/create'
        )
      end
      
      return_address = session[:return_to] || '/home'
      session[:return_to] = nil
      redirect_to return_address
    else
      flash[:error] = "Could not log in to Shopify store."
      redirect_to :action => 'index'
    end
  end
  
  def logout
    session[:shopify] = nil
    flash[:notice] = "Successfully logged out."
    
    redirect_to :action => 'index'
  end

end