microsoft365.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # Copyright (C) 2012-2023 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 Microsoft 365 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, __("The required parameter 'client_id' is missing.") if credentials[:client_id].blank?
  23. raise Exceptions::UnprocessableEntity, __("The required parameter 'client_secret' is missing.") 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. # return to admin interface if admin Consent is in process and user clicks on "Back to app"
  31. return "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/#channels/microsoft365/error/AADSTS65004" if params[:error_description].present? && params[:error_description].include?('AADSTS65004')
  32. external_credential = ExternalCredential.find_by(name: 'microsoft365')
  33. raise Exceptions::UnprocessableEntity, __('No Microsoft 365 app configured!') if !external_credential
  34. raise Exceptions::UnprocessableEntity, __("The required parameter 'code' is missing.") if !params[:code]
  35. response = authorize_tokens(external_credential.credentials, params[:code])
  36. %w[refresh_token access_token expires_in scope token_type id_token].each do |key|
  37. raise Exceptions::UnprocessableEntity, "No #{key} for authorization request found!" if response[key.to_sym].blank?
  38. end
  39. user_data = user_info(response[:id_token])
  40. raise Exceptions::UnprocessableEntity, __("The user's 'preferred_username' could not be extracted from 'id_token'.") if user_data[:preferred_username].blank?
  41. channel_options = {
  42. inbound: {
  43. adapter: 'imap',
  44. options: {
  45. auth_type: 'XOAUTH2',
  46. host: 'outlook.office365.com',
  47. ssl: 'ssl',
  48. user: user_data[:preferred_username],
  49. },
  50. },
  51. outbound: {
  52. adapter: 'smtp',
  53. options: {
  54. host: 'smtp.office365.com',
  55. port: 587,
  56. user: user_data[:preferred_username],
  57. authentication: 'xoauth2',
  58. },
  59. },
  60. auth: response.merge(
  61. provider: 'microsoft365',
  62. type: 'XOAUTH2',
  63. client_id: external_credential.credentials[:client_id],
  64. client_secret: external_credential.credentials[:client_secret],
  65. client_tenant: external_credential.credentials[:client_tenant],
  66. ),
  67. }
  68. if params[:channel_id]
  69. existing_channel = Channel.where(area: 'Microsoft365::Account').find(params[:channel_id])
  70. # Check if current user of the channel is matching the user from the token.
  71. token_user = user_data[:preferred_username]&.downcase
  72. inbound_user = channel_user(existing_channel, :inbound)&.downcase
  73. outbound_user = channel_user(existing_channel, :outbound)&.downcase
  74. if (inbound_user.present? && inbound_user != token_user) || (outbound_user.present? && outbound_user != token_user)
  75. return "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/#channels/microsoft365/error/user_mismatch"
  76. end
  77. channel_options[:inbound][:options][:folder] = existing_channel.options[:inbound][:options][:folder]
  78. channel_options[:inbound][:options][:keep_on_server] = existing_channel.options[:inbound][:options][:keep_on_server]
  79. existing_channel.update!(
  80. options: channel_options,
  81. )
  82. existing_channel.refresh_xoauth2!
  83. return existing_channel
  84. end
  85. migrate_channel = nil
  86. Channel.where(area: 'Email::Account').find_each do |channel|
  87. next if channel.options.dig(:inbound, :options, :host)&.downcase != 'outlook.office365.com'
  88. next if channel.options.dig(:outbound, :options, :host)&.downcase != 'smtp.office365.com'
  89. 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
  90. migrate_channel = channel
  91. break
  92. end
  93. if migrate_channel
  94. channel_options[:inbound][:options][:folder] = migrate_channel.options[:inbound][:options][:folder]
  95. channel_options[:inbound][:options][:keep_on_server] = migrate_channel.options[:inbound][:options][:keep_on_server]
  96. backup = {
  97. attributes: {
  98. area: migrate_channel.area,
  99. options: migrate_channel.options,
  100. last_log_in: migrate_channel.last_log_in,
  101. last_log_out: migrate_channel.last_log_out,
  102. status_in: migrate_channel.status_in,
  103. status_out: migrate_channel.status_out,
  104. },
  105. migrated_at: Time.zone.now,
  106. }
  107. migrate_channel.update(
  108. area: 'Microsoft365::Account',
  109. options: channel_options.merge(backup_imap_classic: backup),
  110. last_log_in: nil,
  111. last_log_out: nil,
  112. )
  113. return migrate_channel
  114. end
  115. email_addresses = [
  116. {
  117. name: "#{Setting.get('product_name')} Support",
  118. email: user_data[:preferred_username],
  119. },
  120. ]
  121. email_addresses.each do |email|
  122. next if !EmailAddress.exists?(email: email[:email])
  123. raise Exceptions::UnprocessableEntity, "Duplicate email address or email alias #{email[:email]} found!"
  124. end
  125. # create channel
  126. channel = Channel.create!(
  127. area: 'Microsoft365::Account',
  128. group_id: Group.first.id,
  129. options: channel_options,
  130. active: false,
  131. created_by_id: 1,
  132. updated_by_id: 1,
  133. )
  134. email_addresses.each do |user_alias|
  135. EmailAddress.create!(
  136. channel_id: channel.id,
  137. name: user_alias[:name],
  138. email: user_alias[:email],
  139. active: true,
  140. created_by_id: 1,
  141. updated_by_id: 1,
  142. )
  143. end
  144. channel
  145. end
  146. 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')
  147. params = {
  148. 'client_id' => credentials[:client_id],
  149. 'redirect_uri' => ExternalCredential.callback_url('microsoft365'),
  150. 'scope' => scope,
  151. 'response_type' => 'code',
  152. 'access_type' => 'offline',
  153. 'prompt' => credentials[:prompt] || 'login',
  154. }
  155. tenant = credentials[:client_tenant].presence || 'common'
  156. uri = URI::HTTPS.build(
  157. host: 'login.microsoftonline.com',
  158. path: "/#{tenant}/oauth2/v2.0/authorize",
  159. query: params.to_query
  160. )
  161. uri.to_s
  162. end
  163. def self.authorize_tokens(credentials, authorization_code)
  164. uri = authorize_tokens_uri(credentials[:client_tenant])
  165. params = authorize_tokens_params(credentials, authorization_code)
  166. response = Net::HTTP.post_form(uri, params)
  167. if response.code != 200 && response.body.blank?
  168. Rails.logger.error "Request failed! (code: #{response.code})"
  169. raise "Request failed! (code: #{response.code})"
  170. end
  171. result = JSON.parse(response.body)
  172. if result['error'] && response.code != 200
  173. Rails.logger.error "Request failed! ERROR: #{result['error']} (#{result['error_description']}, params: #{params.to_json})"
  174. raise "Request failed! ERROR: #{result['error']} (#{result['error_description']})"
  175. end
  176. result[:created_at] = Time.zone.now
  177. result.symbolize_keys
  178. end
  179. def self.authorize_tokens_params(credentials, authorization_code)
  180. {
  181. client_secret: credentials[:client_secret],
  182. code: authorization_code,
  183. grant_type: 'authorization_code',
  184. client_id: credentials[:client_id],
  185. redirect_uri: ExternalCredential.callback_url('microsoft365'),
  186. }
  187. end
  188. def self.authorize_tokens_uri(tenant)
  189. URI::HTTPS.build(
  190. host: 'login.microsoftonline.com',
  191. path: "/#{tenant.presence || 'common'}/oauth2/v2.0/token",
  192. )
  193. end
  194. def self.refresh_token(token)
  195. return token if token[:created_at] >= 50.minutes.ago
  196. params = refresh_token_params(token)
  197. uri = refresh_token_uri(token)
  198. response = Net::HTTP.post_form(uri, params)
  199. if response.code != 200 && response.body.blank?
  200. Rails.logger.error "Request failed! (code: #{response.code})"
  201. raise "Request failed! (code: #{response.code})"
  202. end
  203. result = JSON.parse(response.body)
  204. if result['error'] && response.code != 200
  205. Rails.logger.error "Request failed! ERROR: #{result['error']} (#{result['error_description']}, params: #{params.to_json})"
  206. raise "Request failed! ERROR: #{result['error']} (#{result['error_description']})"
  207. end
  208. token.merge(result.symbolize_keys).merge(
  209. created_at: Time.zone.now,
  210. )
  211. end
  212. def self.refresh_token_params(credentials)
  213. {
  214. client_id: credentials[:client_id],
  215. client_secret: credentials[:client_secret],
  216. refresh_token: credentials[:refresh_token],
  217. grant_type: 'refresh_token',
  218. }
  219. end
  220. def self.refresh_token_uri(credentials)
  221. tenant = credentials[:client_tenant].presence || 'common'
  222. URI::HTTPS.build(
  223. host: 'login.microsoftonline.com',
  224. path: "/#{tenant}/oauth2/v2.0/token",
  225. )
  226. end
  227. def self.user_info(id_token)
  228. split = id_token.split('.')[1]
  229. return if split.blank?
  230. JSON.parse(Base64.decode64(split)).symbolize_keys
  231. end
  232. def self.channel_user(channel, key)
  233. channel.options.dig(key.to_sym, :options, :user)
  234. end
  235. end