@adminforth/two-factors-auth 1.0.10 → 1.0.14

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.
@@ -0,0 +1,152 @@
1
+ <template>
2
+ <div class="relative flex items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-800"
3
+ :style="coreStore.config?.loginBackgroundImage ? {
4
+ 'background-image': 'url(' + loadFile(coreStore.config?.loginBackgroundImage) + ')',
5
+ 'background-size': 'cover',
6
+ 'background-position': 'center',
7
+ 'background-blend-mode': 'darken'
8
+ }: {}"
9
+ >
10
+
11
+ <div id="authentication-modal" tabindex="-1" class=" overflow-y-auto overflow-x-hidden z-50 min-w-[00px] justify-center items-center md:inset-0 h-[calc(100%-1rem)] max-h-full">
12
+ <div class="relative p-4 w-full max-w-md max-h-full">
13
+ <!-- Modal content -->
14
+ <div class="relative bg-white rounded-lg shadow dark:bg-gray-700 dark:shadow-black text-gray-500" >
15
+ <div class="p-8 w-full max-w-md max-h-full" >
16
+ <div class="m-3" >Please enter your authenticator code </div>
17
+
18
+ <form class="max-w-sm mx-auto mt-6 flex flex-col items-center ">
19
+ <div class="flex mb-2 space-x-2 rtl:space-x-reverse ">
20
+ <div>
21
+ <label for="code-1" class="sr-only">First code</label>
22
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-next="code-2" id="code-1" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
23
+ </div>
24
+ <div>
25
+ <label for="code-2" class="sr-only">Second code</label>
26
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-1" data-focus-input-next="code-3" id="code-2" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
27
+ </div>
28
+ <div>
29
+ <label for="code-3" class="sr-only">Third code</label>
30
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-2" data-focus-input-next="code-4" id="code-3" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
31
+ </div>
32
+ <div>
33
+ <label for="code-4" class="sr-only">Fourth code</label>
34
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-3" data-focus-input-next="code-5" id="code-4" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
35
+ </div>
36
+ <div>
37
+ <label for="code-5" class="sr-only">Fifth code</label>
38
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-4" data-focus-input-next="code-6" id="code-5" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
39
+ </div>
40
+ <div>
41
+ <label for="code-6" class="sr-only">Sixth code</label>
42
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-5" id="code-6" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
43
+ </div>
44
+ </div>
45
+ <p id="helper-text-explanation" class="mt-2 text-sm text-gray-500 dark:text-gray-400"></p>
46
+ </form>
47
+ <button @click="()=>{router.push('./login')}" class="flex items-center justify-center gap-1 w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
48
+ >Cancel</button>
49
+ </div>
50
+ </div>
51
+ </div>
52
+ </div>
53
+
54
+ </div>
55
+
56
+
57
+ </template>
58
+
59
+
60
+ <script setup>
61
+
62
+ import { onMounted, ref, watchEffect,computed } from 'vue';
63
+ import { useCoreStore } from '@/stores/core';
64
+ import { useUserStore } from '@/stores/user';
65
+ import { IconEyeSolid, IconEyeSlashSolid } from '@iconify-prerendered/vue-flowbite';
66
+ import { callAdminForthApi, loadFile } from '@/utils';
67
+ import { useRouter } from 'vue-router';
68
+ import { initFlowbite } from 'flowbite'
69
+ import { showErrorTost } from '@/composables/useFrontendApi';
70
+
71
+
72
+
73
+
74
+ const router = useRouter();
75
+ const inProgress = ref(false);
76
+
77
+ const coreStore = useCoreStore();
78
+ const user = useUserStore();
79
+
80
+ // use this simple function to automatically focus on the next input
81
+
82
+
83
+
84
+ const showPw = ref(false);
85
+
86
+ const error = ref(null);
87
+ const totp = ref({});
88
+ const totpJWT = ref(null);
89
+
90
+
91
+ function parseJwt(token) {
92
+ // Split the token into its parts
93
+ const base64Url = token.split('.')[1];
94
+
95
+ // Base64-decode the payload
96
+ const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
97
+ const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
98
+ return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
99
+ }).join(''));
100
+
101
+ // Parse the JSON payload
102
+ return JSON.parse(jsonPayload);
103
+ }
104
+
105
+ onMounted(async () => {
106
+ coreStore.getPublicConfig()
107
+
108
+ function focusNextInput(el, prevId, nextId) {
109
+ if (el.value.length === 0) {
110
+ if (prevId) {
111
+ document.getElementById(prevId).focus();
112
+ }
113
+ } else {
114
+ if (nextId) {
115
+ document.getElementById(nextId).focus();
116
+ } else {
117
+ sendCode()
118
+ }
119
+ }
120
+ }
121
+
122
+ document.querySelectorAll('[data-focus-input-init]').forEach(function(element) {
123
+ element.addEventListener('keyup', function() {
124
+ const prevId = this.getAttribute('data-focus-input-prev');
125
+ const nextId = this.getAttribute('data-focus-input-next');
126
+ focusNextInput(this, prevId, nextId);
127
+ });
128
+ });
129
+
130
+
131
+
132
+ });
133
+
134
+ async function sendCode () {
135
+ inProgress.value = true;
136
+ const code = document.getElementById('code-1').value + document.getElementById('code-2').value + document.getElementById('code-3').value + document.getElementById('code-4').value + document.getElementById('code-5').value + document.getElementById('code-6').value;
137
+ const resp = await callAdminForthApi({
138
+ method: 'POST',
139
+ path: '/plugin/twofa/confirmSetup',
140
+ body: {
141
+ code: code,
142
+ secret: null,
143
+ }
144
+ })
145
+ if (resp.allowedLogin){
146
+ router.push('/');
147
+ } else {
148
+ showErrorTost('Invalid code');
149
+ }
150
+ }
151
+ </script>
152
+
File without changes
@@ -0,0 +1,188 @@
1
+ <template>
2
+ <div class="relative flex items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-800"
3
+ :style="coreStore.config?.loginBackgroundImage ? {
4
+ 'background-image': 'url(' + loadFile(coreStore.config?.loginBackgroundImage) + ')',
5
+ 'background-size': 'cover',
6
+ 'background-position': 'center',
7
+ 'background-blend-mode': 'darken'
8
+ }: {}"
9
+ >
10
+
11
+ <div id="authentication-modal" tabindex="-1" class=" overflow-y-auto overflow-x-hidden z-50 min-w-[00px] justify-center items-center md:inset-0 h-[calc(100%-1rem)] max-h-full">
12
+ <div class="relative p-4 w-full max-w-md max-h-full">
13
+ <!-- Modal content -->
14
+ <div class="relative bg-white rounded-lg shadow dark:bg-gray-700 dark:shadow-black text-gray-500" >
15
+ <div class="p-8 w-full max-w-md max-h-full" >
16
+ <div class="m-3" >Scan this QR code with your authenticator app or open by <a class="text-blue-600" :href="totpUri">click</a></div>
17
+ <div class="flex justify-center m-3" >
18
+ <img :src="totpQrCode" alt="QR code" />
19
+ </div>
20
+ <div class="m-3 ">
21
+ <div class="m-1">Or copy this code to app manually:</div>
22
+ <div class="w-full max-w-[46rem]">
23
+ <div class="relative">
24
+ <label for="npm-install-copy-text" class="sr-only">Label</label>
25
+ <input id="npm-install-copy-text" type="text" class="col-span-10 bg-gray-50 border border-gray-300 text-gray-500 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full px-2.5 py-4 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-400 dark:focus:ring-blue-500 dark:focus:border-blue-500" :value="totp.newSecret" disabled readonly>
26
+ <button data-copy-to-clipboard-target="npm-install-copy-text" class="absolute end-2.5 top-1/2 -translate-y-1/2 text-gray-900 dark:text-gray-400 hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-600 dark:hover:bg-gray-700 rounded-lg py-2 px-2.5 inline-flex items-center justify-center bg-white border-gray-200 border">
27
+ <span id="default-message" class="inline-flex items-center">
28
+ <svg class="w-3 h-3 me-1.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 18 20">
29
+ <path d="M16 1h-3.278A1.992 1.992 0 0 0 11 0H7a1.993 1.993 0 0 0-1.722 1H2a2 2 0 0 0-2 2v15a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2Zm-3 14H5a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2Zm0-4H5a1 1 0 0 1 0-2h8a1 1 0 1 1 0 2Zm0-5H5a1 1 0 0 1 0-2h2V2h4v2h2a1 1 0 1 1 0 2Z"/>
30
+ </svg>
31
+ <span class="text-xs font-semibold">Copy</span>
32
+ </span>
33
+ <span id="success-message" class="hidden inline-flex items-center">
34
+ <svg class="w-3 h-3 text-blue-700 dark:text-blue-500 me-1.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 12">
35
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M1 5.917 5.724 10.5 15 1.5"/>
36
+ </svg>
37
+ <span class="text-xs font-semibold text-blue-700 dark:text-blue-500">Copied</span>
38
+ </span>
39
+ </button>
40
+ </div>
41
+ </div>
42
+ </div>
43
+ <form class="max-w-sm mx-auto mt-6 flex flex-col items-center ">
44
+ <div class="flex mb-2 space-x-2 rtl:space-x-reverse ">
45
+ <div>
46
+ <label for="code-1" class="sr-only">First code</label>
47
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-next="code-2" id="code-1" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
48
+ </div>
49
+ <div>
50
+ <label for="code-2" class="sr-only">Second code</label>
51
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-1" data-focus-input-next="code-3" id="code-2" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
52
+ </div>
53
+ <div>
54
+ <label for="code-3" class="sr-only">Third code</label>
55
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-2" data-focus-input-next="code-4" id="code-3" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
56
+ </div>
57
+ <div>
58
+ <label for="code-4" class="sr-only">Fourth code</label>
59
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-3" data-focus-input-next="code-5" id="code-4" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
60
+ </div>
61
+ <div>
62
+ <label for="code-5" class="sr-only">Fifth code</label>
63
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-4" data-focus-input-next="code-6" id="code-5" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
64
+ </div>
65
+ <div>
66
+ <label for="code-6" class="sr-only">Sixth code</label>
67
+ <input type="text" maxlength="1" data-focus-input-init data-focus-input-prev="code-5" id="code-6" class="block w-9 h-9 py-3 text-sm font-extrabold text-center text-gray-900 bg-white border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required />
68
+ </div>
69
+ </div>
70
+ <p id="helper-text-explanation" class="mt-2 text-sm text-gray-500 dark:text-gray-400"></p>
71
+ </form>
72
+ <button @click="()=>{router.push('./login')}" class="flex items-center justify-center gap-1 w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Cancel</button>
73
+ </div>
74
+ </div>
75
+ </div>
76
+ </div>
77
+
78
+ </div>
79
+
80
+
81
+ </template>
82
+
83
+
84
+ <script setup>
85
+
86
+ import { onMounted, ref, watchEffect,computed } from 'vue';
87
+ import { useCoreStore } from '@/stores/core';
88
+ import { useUserStore } from '@/stores/user';
89
+ import { IconEyeSolid, IconEyeSlashSolid } from '@iconify-prerendered/vue-flowbite';
90
+ import { callAdminForthApi, loadFile } from '@/utils';
91
+ import { useRouter } from 'vue-router';
92
+ import { initFlowbite } from 'flowbite'
93
+ import { showErrorTost } from '@/composables/useFrontendApi';
94
+
95
+
96
+
97
+
98
+ const router = useRouter();
99
+ const inProgress = ref(false);
100
+
101
+ const coreStore = useCoreStore();
102
+ const user = useUserStore();
103
+
104
+ // use this simple function to automatically focus on the next input
105
+
106
+
107
+
108
+ const showPw = ref(false);
109
+
110
+ const error = ref(null);
111
+ const totp = ref({});
112
+ const totpJWT = ref(null);
113
+ const totpUri = computed(() => {
114
+ if (totp.value) {
115
+ return `otpauth://totp/${totp.value.issuer}:${totp.value.userName}?secret=${totp.value.newSecret}&issuer=${totp.value.issuer}`;
116
+ }});
117
+ const totpQrCode = computed(() => {
118
+ if (totpUri.value) {
119
+ return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(totpUri.value)}`;
120
+ }});
121
+
122
+ function parseJwt(token) {
123
+ // Split the token into its parts
124
+ const base64Url = token.split('.')[1];
125
+
126
+ // Base64-decode the payload
127
+ const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
128
+ const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
129
+ return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
130
+ }).join(''));
131
+
132
+ // Parse the JSON payload
133
+ return JSON.parse(jsonPayload);
134
+ }
135
+
136
+ onMounted(async () => {
137
+ coreStore.getPublicConfig()
138
+ const resp = await callAdminForthApi({
139
+ path: '/plugin/twofa/initSetup',
140
+ method: 'POST',});
141
+ if (resp && resp.totpJWT){
142
+ totpJWT.value = resp.totpJWT;
143
+ }
144
+ function focusNextInput(el, prevId, nextId) {
145
+ if (el.value.length === 0) {
146
+ if (prevId) {
147
+ document.getElementById(prevId).focus();
148
+ }
149
+ } else {
150
+ if (nextId) {
151
+ document.getElementById(nextId).focus();
152
+ } else {
153
+ sendCode()
154
+ }
155
+ }
156
+ }
157
+
158
+ document.querySelectorAll('[data-focus-input-init]').forEach(function(element) {
159
+ element.addEventListener('keyup', function() {
160
+ const prevId = this.getAttribute('data-focus-input-prev');
161
+ const nextId = this.getAttribute('data-focus-input-next');
162
+ focusNextInput(this, prevId, nextId);
163
+ });
164
+ });
165
+
166
+ totp.value=parseJwt(totpJWT.value);
167
+
168
+
169
+ });
170
+
171
+ async function sendCode () {
172
+ inProgress.value = true;
173
+ const code = document.getElementById('code-1').value + document.getElementById('code-2').value + document.getElementById('code-3').value + document.getElementById('code-4').value + document.getElementById('code-5').value + document.getElementById('code-6').value;
174
+ const resp = await callAdminForthApi({
175
+ method: 'POST',
176
+ path: '/plugin/twofa/confirmSetup',
177
+ body: {
178
+ code: code,
179
+ secret: totp.value.newSecret,
180
+ }
181
+ })
182
+ if (resp.allowedLogin){
183
+ router.push('/');
184
+ } else {
185
+ showErrorTost('Invalid code');
186
+ }
187
+ }
188
+ </script>
package/dist/index.js CHANGED
@@ -40,11 +40,7 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
40
40
  if (!this.authResource.columns.some((col) => col.name === this.options.twoFaSecretFieldName)) {
41
41
  throw new Error(`Column ${this.options.twoFaSecretFieldName} not found in ${this.authResource.label}`);
42
42
  }
43
- const beforeLoginConfirmation = this.adminforth.config.auth;
44
- if (!beforeLoginConfirmation.beforeLoginConfirmation) {
45
- beforeLoginConfirmation.beforeLoginConfirmation = [];
46
- }
47
- beforeLoginConfirmation.beforeLoginConfirmation.push((_a) => __awaiter(this, [_a], void 0, function* ({ adminUser }) {
43
+ this.adminforth.config.auth.beforeLoginConfirmation.push((_a) => __awaiter(this, [_a], void 0, function* ({ adminUser, response }) {
48
44
  if (adminUser.isRoot) {
49
45
  return { body: { loginAllowed: true }, ok: true };
50
46
  }
@@ -60,31 +56,22 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
60
56
  newSecret = tempSecret.secret;
61
57
  }
62
58
  else {
59
+ const value = this.adminforth.auth.issueJWT({ userName, issuer: brandName, pk: userPk }, 'tempTotp');
60
+ response.setHeader('Set-Cookie', `adminforth_totpTemporaryJWT=${value}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; max-age=3600; `);
63
61
  return {
64
62
  body: {
65
63
  loginAllowed: false,
66
64
  redirectTo: '/confirm2fa',
67
- setCookie: [{
68
- name: 'totpTemporaryJWT',
69
- value: this.adminforth.auth.issueJWT({ userName, issuer: brandName, pk: userPk }, 'tempTotp'),
70
- expiry: '1h',
71
- httpOnly: true
72
- },]
73
65
  },
74
66
  ok: true
75
67
  };
76
68
  }
77
69
  const totpTemporaryJWT = this.adminforth.auth.issueJWT({ userName, newSecret, issuer: brandName, pk: userPk }, 'tempTotp');
70
+ response.setHeader('Set-Cookie', `adminforth_totpTemporaryJWT=${totpTemporaryJWT}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; Expires=${new Date(Date.now() + '1h').toUTCString()} `);
78
71
  return {
79
72
  body: {
80
73
  loginAllowed: false,
81
74
  redirectTo: secret ? '/confirm2fa' : '/setup2fa',
82
- setCookie: [{
83
- name: 'totpTemporaryJWT',
84
- value: totpTemporaryJWT,
85
- expiry: '1h',
86
- httpOnly: true
87
- },]
88
75
  },
89
76
  ok: true
90
77
  };
@@ -96,8 +83,9 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
96
83
  path: `/plugin/twofa/initSetup`,
97
84
  noAuth: true,
98
85
  handler: (server) => __awaiter(this, void 0, void 0, function* () {
86
+ var _a;
99
87
  const toReturn = { totpJWT: null, status: 'ok', };
100
- const totpTemporaryJWT = server.cookies['adminforth_totpTemporaryJWT'];
88
+ const totpTemporaryJWT = (_a = server.cookies.find((cookie) => cookie.key === 'adminforth_totpTemporaryJWT')) === null || _a === void 0 ? void 0 : _a.value;
101
89
  if (totpTemporaryJWT) {
102
90
  toReturn.totpJWT = totpTemporaryJWT;
103
91
  }
@@ -108,7 +96,7 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
108
96
  method: 'POST',
109
97
  path: `/plugin/twofa/confirmSetup`,
110
98
  noAuth: true,
111
- handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response, cookies }) {
99
+ handler: (_b) => __awaiter(this, [_b], void 0, function* ({ body, adminUser, response, cookies }) {
112
100
  const totpTemporaryJWT = cookies['adminforth_totpTemporaryJWT'];
113
101
  const decoded = yield this.adminforth.auth.verify(totpTemporaryJWT, 'tempTotp');
114
102
  if (!decoded) {
package/index.ts CHANGED
@@ -1,10 +1,8 @@
1
- import { AdminForthResource } from "adminforth/types/AdminForthConfig.js";
2
- import type { IAdminForth, IHttpServer, IAdminForthAuth } from "adminforth/types/AdminForthConfig.js";
3
- import { AdminForthPlugin } from "adminforth";
1
+ import { AdminForthPlugin } from "adminforth";
2
+ import type { AdminForthResource, AdminUser, IAdminForth, IHttpServer, IAdminForthAuth, BeforeLoginConfirmationFunction, IAdminForthHttpResponse } from "adminforth";
4
3
  import twofactor from 'node-2fa';
5
4
  import { PluginOptions } from "./types.js"
6
5
 
7
-
8
6
  export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
9
7
  options: PluginOptions;
10
8
  adminforth: IAdminForth;
@@ -44,54 +42,46 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
44
42
  if(!this.authResource.columns.some((col)=>col.name === this.options.twoFaSecretFieldName)){
45
43
  throw new Error(`Column ${this.options.twoFaSecretFieldName} not found in ${this.authResource.label}`)
46
44
  }
47
- const beforeLoginConfirmation = this.adminforth.config.auth as any
48
- if (!beforeLoginConfirmation.beforeLoginConfirmation){
49
- beforeLoginConfirmation.beforeLoginConfirmation = []
50
- }
51
- beforeLoginConfirmation.beforeLoginConfirmation.push(async({adminUser})=>{
52
- if(adminUser.isRoot){
53
- return { body: {loginAllowed: true}, ok: true}
54
- }
55
- const secret = adminUser.dbUser[this.options.twoFaSecretFieldName]
56
- const userName = adminUser.dbUser[adminforth.config.auth.usernameField]
57
- const brandName = adminforth.config.customization.brandName
58
- const authResource = adminforth.config.resources.find((res)=>res.resourceId === adminforth.config.auth.resourceId )
59
- const authPk = authResource.columns.find((col)=>col.primaryKey).name
60
- const userPk = adminUser.dbUser[authPk]
61
- let newSecret = null
62
- if (!secret){
63
- const tempSecret = twofactor.generateSecret({name: brandName,account: userName})
64
- newSecret = tempSecret.secret
65
- } else {
66
- return {
45
+ (this.adminforth.config.auth.beforeLoginConfirmation as BeforeLoginConfirmationFunction[]).push(
46
+ async({ adminUser, response }: { adminUser: AdminUser, response: IAdminForthHttpResponse} )=> {
47
+ if(adminUser.isRoot){
48
+ return { body: {loginAllowed: true}, ok: true}
49
+ }
50
+ const secret = adminUser.dbUser[this.options.twoFaSecretFieldName]
51
+ const userName = adminUser.dbUser[adminforth.config.auth.usernameField]
52
+ const brandName = adminforth.config.customization.brandName
53
+ const authResource = adminforth.config.resources.find((res)=>res.resourceId === adminforth.config.auth.resourceId )
54
+ const authPk = authResource.columns.find((col)=>col.primaryKey).name
55
+ const userPk = adminUser.dbUser[authPk]
56
+ let newSecret = null
57
+ if (!secret){
58
+ const tempSecret = twofactor.generateSecret({name: brandName,account: userName})
59
+ newSecret = tempSecret.secret
60
+ } else {
61
+ const value = this.adminforth.auth.issueJWT({userName, issuer:brandName, pk:userPk },'tempTotp');
62
+ response.setHeader('Set-Cookie', `adminforth_totpTemporaryJWT=${value}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; max-age=3600; `);
63
+
64
+ return {
65
+ body:{
66
+ loginAllowed: false,
67
+ redirectTo: '/confirm2fa',
68
+
69
+ },
70
+ ok: true
71
+
72
+ }
73
+ }
74
+ const totpTemporaryJWT = this.adminforth.auth.issueJWT({userName, newSecret, issuer:brandName, pk:userPk },'tempTotp', )
75
+ response.setHeader('Set-Cookie', `adminforth_totpTemporaryJWT=${totpTemporaryJWT}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; Expires=${new Date(Date.now() + '1h').toUTCString() } `);
76
+
77
+ return {
67
78
  body:{
68
79
  loginAllowed: false,
69
- redirectTo: '/confirm2fa',
70
- setCookie: [{
71
- name: 'totpTemporaryJWT',
72
- value: this.adminforth.auth.issueJWT({userName, issuer:brandName, pk:userPk },'tempTotp', ),
73
- expiry: '1h',
74
- httpOnly: true
75
- },]
80
+ redirectTo: secret ? '/confirm2fa' : '/setup2fa',
76
81
  },
77
82
  ok: true
78
-
79
83
  }
80
- }
81
- const totpTemporaryJWT = this.adminforth.auth.issueJWT({userName, newSecret, issuer:brandName, pk:userPk },'tempTotp', )
82
- return {
83
- body:{
84
- loginAllowed: false,
85
- redirectTo: secret ? '/confirm2fa' : '/setup2fa',
86
- setCookie: [{
87
- name: 'totpTemporaryJWT',
88
- value: totpTemporaryJWT,
89
- expiry: '1h',
90
- httpOnly: true
91
- },]},
92
- ok: true
93
- }
94
- })
84
+ })
95
85
  }
96
86
 
97
87
  setupEndpoints(server: IHttpServer): void {
@@ -101,7 +91,8 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
101
91
  noAuth: true,
102
92
  handler: async (server) => {
103
93
  const toReturn = {totpJWT:null,status:'ok',}
104
- const totpTemporaryJWT = server.cookies['adminforth_totpTemporaryJWT']
94
+
95
+ const totpTemporaryJWT = server.cookies.find((cookie)=>cookie.key === 'adminforth_totpTemporaryJWT')?.value;
105
96
  if (totpTemporaryJWT){
106
97
  toReturn.totpJWT = totpTemporaryJWT
107
98
  }
package/package.json CHANGED
@@ -1,18 +1,16 @@
1
1
  {
2
2
  "name": "@adminforth/two-factors-auth",
3
- "version": "1.0.10",
3
+ "version": "1.0.14",
4
4
  "description": "AdminForth plugin for two factors authentication",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "type": "module",
8
8
  "scripts": {
9
- "test": "echo \"Error: no test specified\" && exit 1",
10
- "rollout": "tsc && npm version patch && npm publish --access public"
9
+ "rollout": "tsc && cp -rf custom dist/ && npm version patch && npm publish --access public"
11
10
  },
12
11
  "author": "devforth",
13
12
  "license": "ISC",
14
13
  "dependencies": {
15
- "adminforth": "^1.1.95",
16
14
  "node-2fa": "^2.0.3"
17
15
  }
18
16
  }
package/dist/auth.js DELETED
@@ -1,108 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import jwt from 'jsonwebtoken';
11
- import crypto from 'crypto';
12
- // Function to generate a password hash using PBKDF2
13
- function calcPasswordHash(password, salt, iterations = 100000, keyLength = 64, digest = 'sha512') {
14
- return new Promise((resolve, reject) => {
15
- crypto.pbkdf2(password, salt, iterations, keyLength, digest, (err, derivedKey) => {
16
- if (err)
17
- reject(err);
18
- resolve(derivedKey.toString('hex'));
19
- });
20
- });
21
- }
22
- // Function to generate a random salt
23
- function generateSalt(length = 16) {
24
- return crypto.randomBytes(length).toString('hex');
25
- }
26
- class AdminForthAuth {
27
- constructor(adminforth) {
28
- this.adminforth = adminforth;
29
- }
30
- removeAuthCookie(response) {
31
- response.setHeader('Set-Cookie', `adminforth_jwt=; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; Expires=Thu, 01 Jan 1970 00:00:00 GMT`);
32
- }
33
- setAuthCookie({ response, username, pk }) {
34
- const token = this.issueJWT({ username, pk, }, 'auth');
35
- response.setHeader('Set-Cookie', `adminforth_jwt=${token}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict`);
36
- }
37
- removeCustomCookie({ response, name }) {
38
- response.setHeader('Set-Cookie', `adminforth_test'='2'; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict`);
39
- }
40
- setCustomCookie({ response, payload }) {
41
- const { name, value, expiry, httpOnly } = payload;
42
- response.setHeader('Set-Cookie', `adminforth_${name}=${value}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; Expires=${new Date(Date.now() + expiry).toUTCString()} `);
43
- }
44
- issueJWT(payload, type) {
45
- // read ADMINFORH_SECRET from environment if not drop error
46
- const secret = process.env.ADMINFORTH_SECRET;
47
- if (!secret) {
48
- throw new Error('ADMINFORTH_SECRET environment not set');
49
- }
50
- // issue JWT token
51
- const expiresIn = process.env.ADMINFORTH_AUTH_EXPIRESIN || '24h';
52
- return jwt.sign(Object.assign(Object.assign({}, payload), { t: type }), secret, { expiresIn });
53
- }
54
- verify(jwtToken, mustHaveType) {
55
- return __awaiter(this, void 0, void 0, function* () {
56
- // read ADMINFORH_SECRET from environment if not drop error
57
- const secret = process.env.ADMINFORTH_SECRET;
58
- if (!secret) {
59
- throw new Error('ADMINFORTH_SECRET environment not set');
60
- }
61
- let decoded;
62
- try {
63
- // verify JWT token
64
- decoded = jwt.verify(jwtToken, secret);
65
- }
66
- catch (err) {
67
- if (err.name === 'TokenExpiredError') {
68
- console.error('Token expired:', err.message);
69
- }
70
- else if (err.name === 'JsonWebTokenError') {
71
- console.error('Token error:', err.message);
72
- }
73
- else {
74
- console.error('Failed to verify JWT token', err);
75
- }
76
- return null;
77
- }
78
- const { pk, t } = decoded;
79
- if (t !== mustHaveType) {
80
- console.error(`Invalid token type during verification: ${t}, must be ${mustHaveType}`);
81
- return null;
82
- }
83
- if (pk === null) {
84
- decoded.isRoot = true;
85
- }
86
- else {
87
- const dbUser = yield this.adminforth.getUserByPk(pk);
88
- decoded.dbUser = dbUser;
89
- }
90
- return decoded;
91
- });
92
- }
93
- static generatePasswordHash(password) {
94
- return __awaiter(this, void 0, void 0, function* () {
95
- const salt = generateSalt();
96
- const hashedPassword = yield calcPasswordHash(password, salt);
97
- return `${salt}:${hashedPassword}`;
98
- });
99
- }
100
- static verifyPassword(password, hashedPassword) {
101
- return __awaiter(this, void 0, void 0, function* () {
102
- const [salt, hash] = hashedPassword.split(':');
103
- const newHash = yield calcPasswordHash(password, salt);
104
- return newHash === hash;
105
- });
106
- }
107
- }
108
- export default AdminForthAuth;