Skip to content

Commit

Permalink
Added AuthProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
erfanmola committed Oct 6, 2023
1 parent 86c187d commit 0a19b51
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import AppearanceProvider from "./providers/AppearanceProvider.vue";
import LocaleProvider from './providers/LocaleProvider.vue';
import AuthProvider from './providers/AuthProvider.vue';
import Switch from './components/Switch.vue';
import List from './components/List.vue';
import Checkbox from './components/Checkbox.vue';
Expand All @@ -8,6 +9,7 @@ import Section from './components/Section.vue';
export {
AppearanceProvider,
LocaleProvider,
AuthProvider,
Switch,
List,
Checkbox,
Expand Down
66 changes: 66 additions & 0 deletions src/providers/AuthProvider.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<script setup>
import { ref, provide } from 'vue';
import WebApp from '@twa-dev/sdk';
import hmac from 'js-crypto-hmac';
const props = defineProps({
bot_token: {
type: String,
required: true,
}
});
const clientAuthorized = ref(null);
const ksort = (obj) => {
const sortedKeys = Object.keys(obj).sort();
const sortedObj = {};
sortedKeys.forEach(key => {
sortedObj[key] = obj[key];
});
return sortedObj;
};
const buffer2Hex = (buffer) => {
return [...new Uint8Array(buffer)]
.map(x => x.toString(16).padStart(2, '0'))
.join('');
}
let initDataUnsafe = {...WebApp.initDataUnsafe};
let initDataHash = initDataUnsafe.hash;
let initDataString = '';
delete initDataUnsafe['hash'];
initDataUnsafe = ksort(initDataUnsafe);
initDataString = Object.entries(initDataUnsafe)
.map(([key, value]) => {
value = typeof value === 'object' ? JSON.stringify(value, null, 0) : value;
return `${key}=${value}`;
})
.join('\n');
hmac.compute(new TextEncoder().encode("WebAppData"), new TextEncoder().encode(props.bot_token), 'SHA-256').then((secret_key) => {
hmac.compute(secret_key, new TextEncoder().encode(initDataString), 'SHA-256').then((result) => {
clientAuthorized.value = buffer2Hex(result) === initDataHash;
});
});
</script>

<template>
<slot v-if="clientAuthorized" />
<slot v-else name="unauthorized">
Unauthorized Telegram Client
</slot>
</template>

<style lang="scss">
</style>

0 comments on commit 0a19b51

Please sign in to comment.