2025-10-17 14:12:27 -03:00
|
|
|
const axios = require("axios");
|
|
|
|
|
require("dotenv").config();
|
2025-10-16 11:21:31 -03:00
|
|
|
|
|
|
|
|
const tenantId = process.env.OAUTH_TENANT_ID;
|
|
|
|
|
const clientId = process.env.OAUTH_CLIENT_ID;
|
|
|
|
|
const clientSecret = process.env.OAUTH_CLIENT_SECRET;
|
|
|
|
|
const redirectUri = process.env.OAUTH_REDIRECT_URI;
|
|
|
|
|
|
|
|
|
|
// Função que gera o link de login para o usuário
|
2025-10-17 14:12:27 -03:00
|
|
|
function getAuthUrl() {
|
2025-10-16 11:21:31 -03:00
|
|
|
const params = new URLSearchParams({
|
|
|
|
|
client_id: clientId,
|
|
|
|
|
response_type: "code",
|
|
|
|
|
redirect_uri: redirectUri,
|
|
|
|
|
response_mode: "query",
|
|
|
|
|
scope: "offline_access https://graph.microsoft.com/.default",
|
|
|
|
|
state: "12345",
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?${params.toString()}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Troca o "authorization code" por tokens
|
2025-10-17 14:12:27 -03:00
|
|
|
async function getTokenFromCode(authCode) {
|
2025-10-16 11:21:31 -03:00
|
|
|
const url = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
|
|
|
|
|
|
|
|
|
|
const params = new URLSearchParams({
|
|
|
|
|
client_id: clientId,
|
|
|
|
|
scope: "https://graph.microsoft.com/.default",
|
|
|
|
|
code: authCode,
|
|
|
|
|
redirect_uri: redirectUri,
|
|
|
|
|
grant_type: "authorization_code",
|
|
|
|
|
client_secret: clientSecret,
|
|
|
|
|
});
|
|
|
|
|
|
2025-10-17 14:12:27 -03:00
|
|
|
const response = await axios.post(url, params.toString(), {
|
|
|
|
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
|
|
|
});
|
2025-10-16 11:21:31 -03:00
|
|
|
return response.data;
|
|
|
|
|
}
|
2025-10-17 14:12:27 -03:00
|
|
|
|
|
|
|
|
module.exports = { getAuthUrl, getTokenFromCode };
|