main 6f65be579def cached
35 files
23.5 KB
7.6k tokens
4 symbols
1 requests
Download .txt
Repository: halitsever/nuxt-telegram-auth
Branch: main
Commit: 6f65be579def
Files: 35
Total size: 23.5 KB

Directory structure:
gitextract_7hlm4j7g/

├── .editorconfig
├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       ├── ci.yml
│       └── docs.yaml
├── .gitignore
├── .npmignore
├── .npmrc
├── .prettierrc
├── .vscode/
│   └── settings.json
├── CHANGELOG.md
├── LICENSE
├── README.md
├── docs/
│   ├── .vitepress/
│   │   └── config.ts
│   ├── index.md
│   ├── installation.md
│   └── properties.md
├── eslint.config.mjs
├── package.json
├── playground/
│   ├── app.vue
│   ├── nuxt.config.ts
│   ├── package.json
│   ├── server/
│   │   └── tsconfig.json
│   └── tsconfig.json
├── src/
│   ├── module.ts
│   └── runtime/
│       ├── app/
│       │   └── composables/
│       │       └── session.ts
│       ├── components/
│       │   └── TelegramLoginWidget.vue
│       ├── server/
│       │   ├── api/
│       │   │   └── telegram/
│       │   │       ├── session.delete.ts
│       │   │       └── session.get.ts
│       │   └── tsconfig.json
│       └── types/
│           └── session.ts
├── test/
│   ├── basic.test.ts
│   └── fixtures/
│       └── basic/
│           ├── app.vue
│           ├── nuxt.config.ts
│           └── package.json
└── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
root = true

[*]
indent_size = 2
indent_style = space
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false


================================================
FILE: .github/dependabot.yml
================================================
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file

version: 2
updates:
  - package-ecosystem: "npm" # See documentation for possible values
    directory: "/" # Location of package manifests
    schedule:
      interval: "weekly"


================================================
FILE: .github/workflows/ci.yml
================================================
name: ci

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  lint:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
      - run: corepack enable
      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install dependencies
        run: npx nypm@latest i

      - name: Lint
        run: npm run lint

  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
      - run: corepack enable
      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install dependencies
        run: npx nypm@latest i

      - name: Prepare For Dev
        run: npm run dev:prepare

      - name: Test
        run: npm run test


================================================
FILE: .github/workflows/docs.yaml
================================================
# Sample workflow for building and deploying a VitePress site to GitHub Pages
#
name: Deploy VitePress site to Pages

on:
  # Runs on pushes targeting the `main` branch. Change this to `master` if you're
  # using the `master` branch as the default branch.
  push:
    branches: [main]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
  contents: read
  pages: write
  id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
  group: pages
  cancel-in-progress: false

jobs:
  # Build job
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0 # Not needed if lastUpdated is not enabled
      # - uses: pnpm/action-setup@v2 # Uncomment this if you're using pnpm
      # - uses: oven-sh/setup-bun@v1 # Uncomment this if you're using Bun
      - name: Setup Node
        uses: actions/setup-node@v3
        with:
          node-version: 18
          cache: npm # or pnpm / yarn
      - name: Setup Pages
        uses: actions/configure-pages@v5
      - name: Install dependencies
        run: npm ci # or pnpm install / yarn install / bun install
      - name: Build with VitePress
        run: |
          npm run docs:build # or pnpm docs:build / yarn docs:build / bun run docs:build
          touch docs/.vitepress/dist/.nojekyll
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: docs/.vitepress/dist

  # Deployment job
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    needs: build
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4


================================================
FILE: .gitignore
================================================
# Dependencies
node_modules

# Logs
*.log*

# Temp directories
.temp
.tmp
.cache

