@andrey4emk/npm-app-back-b24 0.8.5 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bitrix24/b24.js +102 -44
  2. package/package.json +3 -3
package/bitrix24/b24.js CHANGED
@@ -1,61 +1,119 @@
1
- import { B24OAuth, AuthOAuthManager } from "@bitrix24/b24jssdk";
2
1
  import { DateTime } from "luxon";
3
- import dotEnv from "dotenv";
2
+ import path from "path";
3
+ import Conf from "conf";
4
4
 
5
+ import dotEnv from "dotenv";
5
6
  dotEnv.config();
6
7
 
7
- const APP_NAME = process.env.APP_NAME;
8
+ let appName = process.env.APP_NAME || "Задай название приложения в .env";
9
+ let configDir = process.env.CONFIG_DIR || "../config";
10
+ let appEnv = process.env.APP_ENV || "PROD";
8
11
 
9
- async function makeAuthParams(authParamB24, secretParamB24) {
10
- // Формируем параметры авторизации для SDK
11
- let AuthParams = {
12
- applicationToken: "", // если нет — можно '' (см. примечание ниже)
13
- userId: 0, // если неизвестен — 0
14
- memberId: authParamB24.member_id,
15
- accessToken: authParamB24.access_token,
16
- refreshToken: authParamB24.refresh_token,
17
- expires: authParamB24.expires_in,
18
- expiresIn: 1800,
19
- scope: "", // если нет строки scope — оставьте пусто
20
- domain: authParamB24.domain,
21
- clientEndpoint: `https://${authParamB24.domain}/rest/`,
22
- serverEndpoint: "https://oauth.bitrix.info/rest/",
23
- status: "L", // Local — для локальных приложений; подставьте свой вариант
24
- issuer: "store", // опционально
25
- };
26
- let secret = {
27
- clientId: secretParamB24.clientId,
28
- clientSecret: secretParamB24.clientSecret,
29
- };
30
- return { AuthParams, secret };
31
- }
12
+ let clientId = appEnv == "DEV" ? process.env.APP_B24_CLIENT_ID_DEV : process.env.APP_B24_CLIENT_ID;
13
+ let clientSecret = appEnv == "DEV" ? process.env.APP_B24_CLIENT_SECRET_DEV : process.env.APP_B24_CLIENT_SECRET;
14
+
15
+ let confAuthB24 = new Conf({
16
+ cwd: path.resolve(configDir),
17
+ configName: "authB24",
18
+ });
19
+
20
+ // Получаем данные авторизации из конфига
21
+ const authConfig = confAuthB24.get()?.[appEnv];
22
+
23
+ export class B24Prepared {
24
+ constructor() {}
25
+
26
+ async makeAuthParams() {
27
+ // Проверяем данные из confAuthB24. Если чего то не хватает, то возвращаем null
28
+ if (!authConfig || !authConfig.domain || !authConfig.access_token || !authConfig.refresh_token) {
29
+ return { error: true, data: null, message: "В конфиге authB24 не хватает данных для авторизации." };
30
+ }
31
+ // Формируем параметры авторизации для SDK
32
+ let AuthParams = {
33
+ applicationToken: "", // если нет — можно '' (см. примечание ниже)
34
+ userId: 0, // если неизвестен — 0
35
+ memberId: authConfig.member_id,
36
+ accessToken: authConfig.access_token,
37
+ refreshToken: authConfig.refresh_token,
38
+ expires: authConfig.expires_in,
39
+ expiresIn: 1800,
40
+ scope: "", // если нет строки scope — оставьте пусто
41
+ domain: authConfig.domain,
42
+ clientEndpoint: `https://${authConfig.domain}/rest/`,
43
+ serverEndpoint: "https://oauth.bitrix.info/rest/",
44
+ status: "L", // Local — для локальных приложений; подставьте свой вариант
45
+ issuer: "store", // опционально
46
+ };
47
+ // Если authParamB24.domain содержит https://, то удаляем его
48
+ if (AuthParams.domain.startsWith("https://")) {
49
+ AuthParams.domain = AuthParams.domain.replace("https://", "");
50
+ }
51
+
52
+ // Проверяем секреты приложения
53
+ if (!clientId || !clientSecret) {
54
+ return { error: true, data: null, message: "Не заданы clientId или clientSecret приложения в .env." };
55
+ }
56
+ let secret = {
57
+ clientId: clientId,
58
+ clientSecret: clientSecret,
59
+ };
32
60
 
33
- export async function create(authParamB24, secretParamB24) {
34
- let { AuthParams, secret } = await makeAuthParams(authParamB24, secretParamB24);
35
- // Если authParamB24.domain содержит https://, то удаляем его
36
- if (AuthParams.domain.startsWith("https://")) {
37
- AuthParams.domain = AuthParams.domain.replace("https://", "");
61
+ // Если все ок, то возвращаем параметры в data
62
+ return { error: false, data: { AuthParams, secret }, message: "Параметры авторизации сформированы." };
38
63
  }
39
- return await new B24OAuth(AuthParams, secret);
40
- }
41
64
 
42
- // Функция продления токена битрикс24 и сохранения в БД
43
- export async function refresh(authParamB24, secretParamB24) {
44
- try {
45
- let { AuthParams, secret } = await makeAuthParams(authParamB24, secretParamB24);
46
- let newToken = await new AuthOAuthManager(AuthParams, secret).refreshAuth();
47
- if (!newToken) {
48
- return { error: true, message: "В refresh не получили токен" };
65
+ // Сохраняем токены из фронта
66
+ async save(req = null, res = null, $b24) {
67
+ try {
68
+ if (!req) {
69
+ // Вызвали компонент из бэка для пересохранения токенов
70
+ if (!$b24) {
71
+ return { error: true, message: "$b24 не инициализирован." };
72
+ }
73
+
74
+ // Пробуем получить данные авторизации
75
+ let newAuth = null;
76
+ try {
77
+ newAuth = $b24.auth.getAuthData();
78
+ } catch (error) {
79
+ return { error: true, message: `Ошибка при получении данных авторизации из $b24. ${error.message} ` };
80
+ }
81
+
82
+ if (!newAuth || !newAuth.access_token) {
83
+ return { error: true, message: "Не удалось получить новые токены из $b24.auth.getAuthData()." };
84
+ } else {
85
+ confAuthB24.set(appEnv, newAuth);
86
+ return { error: false, message: "Токены битрикс24 пересохранены из бэка." };
87
+ }
88
+ } else {
89
+ // Вызвали из фронта
90
+ try {
91
+ const { access_token, refresh_token, domain, expires_in, member_id } = req.body;
92
+ if (!access_token || !refresh_token || !domain || !expires_in || !member_id) {
93
+ return res.status(400).json({ status: "error", message: "Не заполнены обязательные поля." });
94
+ }
95
+ // Если домен начинается с https:// или http:// убираем эту часть
96
+ let domainClean = domain.replace("https://", "").replace("http://", "");
97
+ confAuthB24.set(appEnv, {
98
+ access_token,
99
+ refresh_token,
100
+ domain: domainClean,
101
+ expires_in,
102
+ member_id,
103
+ });
104
+ res.status(201).json({ status: "ok", message: "Сохранили токены. Перезапустите сервер для применения." });
105
+ } catch (error) {
106
+ res.status(500).json({ status: "error", message: "Не удалось сохранить токен." });
107
+ }
108
+ }
109
+ } catch (error) {
110
+ return { error: true, message: `Ошибка при сохранении токенов: ${error.message}` };
49
111
  }
50
- return { error: false, message: "Токены битрикс24 успешно обновлены.", data: newToken };
51
- } catch (error) {
52
- return { error: true, message: "Не удалось продлить авторизацию.", data: error };
53
112
  }
54
113
  }
55
114
 
56
115
  export async function errTask(b24, dataTask) {
57
116
  try {
58
- let appName = APP_NAME || "Задай название приложения в .env";
59
117
  let title = dataTask.title;
60
118
  let description = dataTask.description || "";
61
119
  let createdBy = dataTask.createdBy || 138;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrey4emk/npm-app-back-b24",
3
- "version": "0.8.5",
3
+ "version": "0.9.0",
4
4
  "description": "Bitrix24 OAuth helpers for Node.js projects",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -29,9 +29,9 @@
29
29
  "sendMessage/wappi.js"
30
30
  ],
31
31
  "dependencies": {
32
- "@bitrix24/b24jssdk": "^0.5.1",
33
32
  "luxon": "^3.4.4",
34
33
  "dotenv": "^17.2.3",
35
- "nodemailer": "^7.0.6"
34
+ "nodemailer": "^7.0.6",
35
+ "conf": "^15.0.2"
36
36
  }
37
37
  }