Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix: Azure endpoint return all users from ioet
  • Loading branch information
cxcarvaj committed Feb 16, 2022
commit 67c6f701a31d322f44c0dd09ec08bb45d2f708e9
65 changes: 34 additions & 31 deletions nodejs-functions/src/handlers/automatic-clock-outs/clock_out.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
const _ = require("lodash");
const CosmosClient = require("@azure/cosmos").CosmosClient;
const config = require("./config");
const TimeEntry = require("./time_entry");
const MsalClient = require("./msal_client");
const TimeEntryDao = require("./time_entry_dao");
const SlackClient = require("./slack_client");
const { CLOCK_OUT_MESSAGE, CLOCK_OUT_MESSAGE_MIDNIGHT } = require("./constants");
const _ = require('lodash');
const CosmosClient = require('@azure/cosmos').CosmosClient;
const config = require('./config');
const TimeEntry = require('./time_entry');
const MsalClient = require('./msal_client');
const TimeEntryDao = require('./time_entry_dao');
const SlackClient = require('./slack_client');
const { CLOCK_OUT_MESSAGE, CLOCK_OUT_MESSAGE_MIDNIGHT } = require('./constants');

const doClockOut = async (context) => {
context.log(
console.log(
`I am going to check how many entries were not clocked out ${new Date()}`
);

const { endpoint, key, databaseId } = config;
const client = new CosmosClient({ endpoint, key });
const database = client.database(databaseId);
const container = database.container("time_entry");
const container = database.container('time_entry');
const timeEntryDao = new TimeEntryDao(database);

const response = await MsalClient.findUsersInMS();
const users = response.data.value;
const users = response.data;
const slackUsers = await SlackClient.findUsersInSlack();

const { resources: entries } = await timeEntryDao.getEntriesWithNoEndDate();
context.log(`Checking for time-entries that need to be clocked out`);
console.log(`Checking for time-entries that need to be clocked out`);

let totalClockOutsExecuted = 0;

Expand All @@ -32,40 +32,43 @@ const doClockOut = async (context) => {
const timeEntry = new TimeEntry(timeEntryAsJson);
const { userName, userEmail } = findUserData(users, timeEntry.timeEntry.owner_id);
const userId = findSlackUserId(slackUsers, userEmail);

if (timeEntry.needsToBeClockedOut()) {
if (userId) {
SlackClient.sendMessageToUser(userId, CLOCK_OUT_MESSAGE.replace('%user_name%', userName));
if( userEmail === '[email protected]'){
if (timeEntry.needsToBeClockedOut()) {
if (userId) {
SlackClient.sendMessageToUser(userId, CLOCK_OUT_MESSAGE.replace('%user_name%', userName));
}
timeEntryAsJson.end_date = timeEntry.getTimeToClockOut();
await container.item(timeEntryAsJson.id, timeEntryAsJson.tenant_id).replace(timeEntryAsJson);
totalClockOutsExecuted++;
}
timeEntryAsJson.end_date = timeEntry.getTimeToClockOut();
await container.item(timeEntryAsJson.id, timeEntryAsJson.tenant_id).replace(timeEntryAsJson);
totalClockOutsExecuted++;
}

else if (timeEntry.needsToBeClockedOutMidnight()) {
if (userId) {
SlackClient.sendMessageToUser(userId, CLOCK_OUT_MESSAGE_MIDNIGHT.replace('%user_name%', userName));

else if (timeEntry.needsToBeClockedOutMidnight()) {
if (userId) {
SlackClient.sendMessageToUser(userId, CLOCK_OUT_MESSAGE_MIDNIGHT.replace('%user_name%', userName));
}
timeEntryAsJson.end_date = timeEntry.getTimeToClockOutMidnight();
await container.item(timeEntryAsJson.id, timeEntryAsJson.tenant_id).replace(timeEntryAsJson);
totalClockOutsExecuted++;
}
timeEntryAsJson.end_date = timeEntry.getTimeToClockOutMidnight();
await container.item(timeEntryAsJson.id, timeEntryAsJson.tenant_id).replace(timeEntryAsJson);
totalClockOutsExecuted++;
}

})
);

context.log(
console.log(
`I just clocked out ${totalClockOutsExecuted} entries, thanks are not needed...`
);
};


const findUserData = (users, id) => {
const user = users.find((user) => user.objectId === id);
return user ? { userName: user.displayName.split(" ")[0], userEmail: _.first(user.otherMails) } : {};
const user = users.find((user) => user.id === id);
return user ? { userName: user.name.split(' ')[0], userEmail: (user.email) } : {};
};

const findSlackUserId = (slackUsers, email) => {
const user = slackUsers.find((slackUser) => slackUser.email === email);
return user ? user.id : null;
};

doClockOut()
module.exports = { doClockOut };
5 changes: 4 additions & 1 deletion nodejs-functions/src/handlers/automatic-clock-outs/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ const config = {
clientId: process.env["CLIENT_ID"],
authority: process.env["AUTHORITY"],
clientSecret: process.env["CLIENT_SECRET"],
slackApiToken: process.env["SLACK_TOKEN_NOTIFY"]
slackApiToken: process.env["SLACK_TOKEN_NOTIFY"],
userNameMS: process.env["USER_NAME_MS"],
userPasswordMS: process.env["USER_PASSWORD_MS"]

};

module.exports = config;
72 changes: 46 additions & 26 deletions nodejs-functions/src/handlers/automatic-clock-outs/msal_client.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,47 @@
const axios = require("axios")
const msal = require('@azure/msal-node');
const config = require("./config");

const findUsersInMS = async() => {
const {clientId, authority, clientSecret} = config;
const endpoint = 'https://graph.windows.net/ioetec.onmicrosoft.com'
const configuration = {
auth: {
clientId: clientId,
authority: authority,
clientSecret: clientSecret
}
};

const cca = new msal.ConfidentialClientApplication(configuration);
const clientCredentialRequest = {
scopes: ['https://graph.windows.net/.default'],
};
const response = await cca.acquireTokenByClientCredential(clientCredentialRequest)
const token = response.accessToken
return axios.get(`${endpoint}/users?api-version=1.6&$select=displayName,otherMails,objectId`,
{ 'headers': { 'Authorization': token } })
}

module.exports = { findUsersInMS };
const axios = require('axios');
const config = require('./config');

const getToken = async () => {
const { clientId, userNameMS, userPasswordMS } = config;
const endpoint =
'https://ioetec.b2clogin.com/ioetec.onmicrosoft.com/B2C_1_accesstoken/oauth2/v2.0/token';

const params = new URLSearchParams();

params.append('username', userNameMS);
params.append('password', userPasswordMS);
params.append('grant_type', 'password');
params.append('scope', clientId);
params.append('client_id', clientId);
params.append('response_type', 'token');

const headers = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};

return await axios
.post(endpoint, params, headers)
.then((result) => {
return result.data.access_token;
})
.catch((err) => {
console.log(`Invalid request to: ${endpoint}`);
});
};

const findUsersInMS = async () => {
const endpoint = 'https://timetracker-api.azurewebsites.net/';
const token = await getToken();

const headers = {
headers: {
Authorization: `Bearer ${token}`,
},
};

return await axios.get(`${endpoint}/users`, headers);
};

module.exports = { findUsersInMS };
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const moment = require("moment")
const moment = require('moment')

class TimeEntry {

Expand All @@ -15,7 +15,7 @@ class TimeEntry {
}

getMidnightInTimeEntryZone(){
return moment(this.timeEntry.start_date).utcOffset(this.timeEntry.timezone_offset * -1).endOf('day');
return moment(this.timeEntry.start_date).utc().subtract(this.timeEntry.timezone_offset, 'minutes').endOf('day')
}

getTimeToClockOutMidnight(){
Expand Down