Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/auth #129

Merged
merged 5 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
GITHUB_ID=""
GITHUB_SECRET=""
GOOGLE_CLIENT_ID=""
GOOGLE_CLIENT_SECRET=""
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="NEXTAUTH_SECRET"
6 changes: 6 additions & 0 deletions apps/web/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import NextAuth from "next-auth";
import { authOptions } from "../../../../lib/auth";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
1 change: 1 addition & 0 deletions apps/web/app/assets/github.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 apps/web/app/assets/google.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 13 additions & 4 deletions apps/web/app/auth/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
"use client";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import React from "react";
import { authOptions } from "../../lib/auth";
import Signin from "../../components/Signin";

import { Signin } from "@repo/ui/pages";
const SigninPage = async () => {
const session = await getServerSession(authOptions);

export default function () {
if (session?.user) {
redirect("/");
}
return <Signin />;
}
};

export default SigninPage;
5 changes: 1 addition & 4 deletions apps/web/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@ export default function RootLayout({ children }: { children: React.ReactNode }):
<html lang="en" suppressHydrationWarning>
<body className={cn("min-h-screen bg-background font-sans antialiased", fontSans.variable)}>
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
<Providers>
<Auth />
{children}
</Providers>
<Providers>{children}</Providers>
</ThemeProvider>
</body>
</html>
Expand Down
5 changes: 1 addition & 4 deletions apps/web/components/AppbarClient.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
"use client";

import { useRecoilValue } from "recoil";
import { userAtom } from "@repo/store";
import { Appbar } from "@repo/ui/components";
import { Track, Problem } from "@prisma/client";

export const AppbarClient = ({ tracks }: { tracks: (Track & { problems: Problem[] })[] }) => {
const user = useRecoilValue(userAtom);
return <Appbar user={user} tracks={tracks} />;
return <Appbar tracks={tracks} />;
};
9 changes: 6 additions & 3 deletions apps/web/components/Providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@ import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { type ThemeProviderProps } from "next-themes/dist/types";
import { ToastProvider } from "@repo/ui/toast";
import { SessionProvider } from "next-auth/react";

export const Providers = ({ children }: { children: React.ReactNode }) => {
return (
<RecoilRoot>
<ToastProvider>{children}</ToastProvider>
</RecoilRoot>
<SessionProvider>
<RecoilRoot>
<ToastProvider>{children}</ToastProvider>
</RecoilRoot>
</SessionProvider>
);
};

