Skip to content

Commit

Permalink
feat: user-aut -> Added google auth
Browse files Browse the repository at this point in the history
  • Loading branch information
Hasnainahmad04 committed Aug 17, 2024
1 parent 89e9736 commit caba088
Show file tree
Hide file tree
Showing 13 changed files with 334 additions and 6 deletions.
5 changes: 5 additions & 0 deletions app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { handlers } from '@/auth';

export const { GET, POST } = handlers;

export const runtime = 'edge';
68 changes: 68 additions & 0 deletions app/sign-in/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { GithubIcon } from 'lucide-react';
import Image from 'next/image';
import React from 'react';

import { signIn } from '@/auth';
import { Button } from '@/components/ui/button';

const SignInPage = () => {
return (
<div className="mx-auto flex min-h-screen w-full flex-col items-center justify-between gap-10 bg-gray-50 px-10 pt-10 lg:flex-row">
<div className="flex flex-col items-center justify-center space-y-6 lg:w-1/2">
<h1 className="text-center text-3xl font-bold text-gray-800">
Welcome Back!
</h1>
<p className="text-balance text-center text-gray-600">
Sign in to access your personalized dashboard, manage your tasks, and
stay on top of your projects. Let&apos;s get started!
</p>
<Image
src="/sign-in-image.svg"
width={500}
height={500}
alt="hero"
className="max-w-sm"
/>
</div>

<div className="mx-auto flex flex-col items-center space-y-4 lg:w-96">
<h2 className="text-xl font-semibold text-gray-700">
Sign in to your account
</h2>
<form
className="w-full"
action={async () => {
'use server';

await signIn('google', { redirectTo: '/dashboard' });
}}
>
<Button
type="submit"
variant="outline"
className="inline-flex w-full justify-start border border-gray-300 text-center"
>
<Image
src="/google_icon.svg"
width={30}
height={30}
alt="google_icon"
className="mr-2"
/>
<span className="flex w-full justify-center text-gray-600">
Sign in with Google
</span>
</Button>
</form>
<Button className="inline-flex w-full justify-start bg-gray-800 text-center text-white">
<GithubIcon className="mr-2 size-6" />
<span className="flex w-full justify-center">
Sign in with Github
</span>
</Button>
</div>
</div>
);
};

export default SignInPage;
18 changes: 18 additions & 0 deletions auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { PrismaAdapter } from '@auth/prisma-adapter';
import NextAuth from 'next-auth';
import Github from 'next-auth/providers/github';
import Google from 'next-auth/providers/google';

import prisma from './prisma/client';

export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [Google, Github],
adapter: PrismaAdapter(prisma),
pages: { signIn: '/sign-in' },
session: { strategy: 'jwt' },
callbacks: {
authorized: async ({ auth: session }) => {
return !!session;
},
},
});
16 changes: 16 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server';

import { auth } from '@/auth';

export default auth((req) => {
if (!req.auth && !['/sign-in', '/'].includes(req.nextUrl.pathname)) {
const newUrl = new URL('/sign-in', req.nextUrl.origin);
return NextResponse.redirect(newUrl);
}

return NextResponse.next();
});

export const config = {
matcher: ['/dashboard/(.*)'],
};
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@
"node": ">=18.18.0"
},
"dependencies": {
"@auth/prisma-adapter": "^2.4.2",
"@dnd-kit/core": "^6.1.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^3.9.0",
"@prisma/client": "^5.17.0",
"@prisma/client": "5.18.0",
"@prisma/extension-accelerate": "^1.1.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-label": "^2.1.0",
Expand All @@ -34,6 +36,7 @@
"lucide-react": "^0.414.0",
"nanoid": "^5.0.7",
"next": "14.2.5",
"next-auth": "^5.0.0-beta.9",
"nextjs-toploader": "^1.6.12",
"prisma": "^5.17.0",
"react": "^18",
Expand Down
7 changes: 4 additions & 3 deletions prisma/client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { PrismaClient } from "@prisma/client";
import { PrismaClient } from '@prisma/client/edge';
import { withAccelerate } from '@prisma/extension-accelerate';

const prismaClientSingleton = () => {
return new PrismaClient();
return new PrismaClient().$extends(withAccelerate());
};

declare const globalThis: {
Expand All @@ -12,4 +13,4 @@ const prisma = globalThis.prismaGlobal ?? prismaClientSingleton();

export default prisma;

if (process.env.NODE_ENV !== "production") globalThis.prismaGlobal = prisma;
if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma;
61 changes: 61 additions & 0 deletions prisma/migrations/20240817143611_added_user_models/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"name" TEXT,
"email" TEXT NOT NULL,
"emailVerified" TIMESTAMP(3),
"image" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "Account" (
"userId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"provider" TEXT NOT NULL,
"providerAccountId" TEXT NOT NULL,
"refresh_token" TEXT,
"access_token" TEXT,
"expires_at" INTEGER,
"token_type" TEXT,
"scope" TEXT,
"id_token" TEXT,
"session_state" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Account_pkey" PRIMARY KEY ("provider","providerAccountId")
);

-- CreateTable
CREATE TABLE "Session" (
"sessionToken" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"expires" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL
);

-- CreateTable
CREATE TABLE "VerificationToken" (
"identifier" TEXT NOT NULL,
"token" TEXT NOT NULL,
"expires" TIMESTAMP(3) NOT NULL,

CONSTRAINT "VerificationToken_pkey" PRIMARY KEY ("identifier","token")
);

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");

-- CreateIndex
CREATE UNIQUE INDEX "Session_sessionToken_key" ON "Session"("sessionToken");

-- AddForeignKey
ALTER TABLE "Account" ADD CONSTRAINT "Account_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
13 changes: 13 additions & 0 deletions prisma/migrations/20240817154924_jugar/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
Warnings:
- The primary key for the `Account` table will be changed. If it partially fails, the table could be left without primary key constraint.
- You are about to drop the column `providerAccountId` on the `Account` table. All the data in the column will be lost.
- Added the required column `provider_account_id` to the `Account` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "Account" DROP CONSTRAINT "Account_pkey",
DROP COLUMN "providerAccountId",
ADD COLUMN "provider_account_id" TEXT NOT NULL,
ADD CONSTRAINT "Account_pkey" PRIMARY KEY ("provider", "provider_account_id");
13 changes: 13 additions & 0 deletions prisma/migrations/20240817155853_revert_jugar/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
Warnings:
- The primary key for the `Account` table will be changed. If it partially fails, the table could be left without primary key constraint.
- You are about to drop the column `provider_account_id` on the `Account` table. All the data in the column will be lost.
- Added the required column `providerAccountId` to the `Account` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "Account" DROP CONSTRAINT "Account_pkey",
DROP COLUMN "provider_account_id",
ADD COLUMN "providerAccountId" TEXT NOT NULL,
ADD CONSTRAINT "Account_pkey" PRIMARY KEY ("provider", "providerAccountId");
56 changes: 55 additions & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
generator client {
provider = "prisma-client-js"
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}

datasource db {
Expand Down Expand Up @@ -48,3 +49,56 @@ enum Label {
FEATURE
DOCUMENTATION
}

// users

model User {
id String @id @default(cuid())
name String?
email String @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Account {
userId String
type String
provider String
providerAccountId String
refresh_token String?
access_token String?
expires_at Int?
token_type String?
scope String?
id_token String?
session_state String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@id([provider, providerAccountId])
}

model Session {
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model VerificationToken {
identifier String
token String
expires DateTime
@@id([identifier, token])
}
1 change: 1 addition & 0 deletions public/google_icon.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 public/sign-in-image.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit caba088

Please sign in to comment.