• Stars
    star
    494
  • Rank 85,677 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 7 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Sign in (or up) with Google for Rails applications

Google Sign-In for Rails

This gem allows you to add Google sign-in to your Rails app. You can let users sign up for and sign in to your service with their Google accounts.

Installation

Add google_sign_in to your Rails app’s Gemfile and run bundle install:

gem 'google_sign_in'

Google Sign-In for Rails requires Rails 5.2 or newer.

Configuration

First, set up an OAuth 2.0 Client ID in the Google API Console:

  1. Go to the API Console.

  2. In the projects menu at the top of the page, ensure the correct project is selected or create a new one.

  3. In the left-side navigation menu, choose APIs & Services → Credentials.

  4. Click the button labeled “Create credentials.” In the menu that appears, choose to create an OAuth client ID.

  5. When prompted to select an application type, select Web application.

  6. Enter your application’s name.

  7. This gem adds a single OAuth callback to your app at /google_sign_in/callback. Under Authorized redirect URIs, add that callback for your application’s domain: for example, https://example.com/google_sign_in/callback.

    To use Google sign-in in development, you’ll need to add another redirect URI for your local environment, like http://localhost:3000/google_sign_in/callback. For security reasons, we recommend using a separate client ID for local development. Repeat these instructions to set up a new client ID for development.

  8. Click the button labeled “Create.” You’ll be presented with a client ID and client secret. Save these.

With your client ID set up, configure your Rails application to use it. Run bin/rails credentials:edit to edit your app’s encrypted credentials and add the following:

google_sign_in:
  client_id: [Your client ID here]
  client_secret: [Your client secret here]

You’re all set to use Google sign-in now. The gem automatically uses the client ID and client secret in your credentials.

Alternatively, you can provide the client ID and client secret using ENV variables. Add a new initializer that sets config.google_sign_in.client_id and config.google_sign_in.client_secret:

# config/initializers/google_sign_in.rb
Rails.application.configure do
  config.google_sign_in.client_id     = ENV['google_sign_in_client_id']
  config.google_sign_in.client_secret = ENV['google_sign_in_client_secret']
end

⚠️ Important: Take care to protect your client secret from disclosure to third parties.

  1. (Optional) The callback route can be configured using:
# config/initializers/google_sign_in.rb
Rails.application.configure do
  config.google_sign_in.root = "my_own/google_sign_in_route"
end

Which would make the callback /my_own/google_sign_in_route/callback.

Usage

This gem provides a google_sign_in_button helper. It generates a button which initiates Google sign-in:

<%= google_sign_in_button 'Sign in with my Google account', proceed_to: create_login_url %>

<%= google_sign_in_button image_tag('google_logo.png', alt: 'Google'), proceed_to: create_login_url %>

<%= google_sign_in_button proceed_to: create_login_url do %>
  Sign in with my <%= image_tag('google_logo.png', alt: 'Google') %> account
<% end %>

The proceed_to argument is required. After authenticating with Google, the gem redirects to proceed_to, providing a Google ID token in flash[:google_sign_in][:id_token] or an OAuth authorizaton code grant error in flash[:google_sign_in][:error]. Your application decides what to do with it:

# config/routes.rb
Rails.application.routes.draw do
  # ...
  get 'login', to: 'logins#new'
  get 'login/create', to: 'logins#create', as: :create_login
end
# app/controllers/logins_controller.rb
class LoginsController < ApplicationController
  def new
  end

  def create
    if user = authenticate_with_google
      cookies.signed[:user_id] = user.id
      redirect_to user
    else
      redirect_to new_session_url, alert: 'authentication_failed'
    end
  end

  private
    def authenticate_with_google
      if id_token = flash[:google_sign_in][:id_token]
        User.find_by google_id: GoogleSignIn::Identity.new(id_token).user_id
      elsif error = flash[:google_sign_in][:error]
        logger.error "Google authentication error: #{error}"
        nil
      end
    end
end

