Skip to content

Commit

Permalink
fix sing in with google issue
Browse files Browse the repository at this point in the history
Signed-off-by: Amit Amrutiya <[email protected]>
  • Loading branch information
amitamrutiya committed Jun 29, 2024
1 parent 1421f26 commit 4bbe1bb
Show file tree
Hide file tree
Showing 18 changed files with 187 additions and 63 deletions.

This file was deleted.

8 changes: 0 additions & 8 deletions frontend/prisma/migrations/20240628055448_add/migration.sql

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
Warnings:
- You are about to drop the `users` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE "chats" DROP CONSTRAINT "chats_userId_fkey";

-- DropTable
DROP TABLE "users";

-- CreateTable
CREATE TABLE "user" (
"_id" TEXT NOT NULL,
"email" TEXT,
"password" TEXT,
"username" TEXT,
"fullname" TEXT,
"profile_image" TEXT,
"bio" TEXT NOT NULL DEFAULT 'Hey there! I am available on ChatApp',
"phone_number" TEXT,
"friends" TEXT[],
"is_online" BOOLEAN NOT NULL DEFAULT false,
"is_verified" BOOLEAN NOT NULL DEFAULT false,
"verifyCode" TEXT,
"verifyCodeExpiry" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,

CONSTRAINT "user_pkey" PRIMARY KEY ("_id")
);

-- CreateIndex
CREATE UNIQUE INDEX "user_email_key" ON "user"("email");

-- CreateIndex
CREATE UNIQUE INDEX "user_username_key" ON "user"("username");

-- CreateIndex
CREATE UNIQUE INDEX "user_phone_number_key" ON "user"("phone_number");

-- AddForeignKey
ALTER TABLE "chats" ADD CONSTRAINT "chats_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("_id") ON DELETE SET NULL ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-- 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,
"access_token" TEXT,
"expires_at" INTEGER,
"token_type" TEXT,
"scope" TEXT,
"id_token" TEXT,
"session_state" TEXT,

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

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

-- AddForeignKey
ALTER TABLE "Account" ADD CONSTRAINT "Account_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("_id") ON DELETE CASCADE ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "chats" ALTER COLUMN "senderId" SET DATA TYPE TEXT,
ALTER COLUMN "receiverId" SET DATA TYPE TEXT;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
Warnings:
- You are about to drop the column `fullname` on the `user` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "user" DROP COLUMN "fullname",
ADD COLUMN "name" TEXT;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
Warnings:
- You are about to drop the column `profile_image` on the `user` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "user" DROP COLUMN "profile_image",
ADD COLUMN "image" TEXT;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
Warnings:
- You are about to drop the column `is_verified` on the `user` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "user" DROP COLUMN "is_verified",
ADD COLUMN "emailVerified" BOOLEAN NOT NULL DEFAULT false;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
Warnings:
- The `emailVerified` column on the `user` table would be dropped and recreated. This will lead to data loss if there is data in the column.
*/
-- AlterTable
ALTER TABLE "user" DROP COLUMN "emailVerified",
ADD COLUMN "emailVerified" TIMESTAMP(3);
54 changes: 37 additions & 17 deletions frontend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,50 @@ datasource db {
}

model User {
id String @id @default(uuid())
email String @unique
password String
username String @unique
fullname String
profile_image String?
bio String @default("Hey there! I am available on ChatApp")
phone_number String? @unique
id String @id @default(uuid()) @map("_id")
email String? @unique
password String?
username String? @unique
name String?
image String?
bio String @default("Hey there! I am available on ChatApp")
phone_number String? @unique
friends String[]
is_online Boolean @default(false)
is_verified Boolean @default(false)
verifyCode String
verifyCodeExpiry DateTime
is_online Boolean @default(false)
emailVerified DateTime?
verifyCode String?
verifyCodeExpiry DateTime?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
chats Chat[]
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
Account Account[]
@@map("users")
@@map("user")
}