# Yarn
**/.yarn/cache
**/.yarn/*state*

# Generated dirs
dist

# Nuxt
.nuxt
.output
.data
.vercel_build_output
.build-*
.netlify

# Env
.env

# Testing
reports
coverage
*.lcov
.nyc_output

# VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets

# Intellij idea
*.iml
.idea

# OSX
.DS_Store
.AppleDouble
.LSOverride
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk


# Vitepress
/docs/.vitepress/cache 

================================================
FILE: .npmignore
================================================
/docs

================================================
FILE: .npmrc
================================================
shamefully-hoist=true
strict-peer-dependencies=false


================================================
FILE: .prettierrc
================================================
{
  "tabWidth": 2,
  "useTabs": false,
  "printWidth": 220
}


================================================
FILE: .vscode/settings.json
================================================
{
  "eslint.experimental.useFlatConfig": true
}


================================================
FILE: CHANGELOG.md
================================================
# Changelog

## v1.2.6

[compare changes](https://github.com/halitsever/nuxt-telegram-auth/compare/v1.2.5...v1.2.6)

### 🩹 Fixes

- **session.get:** Handle nullish telegram token ([bb97043](https://github.com/halitsever/nuxt-telegram-auth/commit/bb97043))

### ❤️ Contributors

- Halit Sever ([@halitsever](https://github.com/halitsever))

## v1.2.5

[compare changes](https://github.com/halitsever/nuxt-telegram-auth/compare/v1.2.4...v1.2.5)

### 🩹 Fixes

- Remove module options ([b721fd6](https://github.com/halitsever/nuxt-telegram-auth/commit/b721fd6))

### ❤️ Contributors

- Halit Sever ([@halitsever](https://github.com/halitsever))

## v1.2.4

[compare changes](https://github.com/halitsever/nuxt-telegram-auth/compare/v1.2.3...v1.2.4)

### 📖 Documentation

- Update docs workflow ([bd91510](https://github.com/halitsever/nuxt-telegram-auth/commit/bd91510))

### 🏡 Chore

- Upgrade dependency versions ([2765271](https://github.com/halitsever/nuxt-telegram-auth/commit/2765271))
- Add compatibilityDate to nuxt.config ([6760493](https://github.com/halitsever/nuxt-telegram-auth/commit/6760493))

### ❤️ Contributors

- Halit Sever ([@halitsever](https://github.com/halitsever))

## v1.2.3

[compare changes](https://github.com/halitsever/nuxt-telegram-auth/compare/v1.2.2...v1.2.3)

## v1.2.2

[compare changes](https://github.com/halitsever/nuxt-telegram-auth/compare/v1.2.0...v1.2.2)

### 🩹 Fixes

- 🐛 eslint integration ([3c9754f](https://github.com/halitsever/nuxt-telegram-auth/commit/3c9754f))
- 🐛 test workflow ([34d20d8](https://github.com/halitsever/nuxt-telegram-auth/commit/34d20d8))
- 🐛 typo prepare:dev => dev:prepare ([da26bc3](https://github.com/halitsever/nuxt-telegram-auth/commit/da26bc3))
- **telegramloginwidget:** Update btoa function for utf8 ([a3ce167](https://github.com/halitsever/nuxt-telegram-auth/commit/a3ce167))

### 📖 Documentation

- ✏️ update features section ([fc44579](https://github.com/halitsever/nuxt-telegram-auth/commit/fc44579))
- ✏️ update features section ([fcf1c1e](https://github.com/halitsever/nuxt-telegram-auth/commit/fcf1c1e))
- Update image aligments ([dd39167](https://github.com/halitsever/nuxt-telegram-auth/commit/dd39167))

### 🏡 Chore

- 🤖 add npm run lint to release script ([269ced5](https://github.com/halitsever/nuxt-telegram-auth/commit/269ced5))
- **deps-dev:** Bump nuxt from 3.12.3 to 3.12.4 ([168e5e5](https://github.com/halitsever/nuxt-telegram-auth/commit/168e5e5))
- **deps-dev:** Bump serve-static from 1.15.0 to 1.16.2 ([ae66e1f](https://github.com/halitsever/nuxt-telegram-auth/commit/ae66e1f))
- **deps-dev:** Bump @types/node from 20.14.10 to 22.7.4 ([bd9663d](https://github.com/halitsever/nuxt-telegram-auth/commit/bd9663d))
- **deps-dev:** Bump vite from 5.3.5 to 5.4.8 ([b1149f4](https://github.com/halitsever/nuxt-telegram-auth/commit/b1149f4))
- **deps-dev:** Bump @nuxt/schema from 3.12.4 to 3.13.2 ([1c62687](https://github.com/halitsever/nuxt-telegram-auth/commit/1c62687))
- **deps-dev:** Bump eslint from 9.6.0 to 9.12.0 ([3418ff4](https://github.com/halitsever/nuxt-telegram-auth/commit/3418ff4))
- **deps-dev:** Bump vitest from 1.6.0 to 2.1.2 ([3bb8589](https://github.com/halitsever/nuxt-telegram-auth/commit/3bb8589))
- **deps-dev:** Bump rollup from 3.29.4 to 3.29.5 ([7551df1](https://github.com/halitsever/nuxt-telegram-auth/commit/7551df1))
- **deps-dev:** Bump vue-tsc from 2.0.26 to 2.1.6 ([4340bea](https://github.com/halitsever/nuxt-telegram-auth/commit/4340bea))
- **package.json:** Bump nuxt to 3.17.1 ([d4e28b5](https://github.com/halitsever/nuxt-telegram-auth/commit/d4e28b5))

### ❤️ Contributors

- Halit Sever ([@halitsever](http://github.com/halitsever))


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2024 Halit Sever

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
<p align="center" class="logo-section">
<img src="https://i.ibb.co/MMcBdPN/nuxt-telegram-auth.png" height="80" width="80"/>
</br>
<img src="https://halitsever-api.vercel.app/api/repo-title?title=Nuxt%20Telegram%20Auth">

<p align="center">
🔐 A telegram login widget integration for nuxt 3
<br>
<br/>
<br/>
<img src="https://img.shields.io/github/sponsors/halitsever"/>
</p>
<p align="center">
<a align="center" href="https://halitsever.github.io/nuxt-telegram-auth">Documentation</a>
  </p>
</p>

<p align="center">
<img src="https://halitsever-api.vercel.app/api/details"/>
</p>

- 😌 [**Easy Integration**](#) - A telegram bot and this module enough for telegram login widget
- 🔒 [**Auth Endpoint**](#) - Nuxt Telegram Module provides a api endpoint for checking is user's cookie valid or not: /api/telegram/session, this method integrated from official <a href="https://gist.github.com/anonymous/6516521b1fb3b464534fbc30ea3573c2">example php code</a>
  <p align="center" >
  <img src="https://halitsever-api.vercel.app/api/installation"/>
  </p>

Installation:

```bash
npx nuxi module add nuxt-telegram-auth
```

Then you need add TELEGRAM_TOKEN to your runtimeConfig:

```javascript
runtimeConfig: {
  TELEGRAM_TOKEN: "my_fancy_bot_token",
}
```

after that you can try on a page:

```javascript

<template>
  <div>
    <div>
      <div v-if="session.loggedIn">
        <NuxtLink @click="logout" to="/">Logout</NuxtLink>
        <a>Hey you are logged in!</a>
        <p>Session: {{ session }}</p>
      </div>
      <div v-else>
        <TelegramLoginWidget telegram-login="my_bot" @callback="testCallback" />
      </div>
    </div>
  </div>
</template>

<script setup>
const { clearSession, session } = useUserSession();
const logout = () => clearSession();
const testCallback = (user) => {
  console.log("Custom callback function: ",user);
};
</script>
```

for more detailed information, please check the documentation page.

<p align="center" href="https://github.com/halitsever/nuxt-telegram-auth/issues">
<img src="https://halitsever-api.vercel.app/api/issue"/>
</p>

<p align="center">
<img src="https://halitsever-api.vercel.app/api/sponsor"/>
</p>

<p align="center">
<img src="https://halitsever-api.vercel.app/api/license"/>
</p>

<p align="center">
  MIT LICENSE | <a href="https://halit.org">Halit Sever</a>
</p>


================================================
FILE: docs/.vitepress/config.ts
================================================
import { defineConfig } from "vitepress";

// https://vitepress.dev/reference/site-config
export default defineConfig({
  title: "Nuxt Telegram Auth",
  description: "Effortlessly integrate the Telegram login widget into your Nuxt 3 application with our easy-to-use npm package, enhancing user authentication and engagement.",

  base: "/nuxt-telegram-auth/",

  themeConfig: {
    // https://vitepress.dev/reference/default-theme-config
    nav: [
      { text: "Home", link: "/" },
      { text: "Quick Start", link: "/installation" },
    ],

    sidebar: [
      {
        text: "Documentation",
        items: [
          { text: "Quickstart", link: "/installation" },
          { text: "Properties", link: "/properties" },
        ],
      },
    ],

    socialLinks: [{ icon: "github", link: "https://github.com/halitsever/nuxt-telegram-auth" }],
  },
});


================================================
FILE: docs/index.md
================================================
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home

hero:
  name: "Nuxt Telegram Auth"

  tagline: 🔐 Telegram login widget integration for Nuxt 3
  actions:
    - theme: brand
      text: Documentation
      link: /installation
    - theme: alt
      text: Github
      link: https://github.com/halitsever/nuxt-telegram-auth
  image:
    src: /telegram-logo.png
    alt: Nuxt Telegram Auth
---


================================================
FILE: docs/installation.md
================================================
# Installation

First of all you need a telegram bot, if you don't know to how to create a telegram bot please check this <a href="https://core.telegram.org/bots#how-do-i-create-a-bot">link</a>.

# Step 1:

Install the module:

```bash
npx nuxi module add nuxt-telegram-auth
```

# Step 2:

You need grab bot token from telegram, you can get your bot's token from Bot_Father:
<img src="/telegram-token.png"/>

Then add your nuxt.config.ts file:

```javascript
runtimeConfig: {
  TELEGRAM_TOKEN: "my_fancy_bot_token",
}
```

also you need allow your domain on Bot_Father otherwise you will get "Invalid Domain" error.

<img src="/domain.png"/>

After that you can use `TelegramLoginWidget` component:

```javascript
<template>
  <div>
    <div>
      <div v-if="session.loggedIn">
        <NuxtLink @click="logout" to="/">Logout</NuxtLink>
        <a>Hey you are logged in!</a>
        <p>Session: {{ session }}</p>
      </div>
      <div v-else>
        <TelegramLoginWidget telegram-login="my_bot" @callback="testCallback" />
      </div>
    </div>
  </div>
</template>

<script setup>
const { clearSession, session } = useUserSession();
const logout = () => clearSession();
const testCallback = (user) => {
  console.log("Custom callback function: ",user);
};
</script>
```

`telegram-login` value should be your bot's name.

`@callback` emit is optional.


================================================
FILE: docs/properties.md
================================================
# Not documented for now


================================================
FILE: eslint.config.mjs
================================================
// @ts-check
import { createConfigForNuxt } from "@nuxt/eslint-config/flat";

// Run `npx @eslint/config-inspector` to inspect the resolved config interactively
export default createConfigForNuxt({
  features: {
    // Rules for module authors
    tooling: true,
    // Rules for formatting
    stylistic: false,
  },

  dirs: {
    src: ["./playground"],
  },
}).append([
  {
    ignores: ["docs/*"],
  },
]);


================================================
FILE: package.json
================================================
{
  "name": "nuxt-telegram-auth",
  "version": "1.2.6",
  "description": "🔐 Telegram login widget integration for Nuxt 3",
  "repository": "https://github.com/halitsever/nuxt-telegram-auth.git",
  "license": "MIT",
  "type": "module",
  "exports": {
    ".": {
      "import": "./dist/module.mjs"
    }
  },
  "main": "./dist/module.mjs",
  "files": [
    "dist"
  ],
  "scripts": {
    "prepack": "nuxt-module-build build",
    "dev": "nuxi dev playground --host",
    "dev:build": "nuxi build playground",
    "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
    "release": "npm run lint && npm run prettier && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags",
    "lint": "eslint .",
    "prettier": "prettier --write .",
    "test": "vitest run",
    "test:watch": "vitest watch",
    "test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
    "docs:dev": "vitepress dev docs",
    "docs:build": "vitepress build docs",
    "docs:preview": "vitepress preview docs"
  },
  "dependencies": {
    "@nuxt/kit": "^3.17.4"
  },
  "devDependencies": {
    "@nuxt/devtools": "^2.4.1",
    "@nuxt/eslint-config": "^1.4.1",
    "@nuxt/module-builder": "^1.0.1",
    "@nuxt/schema": "^3.17.4",
    "@nuxt/test-utils": "^3.19.1",
    "@types/node": "^22.15.21",
    "changelogen": "^0.6.1",
    "eslint": "^9.27.0",
    "nuxt": "^3.17.4",
    "prettier": "^3.5.3",
    "typescript": "latest",
    "vitepress": "^1.6.3",
    "vitest": "^3.1.4",
    "vue-tsc": "^2.2.10"
  },
  "optionalDependencies": {
    "@rollup/rollup-linux-x64-gnu": "^4.41.1"
  }
}


================================================
FILE: playground/app.vue
================================================
<template>
  <div>
    <div>
      <div v-if="session.loggedIn">
        <button @click="logout">Logout</button>
        <a>Hey you are logged in!</a>
        <p>Session: {{ session }}</p>
      </div>
      <div v-else>
        <TelegramLoginWidget telegram-login="my_bot" @callback="testCallback" />
      </div>
    </div>
  </div>
</template>

<script setup>
const { clearSession, session } = useUserSession();
const logout = () => clearSession();
const testCallback = (user) => {
  console.log("Custom callback function: ", user);
};
</script>


================================================
FILE: playground/nuxt.config.ts
================================================
export default defineNuxtConfig({
  modules: ["../src/module"],
  devtools: { enabled: true },
  compatibilityDate: "2025-05-26",
  runtimeConfig: {
    TELEGRAM_TOKEN: "my_fancy_bot_token",
  },
});


================================================
FILE: playground/package.json
================================================
{
  "private": true,
  "name": "nuxt-telegram-auth-playground",
  "type": "module",
  "scripts": {
    "dev": "nuxi dev",
    "build": "nuxi build",
    "generate": "nuxi generate"
  },
  "dependencies": {
    "nuxt": "^3.16.0"
  }
}


================================================
FILE: playground/server/tsconfig.json
================================================
{
  "extends": "../.nuxt/tsconfig.server.json"
}


================================================
FILE: playground/tsconfig.json
================================================
{
  "extends": "./.nuxt/tsconfig.json"
}


================================================
FILE: src/module.ts
================================================
import { defineNuxtModule, createResolver, addComponent, addServerHandler, addImportsDir } from "@nuxt/kit";

export default defineNuxtModule({
  meta: {
    name: "nuxt-telegram-auth",
    configKey: "telegramAuth",
  },

  defaults: {},
  setup(_options, _nuxt) {
    const resolver = createResolver(import.meta.url);

    addImportsDir(resolver.resolve("./runtime/app/composables"));

    addComponent({
      name: "TelegramLoginWidget",
      filePath: resolver.resolve("runtime/components/TelegramLoginWidget.vue"),
    });

    addServerHandler({
      handler: resolver.resolve("runtime/server/api/telegram/session.get"),
      route: "/api/telegram/session",
      method: "get",
    });

    addServerHandler({
      handler: resolver.resolve("runtime/server/api/telegram/session.delete"),
      route: "/api/telegram/session",
      method: "delete",
    });
  },
});


================================================
FILE: src/runtime/app/composables/session.ts
================================================
import { useAsyncData, useRequestFetch, useState } from "nuxt/app";
import type { ITelegramSession, IUserSession } from "../../types/session";

export const useSessionState = () => useState("telegram-session", () => ({}));

export function useUserSession(): IUserSession {
  fetchSession();
  const session = useSessionState();
  return { session, clearSession };
}

export const clearSession = async () => {
  await $fetch("/api/telegram/session", { method: "DELETE" });
  useSessionState().value = { loggedIn: false };
};

export const fetchSession = async () => {
  const sessionState = useSessionState();
  const { data } = await useAsyncData<ITelegramSession>("telegram_auth", () => useRequestFetch()("/api/telegram/session"));
  sessionState.value = data;
};


================================================
FILE: src/runtime/components/TelegramLoginWidget.vue
================================================
<template>
  <div id="telegram" />
</template>

<script setup>
import { onMounted } from "vue";
import { fetchSession } from "../app/composables/session";
import { useCookie } from "#app";

const props = defineProps({
  mode: {
    type: String,
    default: "callback",
  },
  telegramLogin: {
    type: String,
    required: true,
  },
  redirectUrl: {
    type: String,
    default: "",
  },
  requestAccess: {
    type: String,
    default: "read",
  },
  size: {
    type: String,
    default: "medium",
  },
  userpic: {
    type: Boolean,
    default: true,
  },
  radius: {
    default: "0",
    type: String,
  },
});

const emit = defineEmits(["callback", "loaded"]);

const userCookie = useCookie("tg_user", {
  maxAge: 60 * 60 * 24,
  secure: process.env.NODE_ENV === "production",
  sameSite: "lax",
});

const setCookie = (payload) => {
  userCookie.value = btoa(String.fromCharCode(...new TextEncoder("utf-8").encode(JSON.stringify(payload))));
};

function onTelegramAuth(payload) {
  setCookie(payload);
  fetchSession();
  emit("callback", payload);
}

onMounted(() => {
  if (import.meta.client) {
    const script = document.createElement("script");
    script.async = true;
    script.src = "https://telegram.org/js/telegram-widget.js?3";

    script.setAttribute("data-telegram-login", props.telegramLogin);
    script.setAttribute("data-request-access", props.requestAccess);
    script.setAttribute("data-size", props.size);
    script.setAttribute("data-userpic", props.userpic);

    if (props.radius) script.setAttribute("data-radius", props.radius);

    if (props.mode === "callback") {
      window.onTelegramAuth = onTelegramAuth;
      script.setAttribute("data-onauth", "window.onTelegramAuth(user)");
    } else {
      script.setAttribute("data-auth-url", props.redirectUrl);
    }

    document.querySelector("#telegram").appendChild(script);
    emit("loaded");
  }
});
</script>


================================================
FILE: src/runtime/server/api/telegram/session.delete.ts
================================================
import { eventHandler, deleteCookie } from "h3";

export default eventHandler(async (event) => {
  try {
    deleteCookie(event, "tg_user");
    return { status: 200, message: "Session Deleted" };
  } catch (err) {
    console.error("Telegram Auth - ", err);
    return { status: 500, message: "Interval Server Error" };
  }
});


================================================
FILE: src/runtime/server/api/telegram/session.get.ts
================================================
import { eventHandler, getCookie } from "h3";
// @ts-expect-error nitro aliases aren't registered
import { useRuntimeConfig } from "#internal/nitro";
import * as crypto from "node:crypto";

const handleUnauthorized = () => {
  return {
    loggedIn: false,
    status: 401,
    message: "Unauthorized",
  };
};

export default eventHandler(async (event) => {
  try {
    const session = getCookie(event, "tg_user");

    const runtimeConfig = useRuntimeConfig(event);

    if (!session) return handleUnauthorized();

    const decodedCookie = JSON.parse(Buffer.from(session, "base64").toString("utf-8"));

    if (Date.now() / 1000 - decodedCookie.auth_date > 86400) return handleUnauthorized();

    const telegramApiToken = runtimeConfig.TELEGRAM_TOKEN;

    if (!telegramApiToken) return {
      loggedIn: false,
      status: 500,
      body: "Telegram bot token is not configured",
    };

    const secret = crypto.createHash("sha256").update(telegramApiToken).digest();

    /*
        This part creates a data-check-string in here as referred in documentation
        and then it checks on the server side if the hash is correct.
        Docs: https://core.telegram.org/widgets/login#checking-authorization
    */

    const dataCheckString = [];
    for (const key in decodedCookie) if (key != "hash") dataCheckString.push(key + "=" + decodedCookie[key]);

    const check_hash = crypto.createHmac("sha256", secret).update(dataCheckString.sort().join("\n")).digest("hex");

    return {
      loggedIn: check_hash == decodedCookie.hash,
      ...decodedCookie,
    };
  } catch (err) {
    console.error("Telegram Auth - ", err);
    return {
      loggedIn: false,
      status: 500,
      body: "Internal Server Error",
    };
  }
});


