This repository has been archived on 2025-12-25. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
qmi-cloud/server/utils.js
2024-04-22 11:04:36 +02:00

88 lines
3.1 KiB
JavaScript

const axios = require('axios');
const fs = require('fs');
const path = require('path');
const config = require('./config');
const qs = require('qs');
const getUserMsGraph = async function(trigramEmail, doSavePhoto) {
console.log("Passport# Getting MsGraph data for user ", trigramEmail);
try {
const msConfig = {
client_id: config.creds.azureAdClientId,
client_secret: config.creds.azureAdClientSecret,
scope: "https://graph.microsoft.com/.default",
grant_type: "client_credentials"
}
const msTokenRes = await axios.post('https://login.microsoftonline.com/c21eeb5f-f5a6-44e8-a997-124f2f7a497c/oauth2/v2.0/token', qs.stringify(msConfig), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const msAccessToken = msTokenRes.data.access_token;
var msUser = await axios({
method: "GET",
headers: {
Authorization: "Bearer "+ msAccessToken
},
url: `https://graph.microsoft.com/v1.0/users/${trigramEmail}`
});
if (doSavePhoto){
//Save user photo
saveUserPhoto(trigramEmail, msUser.data.id, msAccessToken);
}
return msUser.data;
} catch (e){
console.log('Passport# Error MS Graph stuff!!');
return null;
}
}
const saveUserPhoto = async function(trigramEmail, oid, msAccessToken) {
const pic_path = path.resolve(__dirname, '..', 'photos', `${oid}.jpg`);
if (!fs.existsSync(pic_path)) {
if (!msAccessToken) {
const msConfig = {
client_id: config.creds.azureAdClientId,
client_secret: config.creds.azureAdClientSecret,
scope: "https://graph.microsoft.com/.default",
grant_type: "client_credentials"
}
const msTokenRes = await axios.post('https://login.microsoftonline.com/c21eeb5f-f5a6-44e8-a997-124f2f7a497c/oauth2/v2.0/token', qs.stringify(msConfig), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
msAccessToken = msTokenRes.data.access_token;
}
//Save user photo
axios({
method: 'GET',
url: `https://graph.microsoft.com/v1.0/users/${trigramEmail}/photo/$value`,
responseType: 'stream',
headers: { 'Authorization' : 'Bearer '+msAccessToken }
}).then(function (response) {
console.log(`Passport# Picture found for user (${trigramEmail}) - Saving it to path: ${pic_path}`);
response.data.pipe(fs.createWriteStream(pic_path));
}).catch(function(err){
console.log(`Passport# Error: No picture found for user (${trigramEmail}) or other error- Do nothing`);
});
} else {
console.log(`Passport# Picture already exists for this user (${trigramEmail}) - Do nothing.`);
}
}
module.exports.getUserMsGraph = getUserMsGraph;
module.exports.saveUserPhoto = saveUserPhoto;