Expand Down
62 changes: 62 additions & 0 deletions apps/web/components/Signin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"use client";
import GoogleIcon from "../app/assets/google.svg";
import GithubIcon from "../app/assets/github.svg";
import { signIn } from "next-auth/react";
const Signin = () => {
return (
<div className="flex bg-black">
<div className="w-full md:w-2/5 bg-black flex justify-center items-center h-screen max-sm:hidden max-md:hidden">
<div>
<h1 className="text-4xl font-bold mb-4 text-white">Daily Code</h1>
<div className="grid grid-cols-3 gap-4">
{[...Array(9)].map((_, index) => (
<div key={index} className="opacity-50">
<i className="fas fa-arrow-down fa-3x"></i>
</div>
))}
</div>
</div>
</div>
<div className="w-full h-screen md:w-3/5 bg-gray-900 flex justify-center items-center">
<div className="w-full max-w-md">
<div className="p-5">
<h2 className="text-2xl font-semibold mb-2 text-white text-center">Log In</h2>
</div>
<div className=" mb-4 justify-center py-1 sm:px-6 lg:px-8 ">
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-white py-12 px-4 shadow sm:rounded-lg sm:px-10">
<div className="flex flex-col items-center justify-center gap-4">
<p className="font-normal text-2xl text-gray-900">Welcome</p>

<p className="font-light text-sm text-gray-600">Log in to continue to DailyCode.</p>
<button
type="submit"
className="w-full flex justify-center items-center gap-2 py-3 px-4 border rounded font-light text-md text-gray-900 hover:bg-gray-200 focus:outline-none focus:ring-2 "
onClick={async () => {
await signIn("google");
}}
>
<img src={GoogleIcon.src} className="w-5 h-5 mr-2" />
Continue with Google
</button>
<button
className="w-full flex justify-center items-center gap-2 py-3 px-4 border rounded font-light text-md text-gray-900 hover:bg-gray-200 focus:outline-none focus:ring-2 -mt-2"
onClick={async () => {
await signIn("github");
}}
>
<img src={GithubIcon.src} className="w-5 h-5 mr-2" />
Continue with Github
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export { GithubIcon };

export default Signin;
41 changes: 41 additions & 0 deletions apps/web/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
import type { Adapter } from "next-auth/adapters";
import { SessionStrategy } from "next-auth";

const prisma = new PrismaClient();

export const authOptions = {
adapter: PrismaAdapter(prisma) as Adapter,
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID || "",
clientSecret: process.env.GITHUB_SECRET || "",
allowDangerousEmailAccountLinking: true,
}),
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID || "",
clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
allowDangerousEmailAccountLinking: true,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was giving an error OAuthAccountNotLinked, when logging in from google, logging out and again logging with github, this is the solution I find to avoid the error. Let me know if it's a known error to you @hkirat and if there is any other way to solve it.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its because - the gmail account is the same , so it gives error

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, correct

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can ignore for now

}),
],
secret: process.env.NEXTAUTH_SECRET || "secr3t",
pages: {
signIn: "/auth",
},
session: { strategy: "jwt" as SessionStrategy },
callbacks: {
async jwt({ token }: any) {
return token;
},
async session({ session, token }: any) {
if (token) {
session.accessToken = token.accessToken;
session.user.id = token.sub;
}
return session;
},
},
};
3 changes: 3 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@
"lint:fix": "eslint --fix ."
},
"dependencies": {
"@auth/prisma-adapter": "^1.5.2",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very smart decision using this

"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-slot": "^1.0.2",
"@repo/db": "*",
"@repo/ui": "*",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"firebase": "^10.7.1",
"next": "^14.0.4",
"next-auth": "^4.24.7",
"next-themes": "^0.2.1",
"notion-client": "^6.16.0",
"react": "^18.2.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
Warnings:

- You are about to drop the column `password` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `username` on the `User` table. All the data in the column will be lost.
- A unique constraint covering the columns `[email]` on the table `User` will be added. If there are existing duplicate values, this will fail.

*/
-- AlterTable
ALTER TABLE "User" DROP COLUMN "password",
DROP COLUMN "username",
ADD COLUMN "email" TEXT,
ADD COLUMN "emailVerified" TIMESTAMP(3),
ADD COLUMN "image" TEXT,
ADD COLUMN "name" TEXT;

-- CreateTable
CREATE TABLE "Account" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"provider" TEXT NOT NULL,
"providerAccountId" TEXT NOT NULL,
"refresh_token" TEXT,
"refresh_token_expires_in" INTEGER,
"access_token" TEXT,
"expires_at" INTEGER,
"token_type" TEXT,
"scope" TEXT,
"id_token" TEXT,
"session_state" TEXT,

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

-- CreateTable
CREATE TABLE "Session" (
"id" TEXT NOT NULL,
"sessionToken" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"expires" TIMESTAMP(3) NOT NULL,

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

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

-- CreateIndex
CREATE UNIQUE INDEX "Account_provider_providerAccountId_key" ON "Account"("provider", "providerAccountId");

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

-- CreateIndex
CREATE UNIQUE INDEX "VerificationToken_token_key" ON "VerificationToken"("token");

-- CreateIndex
CREATE UNIQUE INDEX "VerificationToken_identifier_token_key" ON "VerificationToken"("identifier", "token");

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

-- 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;
57 changes: 49 additions & 8 deletions packages/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,50 @@ datasource db {
url = env("DATABASE_URL")
}

model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? @db.Text
refresh_token_expires_in Int?
access_token String? @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? @db.Text
session_state String?

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([provider, providerAccountId])
}

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

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

model VerificationToken {
identifier String
token String @unique
expires DateTime

@@unique([identifier, token])
}

model Track {
Expand Down Expand Up @@ -56,11 +96,12 @@ enum ProblemType {
Code
MCQ
}

model MCQQuestion {
id String @id @default(uuid())
question String
options String[]
id String @id @default(uuid())
question String
options String[]
correctOption String
problem Problem @relation(fields: [problemId], references: [id])
problem Problem @relation(fields: [problemId], references: [id])
problemId String
}
}
Loading