2022-02-22 06:30:26 +00:00
|
|
|
const axios = require('axios');
|
|
|
|
const tokenLifespan = 10;
|
|
|
|
module.exports = Self => {
|
|
|
|
Self.remoteMethodCtx('getServiceAuth', {
|
2022-03-01 10:09:10 +00:00
|
|
|
description: 'Authenticates with the service and request a new token',
|
2022-02-22 06:30:26 +00:00
|
|
|
accessType: 'READ',
|
|
|
|
accepts: [],
|
|
|
|
returns: {
|
|
|
|
type: 'object',
|
|
|
|
root: true
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/getServiceAuth`,
|
|
|
|
verb: 'GET'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.getServiceAuth = async() => {
|
|
|
|
if (!this.login)
|
|
|
|
this.login = await requestToken();
|
|
|
|
|
|
|
|
if (!this.login) return;
|
|
|
|
|
|
|
|
if (Date.now() > this.login.expires)
|
|
|
|
this.login = await requestToken();
|
|
|
|
|
|
|
|
return this.login;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Requests a new Rocketchat token
|
|
|
|
*/
|
|
|
|
async function requestToken() {
|
|
|
|
const models = Self.app.models;
|
|
|
|
const chatConfig = await models.ChatConfig.findOne();
|
|
|
|
|
|
|
|
const {data} = await axios.post(`${chatConfig.api}/login`, {
|
|
|
|
user: chatConfig.user,
|
|
|
|
password: chatConfig.password
|
|
|
|
});
|
|
|
|
|
|
|
|
const requestData = data.data;
|
|
|
|
if (requestData) {
|
|
|
|
return {
|
|
|
|
host: chatConfig.host,
|
|
|
|
api: chatConfig.api,
|
|
|
|
auth: {
|
|
|
|
userId: requestData.userId,
|
|
|
|
token: requestData.authToken
|
|
|
|
},
|
|
|
|
expires: Date.now() + (1000 * 60 * tokenLifespan)
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|