Commit fb5bf120 by tady

refresh oauth token

parent a986f463
...@@ -65,6 +65,8 @@ group :development do ...@@ -65,6 +65,8 @@ group :development do
gem 'thin' gem 'thin'
# gem 'capistrano', '~> 3.0.1' # gem 'capistrano', '~> 3.0.1'
gem 'pry-rails'
end end
group :production do group :production do
...@@ -86,3 +88,5 @@ gem 'action-gmailer', github: 'popgiro/action-gmailer' ...@@ -86,3 +88,5 @@ gem 'action-gmailer', github: 'popgiro/action-gmailer'
# compose html mail # compose html mail
gem 'nokogiri' gem 'nokogiri'
gem 'premailer' gem 'premailer'
gem 'faraday'
...@@ -92,6 +92,7 @@ GEM ...@@ -92,6 +92,7 @@ GEM
mail (2.5.4) mail (2.5.4)
mime-types (~> 1.16) mime-types (~> 1.16)
treetop (~> 1.4.8) treetop (~> 1.4.8)
method_source (0.8.2)
mime-types (1.25.1) mime-types (1.25.1)
mini_portile (0.5.2) mini_portile (0.5.2)
minitest (4.7.5) minitest (4.7.5)
...@@ -121,6 +122,12 @@ GEM ...@@ -121,6 +122,12 @@ GEM
premailer (1.7.9) premailer (1.7.9)
css_parser (>= 1.1.9) css_parser (>= 1.1.9)
htmlentities (>= 4.0.0) htmlentities (>= 4.0.0)
pry (0.9.12.3)
coderay (~> 1.0)
method_source (~> 0.8)
slop (~> 3.4)
pry-rails (0.3.2)
pry (>= 0.9.10)
rack (1.5.2) rack (1.5.2)
rack-mini-profiler (0.1.31) rack-mini-profiler (0.1.31)
rack (>= 1.1.3) rack (>= 1.1.3)
...@@ -155,6 +162,7 @@ GEM ...@@ -155,6 +162,7 @@ GEM
sdoc (0.3.20) sdoc (0.3.20)
json (>= 1.1.3) json (>= 1.1.3)
rdoc (~> 3.10) rdoc (~> 3.10)
slop (3.4.7)
sprockets (2.10.1) sprockets (2.10.1)
hike (~> 1.2) hike (~> 1.2)
multi_json (~> 1.0) multi_json (~> 1.0)
...@@ -194,12 +202,14 @@ DEPENDENCIES ...@@ -194,12 +202,14 @@ DEPENDENCIES
coderay coderay
coffee-rails (~> 4.0.0) coffee-rails (~> 4.0.0)
devise devise
faraday
jbuilder (~> 1.2) jbuilder (~> 1.2)
mail mail
nokogiri nokogiri
omniauth-google-oauth2 omniauth-google-oauth2
pg pg
premailer premailer
pry-rails
rack-mini-profiler rack-mini-profiler
rails (~> 4.0.2) rails (~> 4.0.2)
rails_12factor rails_12factor
......
...@@ -358,10 +358,6 @@ __HTML__ ...@@ -358,10 +358,6 @@ __HTML__
html_body += <<'__HTML__' html_body += <<'__HTML__'
<div style="font-weight: bold; font-size: 18px; line-height: 24px; color: #D03C0F;">
Quick Two Columns to Rows Demo
</div>
<br> <br>
</td> </td>
......
...@@ -56,8 +56,13 @@ class PostsController < ApplicationController ...@@ -56,8 +56,13 @@ class PostsController < ApplicationController
def mail def mail
@post = set_post @post = set_post
# refresh google oauth token if expired
current_user.google_oauth_token_refresh! if current_user.google_oauth_token_expired?
compose_mail(@post, current_user).deliver compose_mail(@post, current_user).deliver
redirect_to root_path(id: @post.id) redirect_to root_path(id: @post.id)
rescue ActionGmailer::DeliveryError
redirect_to root_path(id: @post.id), flash: { notice: 'Gmail authentication expired.' }
end end
# GET /posts/1/edit # GET /posts/1/edit
......
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2 def google_oauth2
# You need to implement the method below in your model (e.g. app/models/user.rb) # You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user) @user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)
if @user.persisted? if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google" flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
sign_in_and_redirect @user, :event => :authentication sign_in_and_redirect @user, :event => :authentication
else else
session["devise.google_data"] = request.env["omniauth.auth"] session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url redirect_to new_user_registration_url
end end
end end
end end
require 'faraday'
class User < ActiveRecord::Base class User < ActiveRecord::Base
# Include default devise modules. Others available are: # Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable # :confirmable, :lockable, :timeoutable and :omniauthable
...@@ -10,7 +12,7 @@ class User < ActiveRecord::Base ...@@ -10,7 +12,7 @@ class User < ActiveRecord::Base
# Device # Device
def self.find_for_google_oauth2(access_token, signed_in_resource=nil) def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info data = access_token.info
user = User.where(:email => data["email"]).first user = User.where(email: data["email"]).first
unless user unless user
user = User.create(name: data["name"], user = User.create(name: data["name"],
...@@ -19,7 +21,39 @@ class User < ActiveRecord::Base ...@@ -19,7 +21,39 @@ class User < ActiveRecord::Base
password: Devise.friendly_token[0,20] password: Devise.friendly_token[0,20]
) )
end end
user.update_attribute(:google_auth_token, access_token.credentials['token'])
user.update_attributes(
google_auth_token: access_token.credentials['token'],
google_refresh_token: access_token.credentials['refresh_token'],
google_token_expires_at: Time.at(access_token.credentials['expires_at'])
)
user user
end end
# check if google oauth token is expired
def google_oauth_token_expired?
self.google_token_expires_at < Time.now
end
# refresh google oauth token
def google_oauth_token_refresh!
conn = Faraday.new(url: 'https://accounts.google.com') do |builder|
builder.request :url_encoded
builder.adapter :net_http
end
response = conn.post '/o/oauth2/token', {
client_id: ENV["GOOGLE_KEY"],
client_secret: ENV["GOOGLE_SECRET"],
refresh_token: self.google_refresh_token,
grant_type: "refresh_token"
}
res_json = JSON.parse(response.body)
self.update_attributes(
google_auth_token: res_json['access_token'],
google_token_expires_at: Time.now + res_json['expires_in'].seconds
)
end
end end
...@@ -3,7 +3,8 @@ Rails.application.config.middleware.use OmniAuth::Builder do ...@@ -3,7 +3,8 @@ Rails.application.config.middleware.use OmniAuth::Builder do
{ {
:name => "google_oauth2", :name => "google_oauth2",
:scope => "https://mail.google.com/, userinfo.email, userinfo.profile", :scope => "https://mail.google.com/, userinfo.email, userinfo.profile",
:prompt => "select_account", access_type: 'offline',
:prompt => "select_account consent",
:image_aspect_ratio => "square", :image_aspect_ratio => "square",
:image_size => 50 :image_size => 50
} }
......
class AddRefreshTokenToUser < ActiveRecord::Migration
def change
add_column :users, :google_refresh_token, :string
add_column :users, :google_token_expires_at, :datetime
end
end
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20131226161253) do ActiveRecord::Schema.define(version: 20131228110818) do
create_table "post_tags", force: true do |t| create_table "post_tags", force: true do |t|
t.integer "post_id", null: false t.integer "post_id", null: false
...@@ -45,17 +45,19 @@ ActiveRecord::Schema.define(version: 20131226161253) do ...@@ -45,17 +45,19 @@ ActiveRecord::Schema.define(version: 20131226161253) do
t.string "image_url" t.string "image_url"
t.datetime "created_at" t.datetime "created_at"
t.datetime "updated_at" t.datetime "updated_at"
t.string "email", default: "", null: false t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false t.string "encrypted_password", default: "", null: false
t.string "reset_password_token" t.string "reset_password_token"
t.datetime "reset_password_sent_at" t.datetime "reset_password_sent_at"
t.datetime "remember_created_at" t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at" t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at" t.datetime "last_sign_in_at"
t.string "current_sign_in_ip" t.string "current_sign_in_ip"
t.string "last_sign_in_ip" t.string "last_sign_in_ip"
t.string "google_auth_token" t.string "google_auth_token"
t.string "google_refresh_token"
t.datetime "google_token_expires_at"
end end
add_index "users", ["email"], name: "index_users_on_email", unique: true add_index "users", ["email"], name: "index_users_on_email", unique: true
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment