google.rb 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. class ExternalCredential::Google
  2. def self.app_verify(params)
  3. request_account_to_link(params, false)
  4. params
  5. end
  6. def self.request_account_to_link(credentials = {}, app_required = true)
  7. external_credential = ExternalCredential.find_by(name: 'google')
  8. raise Exceptions::UnprocessableEntity, 'No Google app configured!' if !external_credential && app_required
  9. if external_credential
  10. if credentials[:client_id].blank?
  11. credentials[:client_id] = external_credential.credentials['client_id']
  12. end
  13. if credentials[:client_secret].blank?
  14. credentials[:client_secret] = external_credential.credentials['client_secret']
  15. end
  16. end
  17. raise Exceptions::UnprocessableEntity, 'No client_id param!' if credentials[:client_id].blank?
  18. raise Exceptions::UnprocessableEntity, 'No client_secret param!' if credentials[:client_secret].blank?
  19. authorize_url = generate_authorize_url(credentials[:client_id])
  20. {
  21. authorize_url: authorize_url,
  22. }
  23. end
  24. def self.link_account(_request_token, params)
  25. external_credential = ExternalCredential.find_by(name: 'google')
  26. raise Exceptions::UnprocessableEntity, 'No google app configured!' if !external_credential
  27. raise Exceptions::UnprocessableEntity, 'No code for session found!' if !params[:code]
  28. response = authorize_tokens(external_credential.credentials[:client_id], external_credential.credentials[:client_secret], params[:code])
  29. %w[refresh_token access_token expires_in scope token_type id_token].each do |key|
  30. raise Exceptions::UnprocessableEntity, "No #{key} for authorization request found!" if response[key.to_sym].blank?
  31. end
  32. user_data = user_info(response[:id_token])
  33. raise Exceptions::UnprocessableEntity, 'Unable to extract user email from id_token!' if user_data[:email].blank?
  34. channel_options = {
  35. inbound: {
  36. adapter: 'imap',
  37. options: {
  38. auth_type: 'XOAUTH2',
  39. host: 'imap.gmail.com',
  40. ssl: true,
  41. user: user_data[:email],
  42. },
  43. },
  44. outbound: {
  45. adapter: 'smtp',
  46. options: {
  47. host: 'smtp.gmail.com',
  48. domain: 'gmail.com',
  49. port: 465,
  50. ssl: true,
  51. user: user_data[:email],
  52. authentication: 'xoauth2',
  53. },
  54. },
  55. auth: response.merge(
  56. provider: 'google',
  57. type: 'XOAUTH2',
  58. client_id: external_credential.credentials[:client_id],
  59. client_secret: external_credential.credentials[:client_secret],
  60. ),
  61. }
  62. if params[:channel_id]
  63. existing_channel = Channel.where(area: 'Google::Account').find(params[:channel_id])
  64. existing_channel.update!(
  65. options: channel_options,
  66. )
  67. existing_channel.refresh_xoauth2!
  68. return existing_channel
  69. end
  70. migrate_channel = nil
  71. Channel.where(area: 'Email::Account').find_each do |channel|
  72. next if channel.options.dig(:inbound, :options, :user) != user_data[:email]
  73. next if channel.options.dig(:inbound, :options, :host) != 'imap.gmail.com'
  74. next if channel.options.dig(:outbound, :options, :user) != user_data[:email]
  75. next if channel.options.dig(:outbound, :options, :host) != 'smtp.gmail.com'
  76. migrate_channel = channel
  77. break
  78. end
  79. if migrate_channel
  80. channel_options[:inbound][:options][:folder] = migrate_channel.options[:inbound][:options][:folder]
  81. channel_options[:inbound][:options][:keep_on_server] = migrate_channel.options[:inbound][:options][:keep_on_server]
  82. backup = {
  83. attributes: {
  84. area: migrate_channel.area,
  85. options: migrate_channel.options,
  86. last_log_in: migrate_channel.last_log_in,
  87. last_log_out: migrate_channel.last_log_out,
  88. status_in: migrate_channel.status_in,
  89. status_out: migrate_channel.status_out,
  90. },
  91. migrated_at: Time.zone.now,
  92. }
  93. migrate_channel.update(
  94. area: 'Google::Account',
  95. options: channel_options.merge(backup_imap_classic: backup),
  96. last_log_in: nil,
  97. last_log_out: nil,
  98. )
  99. return migrate_channel
  100. end
  101. email_addresses = user_aliases(response)
  102. email_addresses.unshift({
  103. realname: "#{Setting.get('product_name')} Support",
  104. email: user_data[:email],
  105. })
  106. email_addresses.each do |email|
  107. next if !EmailAddress.exists?(email: email[:email])
  108. raise Exceptions::UnprocessableEntity, "Duplicate email address or email alias #{email[:email]} found!"
  109. end
  110. # create channel
  111. channel = Channel.create!(
  112. area: 'Google::Account',
  113. group_id: Group.first.id,
  114. options: channel_options,
  115. active: false,
  116. created_by_id: 1,
  117. updated_by_id: 1,
  118. )
  119. email_addresses.each do |user_alias|
  120. EmailAddress.create!(
  121. channel_id: channel.id,
  122. realname: user_alias[:realname],
  123. email: user_alias[:email],
  124. active: true,
  125. created_by_id: 1,
  126. updated_by_id: 1,
  127. )
  128. end
  129. channel
  130. end
  131. def self.generate_authorize_url(client_id, scope = 'openid email profile https://mail.google.com/')
  132. params = {
  133. 'client_id' => client_id,
  134. 'redirect_uri' => ExternalCredential.callback_url('google'),
  135. 'scope' => scope,
  136. 'response_type' => 'code',
  137. 'access_type' => 'offline',
  138. 'prompt' => 'consent',
  139. }
  140. uri = URI::HTTPS.build(
  141. host: 'accounts.google.com',
  142. path: '/o/oauth2/auth',
  143. query: params.to_query
  144. )
  145. uri.to_s
  146. end
  147. def self.authorize_tokens(client_id, client_secret, authorization_code)
  148. params = {
  149. 'client_secret' => client_secret,
  150. 'code' => authorization_code,
  151. 'grant_type' => 'authorization_code',
  152. 'client_id' => client_id,
  153. 'redirect_uri' => ExternalCredential.callback_url('google'),
  154. }
  155. uri = URI::HTTPS.build(
  156. host: 'accounts.google.com',
  157. path: '/o/oauth2/token',
  158. )
  159. response = Net::HTTP.post_form(uri, params)
  160. if response.code != 200 && response.body.blank?
  161. Rails.logger.error "Request failed! (code: #{response.code})"
  162. raise "Request failed! (code: #{response.code})"
  163. end
  164. result = JSON.parse(response.body)
  165. if result['error'] && response.code != 200
  166. Rails.logger.error "Request failed! ERROR: #{result['error']} (#{result['error_description']}, params: #{params.to_json})"
  167. raise "Request failed! ERROR: #{result['error']} (#{result['error_description']})"
  168. end
  169. result[:created_at] = Time.zone.now
  170. result.symbolize_keys
  171. end
  172. def self.refresh_token(token)
  173. return token if token[:created_at] >= 50.minutes.ago
  174. params = {
  175. 'client_id' => token[:client_id],
  176. 'client_secret' => token[:client_secret],
  177. 'refresh_token' => token[:refresh_token],
  178. 'grant_type' => 'refresh_token',
  179. }
  180. uri = URI::HTTPS.build(
  181. host: 'accounts.google.com',
  182. path: '/o/oauth2/token',
  183. )
  184. response = Net::HTTP.post_form(uri, params)
  185. if response.code != 200 && response.body.blank?
  186. Rails.logger.error "Request failed! (code: #{response.code})"
  187. raise "Request failed! (code: #{response.code})"
  188. end
  189. result = JSON.parse(response.body)
  190. if result['error'] && response.code != 200
  191. Rails.logger.error "Request failed! ERROR: #{result['error']} (#{result['error_description']}, params: #{params.to_json})"
  192. raise "Request failed! ERROR: #{result['error']} (#{result['error_description']})"
  193. end
  194. token.merge(
  195. created_at: Time.zone.now,
  196. access_token: result['access_token'],
  197. ).symbolize_keys
  198. end
  199. def self.user_aliases(token)
  200. uri = URI.parse('https://www.googleapis.com/gmail/v1/users/me/settings/sendAs')
  201. http = Net::HTTP.new(uri.host, uri.port)
  202. http.use_ssl = true
  203. response = http.get(uri.request_uri, { 'Authorization' => "#{token[:token_type]} #{token[:access_token]}" })
  204. if response.code != 200 && response.body.blank?
  205. Rails.logger.error "Request failed! (code: #{response.code})"
  206. raise "Request failed! (code: #{response.code})"
  207. end
  208. result = JSON.parse(response.body)
  209. if result['error'] && response.code != 200
  210. Rails.logger.error "Request failed! ERROR: #{result['error']['message']}"
  211. raise "Request failed! ERROR: #{result['error']['message']}"
  212. end
  213. aliases = []
  214. result['sendAs'].each do |row|
  215. next if row['isPrimary']
  216. next if !row['verificationStatus']
  217. next if row['verificationStatus'] != 'accepted'
  218. aliases.push({
  219. realname: row['displayName'],
  220. email: row['sendAsEmail'],
  221. })
  222. end
  223. aliases
  224. end
  225. def self.user_info(id_token)
  226. split = id_token.split('.')[1]
  227. return if split.blank?
  228. JSON.parse(Base64.decode64(split)).symbolize_keys
  229. end
  230. end