Skip to content

Commit

Permalink
Fixed hardcoded email address
Browse files Browse the repository at this point in the history
  • Loading branch information
git-init-priyanshu committed Aug 7, 2024
1 parent 16defb4 commit db5060c
Show file tree
Hide file tree
Showing 19 changed files with 278 additions and 301 deletions.
33 changes: 24 additions & 9 deletions app/(auth)/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { JWTPayload, SignJWT, importJWK } from 'jose';
import bcrypt from 'bcryptjs';

import prisma from "@/prisma/prismaClient";
import { loginSchema, signinSchema } from './zodSchema';
import { signinSchema, signupSchema } from './zodSchema';

const generateJWT = async (payload: JWTPayload) => {
const secret = process.env.JWT_SECRET || 'secret';
Expand All @@ -23,7 +23,7 @@ const generateJWT = async (payload: JWTPayload) => {
return jwt;
};

export const SigninAction = async (data: z.infer<typeof signinSchema>) => {
export const SignupAction = async (data: z.infer<typeof signupSchema>) => {
try {
// User validation
const user = await prisma.user.findFirst({
Expand All @@ -40,15 +40,24 @@ export const SigninAction = async (data: z.infer<typeof signinSchema>) => {
const salt = await bcrypt.genSalt(Number(process.env.SALT) || 10);
const hashedPassword = await bcrypt.hash(data.password, salt);

const authToken = await generateJWT({ email: data.email });

await prisma.user.create({
data: {
const jwtPayload = {
id: user?.id,
email: data.email,
name: user?.name,
picture: user?.picture
}
const authToken = await generateJWT(jwtPayload);

await prisma.user.upsert({
where: { email: data.email },
update: {
password: hashedPassword
},
create: {
name: data.name,
username: data.username,
email: data.email,
password: hashedPassword,
isVerified: false,
}
})

Expand All @@ -62,7 +71,7 @@ export const SigninAction = async (data: z.infer<typeof signinSchema>) => {
}
}

export const LoginAction = async (data: z.infer<typeof loginSchema>) => {
export const SigninAction = async (data: z.infer<typeof signinSchema>) => {
try {
// User validation
const user = await prisma.user.findFirst({
Expand All @@ -82,7 +91,13 @@ export const LoginAction = async (data: z.infer<typeof loginSchema>) => {
error: "Invalid credentials",
}

const authToken = await generateJWT({ email: data.email });
const jwtPayload = {
id: user?.id,
email: data.email,
name: user?.name,
picture: user?.picture
}
const authToken = await generateJWT(jwtPayload);

// Setting the cookie
cookies().set('token', authToken, { httpOnly: true });
Expand Down
14 changes: 7 additions & 7 deletions app/(auth)/signin/components/LogInForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,22 @@ import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"

import { LoginAction } from "../../actions"
import { loginSchema } from '../../zodSchema'
import { SigninAction } from "../../actions"
import { signinSchema } from '../../zodSchema'
import { toast } from "sonner"


export default function LogInForm() {
const router = useRouter()

const { register, handleSubmit } = useForm<z.infer<typeof loginSchema>>();
const { register, handleSubmit } = useForm<z.infer<typeof signinSchema>>();

const submitForm = async (data: z.infer<typeof loginSchema>) => {
const parsedData = loginSchema.parse({
const submitForm = async (data: z.infer<typeof signinSchema>) => {
const parsedData = signinSchema.parse({
email: data.email,
password: data.password
})
const response = await LoginAction(parsedData);
const response = await SigninAction(parsedData);
if (response.success) {
toast.success("login completed")
router.push('/')
Expand Down Expand Up @@ -57,7 +57,7 @@ export default function LogInForm() {
/>
</div>
<Button type="submit" className="w-full bg-blue-500">
Login
Sign in
</Button>
</form>
)
Expand Down
14 changes: 7 additions & 7 deletions app/(auth)/signup/components/SignInForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,23 @@ import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { z } from 'zod'

import { signinSchema } from '../../zodSchema'
import { SigninAction } from '../../actions'
import { signupSchema } from '../../zodSchema'
import { SignupAction } from '../../actions'

export default function CredentialsForm() {
const router = useRouter();

const { register, handleSubmit } = useForm<z.infer<typeof signinSchema>>();
const { register, handleSubmit } = useForm<z.infer<typeof signupSchema>>();

const submitForm = async (data: z.infer<typeof signinSchema>) => {
const parsedData = signinSchema.parse({
const submitForm = async (data: z.infer<typeof signupSchema>) => {
const parsedData = signupSchema.parse({
name: data.name,
username: data.username,
email: data.email,
password: data.password
})

const response = await SigninAction(parsedData);
const response = await SignupAction(parsedData);
if (response.success) {
toast.success("Signin completed")
router.push('/')
Expand Down Expand Up @@ -68,7 +68,7 @@ export default function CredentialsForm() {
/>
</div>
<Button type="submit" className="w-full bg-blue-500">
Sign In
Sign up
</Button>
</form>
)
Expand Down
4 changes: 2 additions & 2 deletions app/(auth)/zodSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ const passwordValidation = new RegExp(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/
);

export const signinSchema = z.object({
export const signupSchema = z.object({
name: z.string().min(1).max(50),
username: z.string().min(1).max(20),
email: z.string().email(),
password: z.string().min(1).regex(passwordValidation)
})

export const loginSchema = z.object({
export const signinSchema = z.object({
email: z.string().email(),
password: z.string()
})
28 changes: 27 additions & 1 deletion app/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,32 @@
import prisma from "@/prisma/prismaClient"

export const GetAllDocs = async () => {
return await prisma.document.findMany({ orderBy: { updatedAt: 'desc' } });
try {
const response = await prisma.document.findMany(
{
select: {
id: true,
thumbnail: true,
name: true,
updatedAt: true,
users: {
select: {
user: {
select: {
name: true,
picture: true
}
}
}
},
},
orderBy: { updatedAt: 'desc' }
}
);
return response;
} catch (e) {
console.log(e);
return null;
}
}

45 changes: 36 additions & 9 deletions app/components/Card/Card.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client'

import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useCallback, useMemo, useRef, useState } from "react"
import { useRouter } from "next/navigation"

import {
Expand All @@ -15,27 +15,47 @@ import prettifyDate from '@/helpers/prettifyDates'
import CardOptions from "./components/Options"
import { debounce } from "lodash"
import { RenameDocument } from "./actions"
import useClientSession from "@/lib/customHooks/useClientSession"

type DocCardPropType = {
docId: string;
thumbnail: string | null;
title: string;
createdAt: Date
updatedAt: Date
users: {
user:
{
name: string,
picture: string | null
}
}[]
}
export default function DocCard({ docId, thumbnail, title, createdAt }: DocCardPropType) {
export default function DocCard({ docId, thumbnail, title, updatedAt, users }: DocCardPropType) {
const router = useRouter();

const session = useClientSession();

const inputRef = useRef<HTMLInputElement>(null);

const [name, setName] = useState(title)

const saveName = useCallback(async () => {
if (!inputRef.current) return;
await RenameDocument(docId, "bartwalpriyanshu@gmail.com", inputRef.current.value);
const email = session.email;
if (!email) return;

await RenameDocument(docId, email, inputRef.current.value);
}, [])

const debounceSaveName = useMemo(() => debounce(saveName, 2000), [saveName])

const getInitials = (name: string) => {
let initials = name.split(" ");

if (initials.length > 2) return initials[0][0] + initials[1][0];
return initials[0][0];
}

return (
<Card className="hover:shadow-lg" >
<CardContent
Expand All @@ -56,11 +76,18 @@ export default function DocCard({ docId, thumbnail, title, createdAt }: DocCardP
/>
<div className="flex items-center w-full justify-between">
<div className="flex gap-2 items-center">
<Avatar className="size-8">
<AvatarImage src="https://github.com/shadcn.png" />
<AvatarFallback>CN</AvatarFallback>
</Avatar>
<p className="text-neutral-600 cursor-default">{prettifyDate(String(createdAt))}</p>
{users.map((e, index) => {
return (
<Avatar key={index} className="size-8">
{
e.user.picture
? <AvatarImage src={e.user.picture} />
: <AvatarFallback>{getInitials(e.user.name)}</AvatarFallback>
}
</Avatar>
)
})}
<p className="text-neutral-600 cursor-default">{prettifyDate(String(updatedAt))}</p>
</div>
<CardOptions docId={docId} inputRef={inputRef} />
</div>
Expand Down
31 changes: 22 additions & 9 deletions app/components/Card/components/Options.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
import { Button } from "@/components/ui/button"

import { DeleteDocument } from "../actions"
import useClientSession from "@/lib/customHooks/useClientSession"

type CardOptionsPropType = {
docId: string,
Expand All @@ -33,6 +34,8 @@ type CardOptionsPropType = {
export default function CardOptions({ docId, inputRef }: CardOptionsPropType) {
const router = useRouter();

const session = useClientSession();

const docOptions = [
{ icon: Type, color: "#60b7c3", title: "Rename", onClick: () => renameDocument() },
{ icon: FilePenLine, color: "#48acf9", title: "Edit", onClick: () => editDocument() },
Expand All @@ -57,6 +60,17 @@ export default function CardOptions({ docId, inputRef }: CardOptionsPropType) {
setIsOptionsOpen(false);
setIsOpen(true);
}

const confirmDeleteDocument = async () => {
const email = session.email;
if (!email) return;
const response = await DeleteDocument(email, docId);
if (response.success) {
toast.success(response.data)
} else {
toast.error(response.error)
}
}
return (
<>
<Popover open={isOptionsOpen}>
Expand All @@ -69,7 +83,7 @@ export default function CardOptions({ docId, inputRef }: CardOptionsPropType) {
>
{docOptions.map((item) => {
return (
<Button variant="ghost" className="gap-2 justify-start" onClick={item.onClick}>
<Button id={item.title} variant="ghost" className="gap-2 justify-start" onClick={item.onClick}>
<item.icon size={20} color={item.color} strokeWidth={1.5} />
<p className="text-neutral-600">{item.title}</p>
</Button>
Expand All @@ -88,14 +102,13 @@ export default function CardOptions({ docId, inputRef }: CardOptionsPropType) {
</DialogHeader>
<div className="flex gap-4">
<Button variant="outline" onClick={() => setIsOpen(false)}>Cancel</Button>
<Button variant="destructive" onClick={async () => {
const response = await DeleteDocument("bartwalpriyanshu@gmail.com", docId)
if (response.success) {
toast.success(response.data)
} else {
toast.error(response.error)
}
}}>Confirm</Button>
<Button
variant="outline"
onClick={confirmDeleteDocument}
className="border-red-200 bg-red-100 hover:bg-red-200"
>
Confirm
</Button>
</div>
</DialogContent>
</Dialog>
Expand Down
14 changes: 9 additions & 5 deletions app/components/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Image from "next/image"
import { toast } from "sonner"
import { signOut, useSession } from 'next-auth/react'
import {
CloudUpload,
LogOut,
Expand All @@ -13,19 +13,23 @@ import {

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import logo from "@/public/doc.svg"
import { CreateNewDocument, LogoutAction } from "./actions"
import logo from "@/public/doc.svg"
import useClientSession from "@/lib/customHooks/useClientSession"

export default function Header() {
const router = useRouter();

const session = useSession();
const session = useClientSession();

const [isLoading, setIsLoading] = useState(false);

const createDocument = async () => {
setIsLoading(true);
const email = "bartwalpriyanshu@gmail.com"

const email = session.email;
if(!email) return;

const response = await CreateNewDocument(email)
if (response.success) {
setIsLoading(false);
Expand All @@ -41,7 +45,7 @@ export default function Header() {
const response = await LogoutAction();
if (response.success) {
toast.success("Successfully logged out")
router.push('/api/auth/signin')
router.push('/signup')
} else {
toast.error(response.error)
}
Expand Down
Loading

0 comments on commit db5060c

Please sign in to comment.