(The above example assumes the user has already signed up for your service and that you’re storing their Google user ID in the User#google_id attribute.)

For security reasons, the proceed_to URL you provide to google_sign_in_button is required to reside on the same origin as your application. This means it must have the same protocol, host, and port as the page where google_sign_in_button is used. We enforce this before redirecting to the proceed_to URL to guard against open redirects.

GoogleSignIn::Identity

The GoogleSignIn::Identity class decodes and verifies the integrity of a Google ID token. It exposes the profile information contained in the token via the following instance methods:

  • name

  • email_address

  • user_id: A string that uniquely identifies a single Google user. Use this, not email_address, to associate a Google user with an application user. A Google user’s email address may change, but their user_id will remain constant.

  • email_verified?

  • avatar_url

  • locale

  • hosted_domain: The user’s hosted G Suite domain, provided only if they belong to a G Suite.

  • given_name: The user's given name.

  • family_name: The user's last name.

Security

For information on our security response procedure, see SECURITY.md.

Maintenance

Short of patching critical security issues, this gem is now considered done, and will not see any further feature development or minor bug fixes. Feel free to fork this work under the MIT license and continue the feature development under a different name.

License

Google Sign-In for Rails is released under the MIT License.

Google is a registered trademark of Google LLC. This project is not operated by or in any way affiliated with Google LLC.

More Repositories

1

trix

A rich text editor for everyday writing
JavaScript
17,847
star
2

kamal

Deploy web apps anywhere.
Ruby
8,744
star
3

handbook

Basecamp Employee Handbook
6,165
star
4

pow

Zero-configuration Rack server for Mac OS X
CoffeeScript
3,423
star
5

policies

37signals policies, terms, and legal. Share them; reuse them; contribute to them.
1,863
star
6

local_time

Rails engine for cache-friendly, client-side local time
CoffeeScript
1,791
star
7

marginalia

Attach comments to ActiveRecord's SQL queries
Ruby
1,676
star
8

mail_view

Visual email testing
Ruby
1,341
star
9

xip-pdns

PowerDNS pipe backend adapter powering xip.io
Shell
1,159
star
10

geared_pagination

Paginate Active Record sets at variable speeds
Ruby
758
star
11

wysihat

A WYSIWYG JavaScript framework
JavaScript
681
star
12

bcx-api

API documentation and wrappers for Basecamp 2
672
star
13

name_of_person

Presenting names of people in full, familiar, abbreviated, and initialized forms (but without titulation etc)
Ruby
647
star
14

console1984

The Rails console you love, 1984 style
Ruby
548
star
15

bc3-api

API documentation for Basecamp 4
472
star
16

intermission

intermission helps you perform zero down time application maintenance
Lua
364
star
17

snapback_cache

A client side page cache for jquery.
JavaScript
316
star
18

audits1984

Auditing tool for Rails console sessions
Ruby
309
star
19

full_request_logger

Make full request logs accessible via web UI
Ruby
305
star
20

mysql_role_swap

(Nearly) Zero interruption mysql maintenance script.
Ruby
282
star
21

mission_control-jobs

Dashboard and Active Job extensions to operate and troubleshoot background jobs
Ruby
270
star
22

concerning

Bite-sized separation of concerns
Ruby
201
star
23

api

API integration and more for Basecamp products (Basecamp, Highrise, Campfire, Backpack)
192
star
24

easymon

Easy Monitoring
Ruby
191
star
25

trashed

Tell StatsD about request time, GC, objects and more. Latest Rails 4 and Ruby 2.1 support, and ancient Rails 2 and Ruby 1.8 support.
Ruby
189
star
26

highrise-api

Official API documentation for Highrise
130
star
27

fast_remote_cache

A faster version of Capistrano's remote_cache deployment strategy
Ruby
125
star
28

mass_encryption

Ruby
104
star
29

platform_agent

Parse user agent to deduce the platform
Ruby
103
star
30

cached_externals

Symlink to external dependencies, rather than bloating your repositories with them
Ruby
100
star
31

campfire-api

Official API documentation for Campfire
97
star
32

basecamp-classic-api

Official API documentation for Basecamp Classic
87
star
33

lufo

Tracks the most recent options chosen on a `<select>` element and displays them at the top of the list
JavaScript
87
star
34

powprox

Pow .dev sites, meet SSL and HTTP/2
Shell
83
star
35

libmemcached_store

ActiveSupport::Cache wrapper for libmemcached
Ruby
81
star
36

action_profiler

Profile Rails requests on a live app
Ruby
75
star
37

bc3-integrations

Ruby
73
star
38

project_search

Rails plugin that adds a script/find command for searching your project
Ruby
71
star
39

activestorage-office-previewer

Active Storage previewer for Microsoft Office files based on LibreOffice
Ruby
67
star
40

dumpsterfire-2020

Code that runs the dumpster
HTML
47
star
41

turbo-8-morphing-demo

Ruby
43
star
42

cognition

Match text; run commands. Works great for building a chatbot!
Ruby
37
star
43

snapshot

A rails plugin that provides tasks for creating and restoring snapshots of development data.
Ruby
34
star
44

backpack-api

Official API documentation for Backpack
Ruby
20
star
45

ruby-dev

Old Rubies on new Macs
15
star
46

orc

Orc(hestrator) - A really bad pow.cx clone for linux
Shell
10
star
47

cleversafe

Ruby
7
star
48

memcached_bench

Ruby
6
star
49

duo-api

Ruby Gem for communicating with the Duo Api
Ruby
6
star
50

accessibility

Guidelines and tools we use at 37signals to make sure our apps are accessible
5
star
51

Xamarin.iOS.OnePasswordExtension

1Password bindings for Xamarin.iOS
C#
5
star
52

mail

Ruby
4
star
53

composed_of_ipaddr

Compact IPv4 attributes for Active Record. Presents an unsigned int (4 bytes) as an IPAddr.
Ruby
4
star
54

house-style

37signals house style
Ruby
3
star
55

deep_hash_transform

Re-key a nested Hash to all-Symbol or -String keys. Rails 4+ backport.
Ruby
3
star
56

github-issues

Github Issue query CLI
Go
2
star
57

homebrew-dev

Old software to build old stuff on new Macs
Ruby
1
star
58

nsone

A stupid simple API client for NS1
Ruby
1
star