Skip to content

Commit

Permalink
Update examples (#21)
Browse files Browse the repository at this point in the history
* Update remix deps

* Update all deps

* Add next-auth app router example

* Update workflows

* Fix lints

* Clean up

* Update pnpm-lock.yaml
  • Loading branch information
manzoorwanijk authored Jan 28, 2024
1 parent 68dad47 commit 5d7eb0c
Show file tree
Hide file tree
Showing 22 changed files with 1,130 additions and 642 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/changeset-version.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ jobs:
with:
node-version: 'lts/*'

- uses: pnpm/action-setup@v2
name: Install pnpm
- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 8
run_install: false
Expand Down
14 changes: 6 additions & 8 deletions .github/workflows/pr-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,23 @@ jobs:
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 18
node-version: lts/*

- uses: pnpm/action-setup@v2
name: Install pnpm
id: pnpm-install
- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
run_install: false

- name: Get pnpm store directory
id: pnpm-cache
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
Expand Down
16 changes: 16 additions & 0 deletions examples/next-auth-app-router/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = tab
indent_size = 4

[*.{yml,md}]
indent_style = space
indent_size = 2

[*.md]
trim_trailing_whitespace = false
5 changes: 5 additions & 0 deletions examples/next-auth-app-router/.example.env.local
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
NEXTAUTH_SECRET=KNUYErmsociervyeruonUIIi7yevre
NEXTAUTH_URL=https:https://something-here.ngrok.io

BOT_TOKEN=xXxXxXxXxXxXxXxXxXxXxXxX
BOT_USERNAME=SomeBotUsername
20 changes: 20 additions & 0 deletions examples/next-auth-app-router/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
.DS_Store

node_modules/
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.yarn-integrity
.npm

.eslintcache

*.tsbuildinfo
next-env.d.ts

.next
.vercel
.env*.local
43 changes: 43 additions & 0 deletions examples/next-auth-app-router/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# @telegram-auth next-auth App Router Example

- [NextAuth.js](https://next-auth.js.org/)

## Get Started

1. Clone the repository

```sh
git clone https://github.com/manzoorwanijk/telegram-auth.git
cd telegram-auth
```

2. Install and build dependencies

```sh
pnpm install
pnpm kick-off
```

3. Go to the "examples/next-auth-app-router" example folder

```sh
cd examples/next-auth-app-router
```

4. Create a `.env.local` file by copying `.example.env.local` and update `BOT_TOKEN` and `BOT_USERNAME` with your bot's token and username that you got from [@BotFather](https://t.me/BotFather).
5. Start the dev server
```sh
pnpm run dev
```
6. You may want to use [ngrok](https://ngrok.com/) to expose your local server to the internet.
```sh
ngrok http 3000
```
Copy the ngrok URL and update `NEXTAUTH_URL` in `.env.local` with it.
Don't forget to send `/setdomain` command to [@BotFather](https://t.me/BotFather) with the ngrok URL to fix the "Bot domain invalid" error.
49 changes: 49 additions & 0 deletions examples/next-auth-app-router/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import NextAuth, { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';

import { objectToAuthDataMap, AuthDataValidator } from '@telegram-auth/server';

export type User = {
id: string;
name: string;
image: string;
};

declare module 'next-auth' {
interface Session {
user: User;
}
}

export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
id: 'telegram-login',
name: 'Telegram Login',
credentials: {},
async authorize(credentials, req) {
const validator = new AuthDataValidator({
botToken: `${process.env.BOT_TOKEN}`,
});

const data = objectToAuthDataMap(req.query || {});
const user = await validator.validate(data);

if (user.id && user.first_name) {
return {
id: user.id.toString(),
name: [user.first_name, user.last_name || ''].join(' '),
image: user.photo_url,
};
}
return null;
},
}),
],
};

const handler = NextAuth(authOptions);

export const GET = handler;

export const POST = handler;
7 changes: 7 additions & 0 deletions examples/next-auth-app-router/app/auth-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use client';

import { SessionProvider } from 'next-auth/react';

export function AuthProvider({ children }: { children: React.ReactNode }) {
return <SessionProvider>{children}</SessionProvider>;
}
24 changes: 24 additions & 0 deletions examples/next-auth-app-router/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { ChakraProvider } from '@chakra-ui/react';

import type { Metadata } from 'next';
import { AuthProvider } from './auth-provider';
import { Info } from '../components/info';

export const metadata: Metadata = {
title: 'Telegram Auth',
};

export default function Layout({ children }: { children: React.ReactNode }) {
return (
<AuthProvider>
<html lang="en">
<body>
<ChakraProvider>
<Info botUsername={`${process.env.BOT_USERNAME}`} />
<main>{children}</main>
</ChakraProvider>
</body>
</html>
</AuthProvider>
);
}
22 changes: 22 additions & 0 deletions examples/next-auth-app-router/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { getServerSession } from 'next-auth';
import { authOptions } from './api/auth/[...nextauth]/route';
import { Box, Heading } from '@chakra-ui/react';

export default async function Home() {
const session = await getServerSession(authOptions);

if (!session) {
return (
<Box>
<Heading as="h1">Not logged in to see what is here</Heading>
</Box>
);
}

return (
<Box>
<Heading as="h1">You can see this because you are logged in.</Heading>
<pre>{JSON.stringify(session.user, null, 2)}</pre>
</Box>
);
}
72 changes: 72 additions & 0 deletions examples/next-auth-app-router/components/info.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
'use client';
import { Box, Button, Card, CardBody, CardFooter, Heading, Image, SkeletonText, Stack, Text } from '@chakra-ui/react';
import { LoginButton } from '@telegram-auth/react';
import { signIn, signOut, useSession } from 'next-auth/react';
import type { User } from '../app/api/auth/[...nextauth]/route';

function LoadingPlaceholder() {
return (
<Box padding="6" boxShadow="lg" bg="white">
<SkeletonText mt="4" noOfLines={4} spacing="4" skeletonHeight="2" />
</Box>
);
}

export function Info({ botUsername }: { botUsername: string }) {
const { data: session, status } = useSession();

if (status === 'loading') {
return <LoadingPlaceholder />;
}

const user = session?.user as User;

if (status === 'authenticated') {
return (
<Card direction={{ base: 'column', sm: 'row' }} overflow="hidden" variant="outline">
{user?.image ? (
<Image objectFit="contain" maxW={{ base: '100%', sm: '200px' }} src={user?.image} alt="" />
) : null}
<Stack>
<CardBody>
<Heading size="md">Hello</Heading>
<Text as="i">You are signed in as</Text>&nbsp;
<Text as="b">{user.name}</Text>
</CardBody>
<CardFooter>
<Button
variant="solid"
colorScheme="blue"
as="a"
onClick={() => {
signOut();
}}
>
{'Sign out'}
</Button>
</CardFooter>
</Stack>
</Card>
);
}

return (
<Card direction={{ base: 'column', sm: 'row' }} overflow="hidden" variant="outline">
<CardBody>
<Heading size="md">Hello</Heading>

<Text py="2">
<Text as="i">You are not signed in</Text>
</Text>
</CardBody>
<CardFooter>
<LoginButton
botUsername={botUsername}
onAuthCallback={(data) => {
signIn('telegram-login', { callbackUrl: '/' }, data as any);
}}
/>
</CardFooter>
</Card>
);
}
10 changes: 10 additions & 0 deletions examples/next-auth-app-router/next-auth.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import 'next-auth/jwt';

// Read more at: https://next-auth.js.org/getting-started/typescript#module-augmentation

declare module 'next-auth/jwt' {
interface JWT {
/** The user's role. */
userRole?: 'admin';
}
}
10 changes: 10 additions & 0 deletions examples/next-auth-app-router/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @type {import('next').NextConfig}
*/
const config = {
experimental: {
externalDir: true,
},
};

module.exports = config;
29 changes: 29 additions & 0 deletions examples/next-auth-app-router/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "@telegram-auth/example-next-auth-app-router",
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"clean": "rimraf .next .turbo",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@chakra-ui/react": "^2.8.2",
"@emotion/react": "^11",
"@emotion/styled": "^11",
"@telegram-auth/react": "*",
"@telegram-auth/server": "*",
"framer-motion": "^11",
"next": "^14.1.0",
"next-auth": "^4.24.5",
"nodemailer": "^6.9.8",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^20.11.9",
"@types/react": "^18.2.48",
"typescript": "^5.3.3"
}
}
1 change: 1 addition & 0 deletions examples/next-auth-app-router/public/next.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/next-auth-app-router/public/vercel.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions examples/next-auth-app-router/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"include": ["process.d.ts", "next-env.d.ts", "next-auth.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"compilerOptions": {
"target": "ES2019",
"lib": ["DOM", "DOM.Iterable", "ES2019"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
]
},
"exclude": ["node_modules", ".next"]
}
Loading

0 comments on commit 5d7eb0c

Please sign in to comment.