create graph api client to handle requests
This commit is contained in:
83
lib/microsoft_graph.rb
Normal file
83
lib/microsoft_graph.rb
Normal file
@@ -0,0 +1,83 @@
|
||||
require 'httparty'
|
||||
|
||||
class MicrosoftGraph
|
||||
BASE_URL = 'https://graph.microsoft.com/v1.0'.freeze
|
||||
BETA_BASE_URL = 'https://graph.microsoft.com/beta'.freeze
|
||||
# Documentation says that "common" can be used (instead of tenantID) to refresh access token
|
||||
REFRESH_TOKEN_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'.freeze
|
||||
|
||||
def initialize(current_user, client_id, client_secret, scopes)
|
||||
@current_user = current_user
|
||||
@uid = current_user.microsoft_user_id
|
||||
@token = current_user.microsoft_access_token
|
||||
@refresh_token = current_user.microsoft_refresh_token
|
||||
@expires_at = current_user.microsoft_token_expires_at
|
||||
|
||||
@client_id = client_id
|
||||
@client_secret = client_secret
|
||||
@scopes = scopes
|
||||
end
|
||||
|
||||
def request(resource)
|
||||
return false unless @token
|
||||
|
||||
response = HTTParty.get(
|
||||
"#{BASE_URL}/#{resource}",
|
||||
headers: {
|
||||
Authorization: "Bearer #{@token}"
|
||||
}
|
||||
)
|
||||
|
||||
if response.code != 200
|
||||
p '[Microsoft Graph API Error]'
|
||||
p response.inspect
|
||||
false
|
||||
else
|
||||
JSON.parse(response.body)
|
||||
end
|
||||
end
|
||||
|
||||
def create_teams_meeting(start_date_time, end_date_time, subject)
|
||||
# check if token expired and obtain new access_token using refresh token
|
||||
|
||||
response = HTTParty.post(
|
||||
"#{BETA_BASE_URL}/me/onlineMeetings",
|
||||
body: {
|
||||
startDateTime: start_date_time,
|
||||
endDateTime: end_date_time,
|
||||
subject: subject,
|
||||
participants: {
|
||||
organizer: {
|
||||
identity: {
|
||||
user: {
|
||||
id: @uid
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
headers: {
|
||||
Authorization: "Bearer #{@token}"
|
||||
}
|
||||
)
|
||||
|
||||
if response.code != 201
|
||||
p '[Microsoft Graph API Error] Failed to create online meeting'
|
||||
p response.inspect
|
||||
else
|
||||
JSON.parse(response.body)
|
||||
end
|
||||
end
|
||||
|
||||
def refresh_token
|
||||
response = HTTParty.post(REFRESH_TOKEN_URL,
|
||||
body: {
|
||||
client_id: @client_id,
|
||||
client_secret: @client_secret,
|
||||
refresh_token: @refresh_token,
|
||||
grant_type: 'refresh_token',
|
||||
scope: @scopes
|
||||
})
|
||||
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user