microsoft365.rb 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. existing_channel.update!(
  71. options: channel_options,
  72. )
  73. existing_channel.refresh_xoauth2!
  74. return existing_channel
  75. end
  76. migrate_channel = nil
  77. Channel.where(area: 'Email::Account').find_each do |channel|
  78. next if channel.options.dig(:inbound, :options, :host)&.downcase != 'outlook.office365.com'
  79. next if channel.options.dig(:outbound, :options, :host)&.downcase != 'smtp.office365.com'
  80. 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
  81. migrate_channel = channel
  82. break
  83. end
  84. if migrate_channel
  85. channel_options[:inbound][:options][:folder] = migrate_channel.options[:inbound][:options][:folder]
  86. channel_options[:inbound][:options][:keep_on_server] = migrate_channel.options[:inbound][:options][:keep_on_server]
  87. backup = {
  88. attributes: {
  89. area: migrate_channel.area,
  90. options: migrate_channel.options,
  91. last_log_in: migrate_channel.last_log_in,
  92. last_log_out: migrate_channel.last_log_out,
  93. status_in: migrate_channel.status_in,
  94. status_out: migrate_channel.status_out,
  95. },
  96. migrated_at: Time.zone.now,
  97. }
  98. migrate_channel.update(
  99. area: 'Microsoft365::Account',
  100. options: channel_options.merge(backup_imap_classic: backup),
  101. last_log_in: nil,
  102. last_log_out: nil,
  103. )
  104. return migrate_channel
  105. end
  106. email_addresses = [
  107. {
  108. realname: "#{Setting.get('product_name')} Support",
  109. email: user_data[:preferred_username],
  110. },
  111. ]
  112. email_addresses.each do |email|
  113. next if !EmailAddress.exists?(email: email[:email])
  114. raise Exceptions::UnprocessableEntity, "Duplicate email address or email alias #{email[:email]} found!"
  115. end
  116. # create channel
  117. channel = Channel.create!(
  118. area: 'Microsoft365::Account',
  119. group_id: Group.first.id,
  120. options: channel_options,
  121. active: false,
  122. created_by_id: 1,
  123. updated_by_id: 1,
  124. )
  125. email_addresses.each do |user_alias|
  126. EmailAddress.create!(
  127. channel_id: channel.id,
  128. realname: user_alias[:realname],
  129. email: user_alias[:email],
  130. active: true,
  131. created_by_id: 1,
  132. updated_by_id: 1,
  133. )
  134. end
  135. channel
  136. end
  137. 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')
  138. params = {
  139. 'client_id' => credentials[:client_id],
  140. 'redirect_uri' => ExternalCredential.callback_url('microsoft365'),
  141. 'scope' => scope,
  142. 'response_type' => 'code',
  143. 'access_type' => 'offline',
  144. 'prompt' => credentials[:prompt] || 'login',
  145. }
  146. tenant = credentials[:client_tenant].presence || 'common'
  147. uri = URI::HTTPS.build(
  148. host: 'login.microsoftonline.com',
  149. path: "/#{tenant}/oauth2/v2.0/authorize",
  150. query: params.to_query
  151. )
  152. uri.to_s
  153. end
  154. def self.authorize_tokens(credentials, authorization_code)
  155. uri = authorize_tokens_uri(credentials[:client_tenant])
  156. params = authorize_tokens_params(credentials, authorization_code)
  157. response = Net::HTTP.post_form(uri, params)
  158. if response.code != 200 && response.body.blank?
  159. Rails.logger.error "Request failed! (code: #{response.code})"
  160. raise "Request failed! (code: #{response.code})"
  161. end
  162. result = JSON.parse(response.body)
  163. if result['error'] && response.code != 200
  164. Rails.logger.error "Request failed! ERROR: #{result['error']} (#{result['error_description']}, params: #{params.to_json})"
  165. raise "Request failed! ERROR: #{result['error']} (#{result['error_description']})"
  166. end
  167. result[:created_at] = Time.zone.now
  168. result.symbolize_keys
  169. end
  170. def self.authorize_tokens_params(credentials, authorization_code)
  171. {
  172. client_secret: credentials[:client_secret],
  173. code: authorization_code,
  174. grant_type: 'authorization_code',
  175. client_id: credentials[:client_id],
  176. redirect_uri: ExternalCredential.callback_url('microsoft365'),
  177. }
  178. end
  179. def self.authorize_tokens_uri(tenant)
  180. URI::HTTPS.build(
  181. host: 'login.microsoftonline.com',
  182. path: "/#{tenant.presence || 'common'}/oauth2/v2.0/token",
  183. )
  184. end
  185. def self.refresh_token(token)
  186. return token if token[:created_at] >= 50.minutes.ago
  187. params = refresh_token_params(token)
  188. uri = refresh_token_uri(token)
  189. response = Net::HTTP.post_form(uri, params)
  190. if response.code != 200 && response.body.blank?
  191. Rails.logger.error "Request failed! (code: #{response.code})"
  192. raise "Request failed! (code: #{response.code})"
  193. end
  194. result = JSON.parse(response.body)
  195. if result['error'] && response.code != 200
  196. Rails.logger.error "Request failed! ERROR: #{result['error']} (#{result['error_description']}, params: #{params.to_json})"
  197. raise "Request failed! ERROR: #{result['error']} (#{result['error_description']})"
  198. end
  199. token.merge(result.symbolize_keys).merge(
  200. created_at: Time.zone.now,
  201. )
  202. end
  203. def self.refresh_token_params(credentials)
  204. {
  205. client_id: credentials[:client_id],
  206. client_secret: credentials[:client_secret],
  207. refresh_token: credentials[:refresh_token],
  208. grant_type: 'refresh_token',
  209. }
  210. end
  211. def self.refresh_token_uri(credentials)
  212. tenant = credentials[:client_tenant].presence || 'common'
  213. URI::HTTPS.build(
  214. host: 'login.microsoftonline.com',
  215. path: "/#{tenant}/oauth2/v2.0/token",
  216. )
  217. end
  218. def self.user_info(id_token)
  219. split = id_token.split('.')[1]
  220. return if split.blank?
  221. JSON.parse(Base64.decode64(split)).symbolize_keys
  222. end
  223. end