google.rb 9.4 KB

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