microsoft365.rb 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class ExternalCredential::Microsoft365
  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: 'microsoft365')
  9. raise Exceptions::UnprocessableEntity, __('No Microsoft365 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. # client_tenant may be empty. Set only if key is nonexistant at all
  18. if !credentials.key? :client_tenant
  19. credentials[:client_tenant] = external_credential.credentials['client_tenant']
  20. end
  21. end
  22. raise Exceptions::UnprocessableEntity, __('No client_id param!') if credentials[:client_id].blank?
  23. raise Exceptions::UnprocessableEntity, __('No client_secret param!') if credentials[:client_secret].blank?
  24. authorize_url = generate_authorize_url(credentials)
  25. {
  26. authorize_url: authorize_url,
  27. }
  28. end
  29. def self.link_account(_request_token, params)
  30. external_credential = ExternalCredential.find_by(name: 'microsoft365')
  31. raise Exceptions::UnprocessableEntity, __('No Microsoft365 app configured!') if !external_credential
  32. raise Exceptions::UnprocessableEntity, __('No code for session found!') if !params[:code]
  33. response = authorize_tokens(external_credential.credentials, params[:code])
  34. %w[refresh_token access_token expires_in scope token_type id_token].each do |key|
  35. raise Exceptions::UnprocessableEntity, "No #{key} for authorization request found!" if response[key.to_sym].blank?
  36. end
  37. user_data = user_info(response[:id_token])
  38. raise Exceptions::UnprocessableEntity, __("The user's 'preferred_username' could not be extracted from 'id_token'.") if user_data[:preferred_username].blank?
  39. channel_options = {
  40. inbound: {
  41. adapter: 'imap',
  42. options: {
  43. auth_type: 'XOAUTH2',
  44. host: 'outlook.office365.com',
  45. ssl: 'ssl',
  46. user: user_data[:preferred_username],
  47. },
  48. },
  49. outbound: {
  50. adapter: 'smtp',
  51. options: {
  52. host: 'smtp.office365.com',
  53. port: 587,
  54. user: user_data[:preferred_username],
  55. authentication: 'xoauth2',
  56. },
  57. },
  58. auth: response.merge(
  59. provider: 'microsoft365',
  60. type: 'XOAUTH2',
  61. client_id: external_credential.credentials[:client_id],
  62. client_secret: external_credential.credentials[:client_secret],
  63. client_tenant: external_credential.credentials[:client_tenant],
  64. ),
  65. }
  66. if params[:channel_id]
  67. existing_channel = Channel.where(area: 'Microsoft365::Account').find(params[:channel_id])
  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 != 'outlook.office365.com'
  77. next if channel.options.dig(:outbound, :options, :host)&.downcase != 'smtp.office365.com'
  78. next if channel.options.dig(:outbound, :options, :user)&.downcase != user_data[:preferred_username].downcase && channel.options.dig(:outbound, :email)&.downcase != user_data[:preferred_username].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: 'Microsoft365::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 = [
  105. {
  106. realname: "#{Setting.get('product_name')} Support",
  107. email: user_data[:preferred_username],
  108. },
  109. ]
  110. email_addresses.each do |email|
  111. next if !EmailAddress.exists?(email: email[:email])
  112. raise Exceptions::UnprocessableEntity, "Duplicate email address or email alias #{email[:email]} found!"
  113. end
  114. # create channel
  115. channel = Channel.create!(
  116. area: 'Microsoft365::Account',
  117. group_id: Group.first.id,
  118. options: channel_options,
  119. active: false,
  120. created_by_id: 1,
  121. updated_by_id: 1,
  122. )
  123. email_addresses.each do |user_alias|
  124. EmailAddress.create!(
  125. channel_id: channel.id,
  126. realname: user_alias[:realname],
  127. email: user_alias[:email],
  128. active: true,
  129. created_by_id: 1,
  130. updated_by_id: 1,
  131. )
  132. end
  133. channel
  134. end
  135. def self.generate_authorize_url(credentials, scope = 'https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send offline_access openid profile email')
  136. params = {
  137. 'client_id' => credentials[:client_id],
  138. 'redirect_uri' => ExternalCredential.callback_url('microsoft365'),
  139. 'scope' => scope,
  140. 'response_type' => 'code',
  141. 'access_type' => 'offline',
  142. 'prompt' => 'consent',
  143. }
  144. tenant = credentials[:client_tenant].presence || 'common'
  145. uri = URI::HTTPS.build(
  146. host: 'login.microsoftonline.com',
  147. path: "/#{tenant}/oauth2/v2.0/authorize",
  148. query: params.to_query
  149. )
  150. uri.to_s
  151. end
  152. def self.authorize_tokens(credentials, authorization_code)
  153. uri = authorize_tokens_uri(credentials[:client_tenant])
  154. params = authorize_tokens_params(credentials, authorization_code)
  155. response = Net::HTTP.post_form(uri, params)
  156. if response.code != 200 && response.body.blank?
  157. Rails.logger.error "Request failed! (code: #{response.code})"
  158. raise "Request failed! (code: #{response.code})"
  159. end
  160. result = JSON.parse(response.body)
  161. if result['error'] && response.code != 200
  162. Rails.logger.error "Request failed! ERROR: #{result['error']} (#{result['error_description']}, params: #{params.to_json})"
  163. raise "Request failed! ERROR: #{result['error']} (#{result['error_description']})"
  164. end
  165. result[:created_at] = Time.zone.now
  166. result.symbolize_keys
  167. end
  168. def self.authorize_tokens_params(credentials, authorization_code)
  169. {
  170. client_secret: credentials[:client_secret],
  171. code: authorization_code,
  172. grant_type: 'authorization_code',
  173. client_id: credentials[:client_id],
  174. redirect_uri: ExternalCredential.callback_url('microsoft365'),
  175. }
  176. end
  177. def self.authorize_tokens_uri(tenant)
  178. URI::HTTPS.build(
  179. host: 'login.microsoftonline.com',
  180. path: "/#{tenant.presence || 'common'}/oauth2/v2.0/token",
  181. )
  182. end
  183. def self.refresh_token(token)
  184. return token if token[:created_at] >= 50.minutes.ago
  185. params = refresh_token_params(token)
  186. uri = refresh_token_uri(token)
  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(result.symbolize_keys).merge(
  198. created_at: Time.zone.now,
  199. )
  200. end
  201. def self.refresh_token_params(credentials)
  202. {
  203. client_id: credentials[:client_id],
  204. client_secret: credentials[:client_secret],
  205. refresh_token: credentials[:refresh_token],
  206. grant_type: 'refresh_token',
  207. }
  208. end
  209. def self.refresh_token_uri(credentials)
  210. tenant = credentials[:client_tenant].presence || 'common'
  211. URI::HTTPS.build(
  212. host: 'login.microsoftonline.com',
  213. path: "/#{tenant}/oauth2/v2.0/token",
  214. )
  215. end
  216. def self.user_info(id_token)
  217. split = id_token.split('.')[1]
  218. return if split.blank?
  219. JSON.parse(Base64.decode64(split)).symbolize_keys
  220. end
  221. end