salix/back/methods/chat/getServiceAuth.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

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',
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;
2023-01-16 14:18:24 +00:00
if (Date.vnNow() > 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
},
2023-01-16 14:18:24 +00:00
expires: Date.vnNow() + (1000 * 60 * tokenLifespan)
};
}
}
};