================================================
FILE: src/runtime/server/tsconfig.json
================================================
{
  "extends": "../../../.nuxt/tsconfig.server.json"
}


================================================
FILE: src/runtime/types/session.ts
================================================
import type { Ref } from "vue";

export interface ITelegramSession {
  loggedIn: boolean;
  status: number;
  id?: number;
  message?: string;
  first_name?: string;
  username?: string;
  photo_url?: string;
  auth_date?: Date;
  hash?: string;
}

export interface IUserSession {
  session: ITelegramSession | Ref<null>;
  clearSession: () => Promise<void>;
}


================================================
FILE: test/basic.test.ts
================================================
import { fileURLToPath } from "node:url";
import { describe, it, expect } from "vitest";
import { setup, $fetch } from "@nuxt/test-utils/e2e";

describe("ssr", async () => {
  await setup({
    rootDir: fileURLToPath(new URL("./fixtures/basic", import.meta.url)),
  });

  it("renders the index page", async () => {
    // Get response to a server-rendered page with `$fetch`.
    const html = await $fetch("/");
    expect(html).toContain("<div>basic</div>");
  });
});


================================================
FILE: test/fixtures/basic/app.vue
================================================
<template>
  <div>basic</div>
</template>

<script setup></script>


================================================
FILE: test/fixtures/basic/nuxt.config.ts
================================================
import NuxtTelegramAuth from "../../../src/module";