model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? @db.Text
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 Chat {
id Int @id @default(autoincrement())
senderId Int
receiverId Int
senderId String
receiverId String
message String
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/actions/check-username-unique.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ export async function checkUsernameUnique(
const existingVerifiedUser = await db.user.findFirst({
where: {
username,
is_verified: true,
emailVerified: {
not: null,
},
},
});

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/actions/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function login(values: z.infer<typeof signInSchema>) {
return { success: false, message: "Email does not exist!" };
}

if (!existingUser.is_verified) {
if (!existingUser.emailVerified) {
return {
success: false,
message: "Email not verified. First verify email",
Expand Down
12 changes: 7 additions & 5 deletions frontend/src/actions/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ export async function register(values: z.infer<typeof signUpSchema>) {
const existingUserVerifiedByUsername = await db.user.findFirst({
where: {
username,
is_verified: true,
emailVerified: {
not: null,
},
},
});

Expand All @@ -37,7 +39,7 @@ export async function register(values: z.infer<typeof signUpSchema>) {
expiryDate.setMinutes(expiryDate.getMinutes() + 10);
const verifyCode = Math.floor(100000 + Math.random() * 900000).toString();

if (existingUserByEmail && existingUserByEmail.is_verified) {
if (existingUserByEmail && existingUserByEmail.emailVerified) {
// existingUserByEmail.password = hashedPassword;
// existingUserByEmail.verifyCode = verifyCode;
// existingUserByEmail.verifyCodeExpiry = expiryDate;
Expand All @@ -52,12 +54,12 @@ export async function register(values: z.infer<typeof signUpSchema>) {
const newUser = await db.user.create({
data: {
email,
fullname,
name: fullname,
password: hashedPassword,
username: username,
profile_image: `https://api.dicebear.com/5.x/initials/svg?seed=${firstName}+${lastName}`,
image: `https://api.dicebear.com/5.x/initials/svg?seed=${firstName}+${lastName}`,
is_online: true,
is_verified: false,
emailVerified: new Date(),
verifyCode: verifyCode,
verifyCodeExpiry: expiryDate,
friends: [],
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/actions/verify-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export async function verifyCode(value: verifyCodeType) {
id: user.id,
},
data: {
is_verified: true,
emailVerified: new Date(),
},
});

Expand Down
37 changes: 22 additions & 15 deletions frontend/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,24 @@ export const {
signIn,
signOut,
} = NextAuth({
events: {
async linkAccount({ user }) {
await db.user.update({
where: {
id: user.id,
},
data: {
emailVerified: new Date(),
},
});
},
},
callbacks: {
async signIn({ account, profile, user }) {
if (account?.provider === "google") {
console.log("profile", profile);
return !!profile?.email_verified;
}
if (account?.provider !== "credentials") return true;

const existingUser: User | null = await getUserById(user.id!);
console.log("existingUser", existingUser);
if (!existingUser || !existingUser.is_verified) {
if (!existingUser || !existingUser.emailVerified) {
return false;
}
return true;
Expand All @@ -30,11 +37,10 @@ export const {
if (token.sub) {
session.user.id = token.sub;
}
session.user.is_verified = token.is_verified;
session.user.username = token.username;
// @ts-ignore
session.user.fullname = token.name;
session.user.profile_image = token.profile_image;
session.user.name = token.name;
session.user.image = token.image;
session.user.bio = token.bio;
session.user.phone_number = token.phone_number;
session.user.is_online = token.is_online;
Expand All @@ -50,14 +56,15 @@ export const {
const existingUser = await getUserById(token.sub);
if (!existingUser) return token;

token.name = existingUser.fullname;
token.email = existingUser.email;
token.username = existingUser.username;
if (existingUser.email && existingUser.username && existingUser.name) {
token.name = existingUser.name;
token.email = existingUser.email;
token.username = existingUser.username;
}
token.bio = existingUser.bio;
token.is_online = existingUser.is_online;
token.is_verified = existingUser.is_verified;
token.username = existingUser.username;
token.picture = existingUser.profile_image;
token.emailVerified = existingUser.emailVerified;
if (existingUser.image) token.image = existingUser.image;
return token;
},
},
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const Navbar = async () => {
<>
<UserAvatar
username={user?.name || user?.email || "Someone"}
src={user?.profile_image || ""}
src={user?.image || ""}
height={40}
width={40}
/>
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/components/RoomNavbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ const RoomNavbar: React.FC<RoomNavbarProps> = (props) => {
<div>
<div className="mx-5 mt-4 flex items-center text-white">
<UserAvatar
username={user?.fullname || user.email || "Someone"}
src={user?.profile_image || ""}
username={user?.name || user.email || "Someone"}
src={user?.image || ""}
height={40}
width={40}
/>
Expand All @@ -52,7 +52,7 @@ const RoomNavbar: React.FC<RoomNavbarProps> = (props) => {
<>
<UserAvatar
username={user?.username || user?.email || "Someone"}
src={user?.profile_image || ""}
src={user?.image || ""}
height={40}
width={40}
/>
Expand Down
15 changes: 6 additions & 9 deletions frontend/src/types/next-auth.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import { JWT } from "next-auth/jwt";
declare module "next-auth" {
interface User {
_id?: string;
is_verified?: boolean;
username?: string;
email?: string;
fullname?: string;
profile_image?: string;
name?: string;
image?: string;
bio?: string;
phone_number?: string;
is_online?: boolean;
Expand All @@ -18,11 +17,10 @@ declare module "next-auth" {
interface Session {
user: {
_id?: string;
is_verified?: boolean;
username?: string;
email?: string;
fullname?: string;
profile_image?: string;
name?: string;
image?: string;
bio?: string;
phone_number?: string;
is_online?: boolean;
Expand All @@ -33,11 +31,10 @@ declare module "next-auth" {
declare module "next-auth/jwt" {
interface JWT {
_id?: string;
is_verified?: boolean;
username?: string;
email?: string;
fullname?: string;
profile_image?: string;
name?: string;
image?: string;
bio?: string;
phone_number?: string;
is_online?: boolean;
Expand Down

0 comments on commit 4bbe1bb

Please sign in to comment.