viabiliza/service/authService.js

40 lines
1.2 KiB
JavaScript

import axios from "axios";
import dotenv from "dotenv";
dotenv.config();
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
export function getAuthUrl() {
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
export async function getTokenFromCode(authCode) {
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,
});
const response = await axios.post(url, params);
return response.data;
}