export default defineNuxtConfig({
  modules: [NuxtTelegramAuth],
});


================================================
FILE: test/fixtures/basic/package.json
================================================
{
  "private": true,
  "name": "basic",
  "type": "module"
}


================================================
FILE: tsconfig.json
================================================
{
  "extends": "./.nuxt/tsconfig.json",
  "exclude": ["dist", "node_modules", "playground"]
}
Download .txt
gitextract_7hlm4j7g/

├── .editorconfig
├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       ├── ci.yml
│       └── docs.yaml
├── .gitignore
├── .npmignore
├── .npmrc
├── .prettierrc
├── .vscode/
│   └── settings.json
├── CHANGELOG.md
├── LICENSE
├── README.md
├── docs/
│   ├── .vitepress/
│   │   └── config.ts
│   ├── index.md
│   ├── installation.md
│   └── properties.md
├── eslint.config.mjs
├── package.json
├── playground/
│   ├── app.vue
│   ├── nuxt.config.ts
│   ├── package.json
│   ├── server/
│   │   └── tsconfig.json
│   └── tsconfig.json
├── src/
│   ├── module.ts
│   └── runtime/
│       ├── app/
│       │   └── composables/
│       │       └── session.ts
│       ├── components/
│       │   └── TelegramLoginWidget.vue
│       ├── server/
│       │   ├── api/
│       │   │   └── telegram/
│       │   │       ├── session.delete.ts
│       │   │       └── session.get.ts
│       │   └── tsconfig.json
│       └── types/
│           └── session.ts
├── test/
│   ├── basic.test.ts
│   └── fixtures/
│       └── basic/
│           ├── app.vue
│           ├── nuxt.config.ts
│           └── package.json
└── tsconfig.json
Download .txt
SYMBOL INDEX (4 symbols across 3 files)

