login-auth-services
Version:
Authentication services for Google, GitHub, Microsoft, okta and multi-factor authentication using OTP.
57 lines (49 loc) • 2.06 kB
text/typescript
import axios from "axios";
import queryString from "query-string";
import { DatabaseService } from "../services/databaseService";
import { MicrosoftOAuthOptions } from "../helpers/interface.types";
const dbService = DatabaseService.getInstance();
export const getAuthURLMicrosoft = (options: MicrosoftOAuthOptions) => {
const params = queryString.stringify({
client_id: options.clientId,
redirect_uri: options.redirectUri,
response_type: "code",
scope: options.scope || 'openid email profile',
state: Math.random().toString(36).substring(7),
});
return `https://login.microsoftonline.com/${options.tenantId}/oauth2/v2.0/authorize?${params}`;
};
export const getTokenMicrosoft = async (code: any, options: { tenantId: any; clientId: any; clientSecret: any; redirectUri: any; }) => {
const response = await axios.post(
`https://login.microsoftonline.com/${options.tenantId}/oauth2/v2.0/token`,
queryString.stringify({
client_id: options.clientId,
client_secret: options.clientSecret,
code,
redirect_uri: options.redirectUri,
grant_type: "authorization_code",
}),
{ headers: { "Content-Type": "application/x-www-form-urlencoded" } }
);
return response.data.access_token;
};
export const getUserInfoMicrosoft = async (accessToken: any) => {
const response = await axios.get("https://graph.microsoft.com/v1.0/me", {
headers: { Authorization: `Bearer ${accessToken}` },
});
return response.data;
};
export const handleMicrosoftCallback = async (code: string, options: MicrosoftOAuthOptions) => {
try {
const accessToken = await getTokenMicrosoft(code, options);
const profile = await getUserInfoMicrosoft(accessToken);
// Now update the user's Microsoft ID in the database
const user = await dbService.findUserByEmail(profile.userPrincipalName);
if (user) {
await dbService.updateUser(user.id, { microsoftId: profile.id });
}
return profile;
} catch (err) {
throw err;
}
};