google.rb 9.4 KB

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