FILE: src/module.ts
  method setup (line 10) | setup(_options, _nuxt) {

FILE: src/runtime/app/composables/session.ts
  function useUserSession (line 6) | function useUserSession(): IUserSession {

FILE: src/runtime/types/session.ts
  type ITelegramSession (line 3) | interface ITelegramSession {
  type IUserSession (line 15) | interface IUserSession {
Condensed preview — 35 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (27K chars).
[
  {
    "path": ".editorconfig",
    "chars": 188,
    "preview": "root = true\n\n[*]\nindent_size = 2\nindent_style = space\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ni"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 525,
    "preview": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where "
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 764,
    "preview": "name: ci\n\non:\n  push:\n    branches:\n      - main\n  pull_request:\n    branches:\n      - main\n\njobs:\n  lint:\n    runs-on: "
  },
  {
    "path": ".github/workflows/docs.yaml",
    "chars": 2055,
    "preview": "# Sample workflow for building and deploying a VitePress site to GitHub Pages\n#\nname: Deploy VitePress site to Pages\n\non"
  },
  {
    "path": ".gitignore",
    "chars": 580,
    "preview": "# Dependencies\nnode_modules\n\n# Logs\n*.log*\n\n# Temp directories\n.temp\n.tmp\n.cache\n\n# Yarn\n**/.yarn/cache\n**/.yarn/*state*"
  },
  {
    "path": ".npmignore",
    "chars": 5,
    "preview": "/docs"
  },
  {
    "path": ".npmrc",
    "chars": 53,
    "preview": "shamefully-hoist=true\nstrict-peer-dependencies=false\n"
  },
  {
    "path": ".prettierrc",
    "chars": 61,
    "preview": "{\n  \"tabWidth\": 2,\n  \"useTabs\": false,\n  \"printWidth\": 220\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 48,
    "preview": "{\n  \"eslint.experimental.useFlatConfig\": true\n}\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 3669,
    "preview": "# Changelog\n\n## v1.2.6\n\n[compare changes](https://github.com/halitsever/nuxt-telegram-auth/compare/v1.2.5...v1.2.6)\n\n###"
  },
  {
    "path": "LICENSE",
    "chars": 1068,
    "preview": "MIT License\n\nCopyright (c) 2024 Halit Sever\n\nPermission is hereby granted, free of charge, to any person obtaining a cop"
  },
  {
    "path": "README.md",
    "chars": 2331,
    "preview": "<p align=\"center\" class=\"logo-section\">\n<img src=\"https://i.ibb.co/MMcBdPN/nuxt-telegram-auth.png\" height=\"80\" width=\"80"
  },
  {
    "path": "docs/.vitepress/config.ts",
    "chars": 863,
    "preview": "import { defineConfig } from \"vitepress\";\n\n// https://vitepress.dev/reference/site-config\nexport default defineConfig({\n"
  },
  {
    "path": "docs/index.md",
    "chars": 418,
    "preview": "---\n# https://vitepress.dev/reference/default-theme-home-page\nlayout: home\n\nhero:\n  name: \"Nuxt Telegram Auth\"\n\n  taglin"
  },
  {
    "path": "docs/installation.md",
    "chars": 1360,
    "preview": "# Installation\n\nFirst of all you need a telegram bot, if you don't know to how to create a telegram bot please check thi"
  },
  {
    "path": "docs/properties.md",
    "chars": 25,
    "preview": "# Not documented for now\n"
  },
  {
    "path": "eslint.config.mjs",
    "chars": 411,
    "preview": "// @ts-check\nimport { createConfigForNuxt } from \"@nuxt/eslint-config/flat\";\n\n// Run `npx @eslint/config-inspector` to i"
  },
  {
    "path": "package.json",
    "chars": 1668,
    "preview": "{\n  \"name\": \"nuxt-telegram-auth\",\n  \"version\": \"1.2.6\",\n  \"description\": \"🔐 Telegram login widget integration for Nuxt 3"
  },
  {
    "path": "playground/app.vue",
    "chars": 549,
    "preview": "<template>\n  <div>\n    <div>\n      <div v-if=\"session.loggedIn\">\n        <button @click=\"logout\">Logout</button>\n       "
  },
  {
    "path": "playground/nuxt.config.ts",
    "chars": 200,
    "preview": "export default defineNuxtConfig({\n  modules: [\"../src/module\"],\n  devtools: { enabled: true },\n  compatibilityDate: \"202"
  },
  {
    "path": "playground/package.json",
    "chars": 234,
    "preview": "{\n  \"private\": true,\n  \"name\": \"nuxt-telegram-auth-playground\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"nuxi dev\""
  },
  {
    "path": "playground/server/tsconfig.json",
    "chars": 49,
    "preview": "{\n  \"extends\": \"../.nuxt/tsconfig.server.json\"\n}\n"
  },
  {
    "path": "playground/tsconfig.json",
    "chars": 41,
    "preview": "{\n  \"extends\": \"./.nuxt/tsconfig.json\"\n}\n"
  },
  {
    "path": "src/module.ts",
    "chars": 879,
    "preview": "import { defineNuxtModule, createResolver, addComponent, addServerHandler, addImportsDir } from \"@nuxt/kit\";\n\nexport def"
  },
  {
    "path": "src/runtime/app/composables/session.ts",
    "chars": 765,
    "preview": "import { useAsyncData, useRequestFetch, useState } from \"nuxt/app\";\nimport type { ITelegramSession, IUserSession } from "
  },
  {
    "path": "src/runtime/components/TelegramLoginWidget.vue",
    "chars": 1917,
    "preview": "<template>\n  <div id=\"telegram\" />\n</template>\n\n<script setup>\nimport { onMounted } from \"vue\";\nimport { fetchSession } "
  },
  {
    "path": "src/runtime/server/api/telegram/session.delete.ts",
    "chars": 329,
    "preview": "import { eventHandler, deleteCookie } from \"h3\";\n\nexport default eventHandler(async (event) => {\n  try {\n    deleteCooki"
  },
  {
    "path": "src/runtime/server/api/telegram/session.get.ts",
    "chars": 1746,
    "preview": "import { eventHandler, getCookie } from \"h3\";\n// @ts-expect-error nitro aliases aren't registered\nimport { useRuntimeCon"
  },
  {
    "path": "src/runtime/server/tsconfig.json",
    "chars": 55,
    "preview": "{\n  \"extends\": \"../../../.nuxt/tsconfig.server.json\"\n}\n"
  },
  {
    "path": "src/runtime/types/session.ts",
    "chars": 361,
    "preview": "import type { Ref } from \"vue\";\n\nexport interface ITelegramSession {\n  loggedIn: boolean;\n  status: number;\n  id?: numbe"
  },
  {
    "path": "test/basic.test.ts",
    "chars": 471,
    "preview": "import { fileURLToPath } from \"node:url\";\nimport { describe, it, expect } from \"vitest\";\nimport { setup, $fetch } from \""
  },
  {
    "path": "test/fixtures/basic/app.vue",
    "chars": 67,
    "preview": "<template>\n  <div>basic</div>\n</template>\n\n<script setup></script>\n"
  },
  {
    "path": "test/fixtures/basic/nuxt.config.ts",
    "chars": 122,
    "preview": "import NuxtTelegramAuth from \"../../../src/module\";\n\nexport default defineNuxtConfig({\n  modules: [NuxtTelegramAuth],\n})"
  },
  {
    "path": "test/fixtures/basic/package.json",
    "chars": 61,
    "preview": "{\n  \"private\": true,\n  \"name\": \"basic\",\n  \"type\": \"module\"\n}\n"
  },
  {
    "path": "tsconfig.json",
    "chars": 94,
    "preview": "{\n  \"extends\": \"./.nuxt/tsconfig.json\",\n  \"exclude\": [\"dist\", \"node_modules\", \"playground\"]\n}\n"
  }
]

About this extraction

This page contains the full source code of the halitsever/nuxt-telegram-auth GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 35 files (23.5 KB), approximately 7.6k tokens, and a symbol index with 4 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!