Git
14 files changed +490 −3
Review
Insert▾
app/controllers/google_calendar_controller.rb (+29 −0) added


  
1
class GoogleCalendarController < ApplicationController


  
2
  def connect


  
3
    state = SecureRandom.hex(16)


  
4
    session[:google_calendar_state] = state


  
5


      


  
6
    redirect_to GoogleCalendar::Client.authorize_url(redirect_uri: google_calendar_callback_url, state: state), allow_other_host: true


  
7
  end


  
8


      


  
9
  def callback


  
10
    if params[:state].blank? || params[:state] != session.delete(:google_calendar_state)


  
11
      return render json: { error: "state mismatch" }, status: :unprocessable_entity


  
12
    end


  
13
    return render json: { error: params[:error] }, status: :unprocessable_entity if params[:code].blank?


  
14


      


  
15
    tokens = GoogleCalendar::Client.exchange_code(params[:code], redirect_uri: google_calendar_callback_url)


  
16
    email = GoogleCalendar::Client.userinfo(tokens.fetch("access_token")).fetch("email")


  
17
    connection = GoogleCalendarConnection.from_tokens!(tokens, email: email)


  
18
    SyncGoogleCalendarJob.perform_later(connection.id)


  
19


      


  
20
    render plain: "Google Calendar connected for #{email}. Syncing in the background."


  
21
  end


  
22


      


  
23
  def disconnect


  
24
    connection = GoogleCalendarConnection.find(params[:id])


  
25
    connection.destroy


  
26
    CalendarEvent.where(source: "google").delete_all if GoogleCalendarConnection.none?


  
27
    head :no_content


  
28
  end


  
29
end