Skip to content

Instantly share code, notes, and snippets.

@mecampbellsoup
Last active December 21, 2015 19:59
Show Gist options
  • Save mecampbellsoup/6357855 to your computer and use it in GitHub Desktop.
Save mecampbellsoup/6357855 to your computer and use it in GitHub Desktop.
Excerpts from my Duke Recruits app. Things work great on localhost, but falls apart on Heroku.
class Authentication < ActiveRecord::Base
devise :omniauthable
belongs_to :user
end
# config/initializers/devise.rb
Devise.setup do |config|
require "omniauth-google-oauth2"
require "omniauth-facebook"
require 'omniauth-linkedin-oauth2'
require 'linkedin'
config.omniauth :google_oauth2, ENV['GOOGLE_ID'], ENV['GOOGLE_SECRET'], { scope: 'userinfo.email, userinfo.profile, https://www.google.com/m8/feeds', access_type: 'offline', client_options: {:ssl => {:ca_file => '/usr/lib/ssl/certs/ca-certificates.crt'}} }
config.omniauth :facebook, ENV['FACEBOOK_ID'], ENV['FACEBOOK_SECRET']
config.omniauth :linked_in, ENV['LINKEDIN_API_KEY'], ENV['LINKEDIN_SECRET_KEY']
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class with default "from" parameter.
config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
end
source 'https://rubygems.org'
ruby '2.0.0'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'
gem 'awesome_print'
gem 'simple_form'
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
group :production do
gem 'rails_12factor'
gem 'pg'
end
gem "twitter-bootstrap-rails"
gem "therubyracer"
gem "less-rails" #Sprockets (what Rails 3.1 uses for its asset pipeline) supports LESS
gem 'protected_attributes'
gem 'omniauth-google-oauth2'
gem 'omniauth-facebook'
gem 'omniauth-linkedin-oauth2'
gem 'linkedin'
gem 'devise'
gem 'uuidtools'
gem 'icalendar'
gem 'rest-client'
group :development do
gem "better_errors"
gem "binding_of_caller"
gem 'pry-debugger'
gem "nifty-generators"
end
group :development, :test do
gem 'sqlite3'
end
# Use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
oauthorize "Facebook"
end
def google_oauth2
oauthorize "Google"
end
def linkedin
oauthorize "LinkedIn"
end
private
def oauthorize(kind)
user = User.find_for_ouath(kind, request.env["omniauth.auth"], current_user)
if user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => kind
sign_in_and_redirect user, :event => :authentication
else
session["devise.#{kind.downcase}_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
DukeRecruits::Application.routes.draw do
get "comments/create"
root :to => "welcome#index"
#devise_for :users
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
resources :companies, only: [:show, :index]
resources :events, only: [:index, :show] do
resources :comments, only: :create
end
get "events/:id/export", to: "events#export", as: :ical_export
get "events/:id/upvote", to: "comments#upvote", as: :upvote
devise_scope :user do
get "users/:id", :to => "users#show", as: :user_profile
end
end
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20130822175104) do
create_table "authentications", force: true do |t|
t.string "provider"
t.string "uid"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "token"
t.string "secret"
t.string "name"
t.string "link"
end
create_table "comments", force: true do |t|
t.integer "user_id"
t.integer "event_id"
t.text "post"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "upvotes"
end
add_index "comments", ["event_id"], name: "index_comments_on_event_id"
add_index "comments", ["user_id"], name: "index_comments_on_user_id"
create_table "companies", force: true do |t|
t.string "name"
t.string "description"
t.string "website"
t.string "logo"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "events", force: true do |t|
t.string "title"
t.string "location"
t.text "description"
t.datetime "date"
t.datetime "end_date"
t.integer "company_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "confirmation_token"
t.string "unlock_token"
t.string "authentication_token"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
end
add_index "users", ["authentication_token"], name: "index_users_on_authentication_token", unique: true
add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
add_index "users", ["unlock_token"], name: "index_users_on_unlock_token", unique: true
end
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Company.create name: "Goldman Sachs", description: "A full-service global investment banking and securities firm.", website: "http://www.goldmansachs.com/", logo: "http://ja-utah.org/wp-content/uploads/2012/09/goldman-sachs.gif"
Company.create name: "Morgan Stanley", description: "Global financial services firm and a market leader in securities, asset management and credit services.", website: "http://www.morganstanley.com/", logo: "http://news.doddleme.com/wp-content/uploads/2012/12/morgan-stanley.png"
Company.create name: "Deutsche Bank", description: "One of the world's leading financial service providers.", website: "https://www.db.com/us/", logo: "http://www.logostage.com/logos/deutsche_bank.png"
Company.create name: "Citigroup", description: "Our Investment Banking unit provides comprehensive financial advisory and capital raising services to top corporations, financial institutions and governments worldwide.", website: "http://www.citigroup.com/citi/", logo: "http://www.logodesignlove.com/images/classic/citi-logo.jpg"
Company.create name: "Bank of America Merrill Lynch", description: "Bank of America Merrill Lynch offers global commercial and corporate banking and markets solutions.", website: "http://corp.bankofamerica.com/", logo: "http://www.ivarjacobson.com/uploadedImages/Bank%20of%20America%20logo(1).jpg"
Company.create name: "Deloitte", description: "Consulting, audit, risk management, and tax services", website: "http://www.deloitte.com/", logo: "http://www.actuaries.org.uk/sites/all/files/event_sponsors/Deloitte_0.JPG"
Company.create name: "Boston Consulting Group", description: "The world's leading advisor on business strategy", website: "http://www.bcg.com/‎", logo: "http://www.arenaflowers.com/files/Image/arenaflowers.com/news/bcg-logo.gif"
Company.create name: "McKinsey & Company", description: "Trusted advisor and counselor to many of the world's most influential businesses and institutions.", website: "http://www.mckinsey.com/", logo: "http://cdn.business2community.com/wp-content/uploads/2012/09/McKinsey-logo1.gif"
Company.create name: "Accenture", description: "Accenture is a management consulting, technology services and outsourcing company helping clients become high-performance businesses and governments.", website: "http://www.accenture.com/‎", logo: "http://i1-news.softpedia-static.com/images/news2/40-of-Nokia-s-Outsourced-Symbian-Developers-quot-Laid-Off-Voluntarily-quot-by-Accenture-2.jpg"
Event.create title: "Goldman Sachs Recruiting Kick-off", location: "Nasher Museum of Art", description: "GS will discuss the application process, what makes an ideal candidate, and how to prepare for interviews!", date: DateTime.new(2013,9,3,18.5), end_date: DateTime.new(2013,9,3,20.5), company_id: 1
Event.create title: "Morgan Stanley: Internships 101", location: "The Washington Duke Inn", description: "Morgan Stanley to provide light snacks & refreshments for their info session.", date: DateTime.new(2013,9,4,16.25), end_date: DateTime.new(2013,9,4,18.25), company_id: 2
Event.create title: "Citi @ Duke Kickoff", location: "Fuqua School of Business", description: "Citi to discuss why they love Duke students so much!", date: DateTime.new(2013,9,10,17), end_date: DateTime.new(2013,9,10,19.5), company_id: 4
Event.create title: "BAML Info Session", location: "Washington Duke Inn & Golf Club", description: "Panel of BAML managers fielding any & all recruiting-related questions.", date: DateTime.new(2013,9,15,16.75), end_date: DateTime.new(2013,9,15,18.5), company_id: 5
Event.create title: "Opportunities with Deloitte", location: "WaDuke, Room 105", description: "Deloitte presents the global positions they're looking to fill at Duke.", date: DateTime.new(2013,9,16,17.5), end_date: DateTime.new(2013,9,16,19.5), company_id: 6
Event.create title: "BCG + You.", location: "Fuqua School of Business, McClendon Auditorium", description: "What makes BCG a special place to work, grow, and learn?", date: DateTime.new(2013,9,17,17.5), end_date: DateTime.new(2013,9,17,19), company_id: 7
Event.create title: "DB - Global Intern & Full-time Recruiting Seminar", location: "Duke Lemur Center", description: "As DB continues to grow in the US, we are looking to add at least 50 Duke students to our incoming analyst class. Come learn how to join!", date: DateTime.new(2013,9,10,17), end_date: DateTime.new(2013,9,10,19.5), company_id: 3
Event.create title: "Consulting Kickoff Mixer", location: "The Great Hall", description: "What sets McKinsey apart? Come find out.", date: DateTime.new(2013,9,1,17), end_date: DateTime.new(2013,9,1,19), company_id: 8
Event.create title: "Accelerate with Accenture", location: "Bryan Center (Mezzanine)", description: "Why we dropped Tiger Woods, and what this means for you.", date: DateTime.new(2013,9,20,18), end_date: DateTime.new(2013,9,20,20), company_id: 9
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
devise :omniauthable, :omniauth_providers => [:google_oauth2, :facebook, :linkedin]
has_many :events
has_many :comments
has_many :authentications, dependent: :destroy
has_many :companies, through: :events
>def self.find_for_ouath(provider, access_token, resource=nil)
user, email, name, uid, auth_attr = nil, nil, nil, {}
case provider
when "Facebook"
uid = access_token['uid']
email = access_token['extra']['raw_info']['email']
name = access_token['info']['name']
auth_attr = { :uid => uid, :token => access_token['credentials']['token'], :secret => nil, :name => name, :link => access_token['extra']['raw_info']['link'] }
when 'LinkedIn'
uid = access_token['uid']
email = access_token['info']['email']
name = access_token['info']['name']
auth_attr = { :uid => uid, :token => access_token['credentials']['token'], :secret => nil, :name => name, :link => access_token['info']['urls']['public_profile'] }
when 'Google'
uid = access_token['uid']
email = access_token['info']['email']
name = access_token['info']['name']
auth_attr = { :uid => uid, :token => access_token['credentials']['token'], :secret => nil, :name => name, :link => access_token['extra']['raw_info']['link'] }
else
raise 'Provider #{provider} not handled'
end
if resource.nil? #resource checks for current_user in omniauth controller
if email
user = User.find_for_oauth_by_email(email, name, resource)
elsif uid && name
user = User.find_for_oauth_by_uid(uid, resource)
if user.nil?
user = find_for_oauth_by_name(name, resource)
end
end
else
user = resource
end
auth = user.authentications.find_by_provider(provider)
if auth.nil?
auth = user.authentications.build(:provider => provider)
user.authentications << auth
end
auth.update_attributes auth_attr
return user
end
def self.find_for_oauth_by_uid(uid, resource=nil)
user = nil
if auth = Authentication.find_by_uid(uid.to_s)
user = auth.user
else
user = User.new(email: email, name: name, password: Devise.friendly_token[0,20])
user.save
end
return user
end
def self.find_for_oauth_by_email(email, name, resource=nil)
if user = User.find_by_email(email)
user
else
user = User.new(email: email, name: name, password: Devise.friendly_token[0,20])
user.save
end
return user
end
def self.find_for_oauth_by_name(name, resource=nil)
if user = User.find_by_name(name)
user
else
user = User.new(:name => name, :password => Devise.friendly_token[0,20], :email => "#{UUIDTools::UUID.random_create}@host")
user.save false
end
return user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment