sample-oauth2-discord-telegram-svelte Svelte Themes

Sample Oauth2 Discord Telegram Svelte

Discord & Telegram OAuth2 Integration

A SvelteKit application demonstrating Discord and Telegram OAuth2 integration with JWT authentication.

Features

  • Discord OAuth2: Connect Discord accounts with optional guild membership verification
  • Telegram OAuth: Connect Telegram accounts using Login Widget with data verification
  • JWT Authentication: Secure token-based authentication with access and refresh tokens
  • Referral System: Support for referral codes during account connection
  • TypeScript: Fully typed implementation
  • Responsive UI: Modern, responsive interface with Tailwind CSS

API Endpoints

Discord OAuth2

  • GET /api/auth/discord/auth-url?redirectUri=... - Get Discord authorization URL
  • POST /api/auth/connect/discord - Connect Discord account

Telegram OAuth

  • GET /api/auth/telegram/widget-config - Get Telegram widget configuration
  • POST /api/auth/connect/telegram - Connect Telegram account

Setup

1. Install Dependencies

npm install

2. Environment Configuration

Copy .env.example to .env and configure your OAuth credentials:

cp .env.example .env

3. Discord Setup

  1. Go to Discord Developer Portal
  2. Create a new application
  3. Go to OAuth2 settings
  4. Add redirect URI: http://localhost:8000/auth/discord/callback
  5. Copy Client ID and Client Secret to your .env file

Optional: For guild membership verification:

  1. Create a bot in your application
  2. Add the bot to your Discord server
  3. Copy Bot Token and Guild ID to your .env file

4. Telegram Setup

  1. Create a bot using @BotFather
  2. Use /setdomain command to set your domain: localhost
  3. Copy Bot Token and Bot Username to your .env file

Optional: For channel membership verification:

  1. Add your bot to the Telegram channel as an admin
  2. Copy Channel ID to your .env file

5. JWT Configuration

Generate a secure JWT secret:

node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"

Add this to your .env file as JWT_SECRET.

Development

Start the development server:

npm run dev

# or start the server and open the app in a new browser tab
npm run dev -- --open

Building

To create a production version of your app:

npm run build

You can preview the production build with npm run preview.

Project Structure

src/
├── lib/
│   ├── components/auth/     # OAuth UI components
│   ├── services/           # Business logic services
│   ├── types/             # TypeScript type definitions
│   └── config.ts          # Environment configuration
├── routes/
│   ├── api/auth/          # API endpoints
│   ├── auth/              # OAuth callback pages
│   └── +page.svelte       # Demo page
└── app.html               # HTML template

Usage Examples

Frontend Integration

<script>
  import DiscordOAuth from '$lib/components/auth/DiscordOAuth.svelte';
  import TelegramOAuth from '$lib/components/auth/TelegramOAuth.svelte';

  function handleSuccess(result) {
    console.log('User authenticated:', result);
    // Store tokens and redirect user
  }

  function handleError(error) {
    console.error('Authentication failed:', error);
  }
</script>

<DiscordOAuth
  onSuccess={handleSuccess}
  onError={handleError}
  referralCode="optional-referral"
/>

<TelegramOAuth
  onSuccess={handleSuccess}
  onError={handleError}
  referralCode="optional-referral"
/>

API Usage

// Get Discord auth URL
const response = await fetch('/api/auth/discord/auth-url?redirectUri=http://localhost:5173/callback');
const { authUrl } = await response.json();

// Connect Discord account
const response = await fetch('/api/auth/connect/discord', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    code: 'discord_oauth_code',
    redirectUri: 'http://localhost:5173/callback',
    referralCode: 'optional'
  })
});

// Connect Telegram account
const response = await fetch('/api/auth/connect/telegram', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    id: 123456789,
    first_name: 'John',
    username: 'johndoe',
    auth_date: 1640995200,
    hash: 'telegram_hash',
    referralCode: 'optional'
  })
});

Security Features

  • HMAC Verification: Telegram data is verified using HMAC-SHA256
  • Token Expiration: JWT tokens have configurable expiration times
  • Guild/Channel Verification: Optional membership verification for Discord/Telegram
  • CSRF Protection: State parameter support for Discord OAuth
  • Input Validation: Comprehensive request validation

License

MIT

Top categories

Loading Svelte Themes