Skip to content

Commit

Permalink
feat: make Clerk auth in insights app
Browse files Browse the repository at this point in the history
  • Loading branch information
aliakseikrauchanka committed Dec 29, 2024
1 parent 692b983 commit 6c067a3
Show file tree
Hide file tree
Showing 11 changed files with 263 additions and 61 deletions.
28 changes: 20 additions & 8 deletions apps/insights-app/src/app/api/insights/route.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
import { utilFetch } from '@lifeis/common-ui';
import { getAuth } from '@clerk/nextjs/server';
import { Client } from '@notionhq/client';
import { NextRequest, NextResponse } from 'next/server';
import { PageObjectResponse } from '@notionhq/client/build/src/api-endpoints';

export const GET = async (): Promise<Response> => {
const response = await utilFetch(`/insights`, {
method: 'GET',
});
const notion = new Client({ auth: process.env.NEXT_NOTION_API_KEY });
const insightsDatabaseId = 'caae7cadc59c43fe920dd5ce4048dade';

export const GET = async (req: NextRequest, res: NextResponse) => {
const { userId } = getAuth(req);

if (!response.ok) {
throw new Error('Failed to get logs');
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

return response;
const response = await notion.databases.query({
database_id: insightsDatabaseId,
});
// objects;
const insights = response.results.map((obj) =>
((obj as PageObjectResponse).properties.insight as any).title.map((title: any) => title.plain_text).join(', '),
);

return NextResponse.json(insights, { status: 200 });
};
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
'use client';

import React, { useEffect, useState } from 'react';
import { GET } from '../../api/insights/route';
// import { GET } from '../../api/insights/route';

export const AllInsights = () => {
const [insights, setInsights] = useState<string[]>([]);

useEffect(() => {
const fetchLogs = async () => {
const insightsResponse = await GET();
const insightsResponse = await fetch('/api/insights');
const insights = await insightsResponse.json();
setInsights(insights);
};
Expand Down
18 changes: 15 additions & 3 deletions apps/insights-app/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,22 @@ export const metadata = {
description: 'Generated by create-nx-workspace',
};

import { ClerkProvider, SignInButton, SignedIn, SignedOut, UserButton } from '@clerk/nextjs';

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
<ClerkProvider>
<html lang="en">
<body>
<SignedOut>
<SignInButton />
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
{children}
</body>
</html>
</ClerkProvider>
);
}
40 changes: 7 additions & 33 deletions apps/insights-app/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,13 @@
'use client';

import { init, isUserLoggedIn, UserSession } from '@lifeis/common-ui';
import { useEffect, useState } from 'react';

import { CONFIG } from '../config';
import { GoogleOAuthProvider } from '@react-oauth/google';
import { AllInsights } from './components/all-insights/all-insights';
import { auth, currentUser } from '@clerk/nextjs/server';

export default function Index() {
const [isLoggedIn, setIsLoggedIn] = useState(isUserLoggedIn());
const [isInitialized, setIsInitialized] = useState(false);

useEffect(() => {
init({
beUrl: CONFIG.BE_URL,
clientId: CONFIG.CLIENT_ID,
app: 'insights',
});
setIsInitialized(true);
}, []);
export default async function Index() {
// const { userId } = await auth();

return (
<GoogleOAuthProvider clientId={CONFIG.CLIENT_ID}>
<header>
<UserSession
isLoggedIn={isLoggedIn}
onLoginSuccess={() => setIsLoggedIn(true)}
onLogOut={() => setIsLoggedIn(false)}
/>
</header>
{isLoggedIn && isInitialized && (
<div>
<AllInsights />
</div>
)}
</GoogleOAuthProvider>
<div>
<AllInsights />
{/* {userId} */}
</div>
);
}
1 change: 0 additions & 1 deletion apps/insights-app/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export const CONFIG = {
BE_URL: `${process.env.NEXT_PUBLIC_BE || 'http://localhost:3000'}/api`,
CLIENT_ID: process.env.NEXT_PUBLIC_CLIENT_ID as string,
};
12 changes: 12 additions & 0 deletions apps/insights-app/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { clerkMiddleware } from '@clerk/nextjs/server';

export default clerkMiddleware();

export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always run for API routes
'/(api|trpc)(.*)',
],
};
4 changes: 3 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ services:
- ${INSIGHTS_PORT}:4200
environment:
- NEXT_PUBLIC_BE=${NGINX_DOMAIN}
- NEXT_PUBLIC_CLIENT_ID=${INSIGHTS_CLIENT_ID}
- NEXT_NOTION_API_KEY=${NOTION_API_KEY}
- NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=${NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY}
- CLERK_SECRET_KEY=${CLERK_SECRET_KEY}

volumes:
mono-node-modules: null
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@ export const UserSession = ({ isLoggedIn, isOfflineMode, onLoginSuccess, onLogOu
{isLoggedIn ? (
<div className={css.userSessionContent}>
<h2>
Welcome,{' '}
<span onClick={() => alert('Срочно! Только что было определено, что Серега Я - космический бульбозавт')}>
User
Velkommen!
</span>
!
</h2>
{!isOfflineMode && (
<div>
Expand Down
4 changes: 2 additions & 2 deletions libs/common-ui/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
interface IInitArgs {
beUrl: string;
clientId: string;
clientId?: string;
app?: string;
isOffline?: boolean;
}
Expand All @@ -12,7 +12,7 @@ export const CONFIG = {
isOffline: false,
};

export const init = ({ beUrl, clientId, app = '', isOffline = false }: IInitArgs) => {
export const init = ({ beUrl, clientId = '', app = '', isOffline = false }: IInitArgs) => {
CONFIG.BE_URL = beUrl;
CONFIG.CLIENT_ID = clientId;
CONFIG.APP = app;
Expand Down
Loading

0 comments on commit 6c067a3

Please sign in to comment.