Skip to content

Commit

Permalink
added google auth
Browse files Browse the repository at this point in the history
  • Loading branch information
sifat0666 committed Aug 31, 2022
1 parent 6a41839 commit 14d144b
Show file tree
Hide file tree
Showing 12 changed files with 158 additions and 20 deletions.
16 changes: 11 additions & 5 deletions components/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,26 @@ import React from 'react'
import { FaShoppingCart } from 'react-icons/fa'
import {SiAnalogue} from 'react-icons/si'
import {MdKeyboardArrowDown} from 'react-icons/md'
import useAuthStore from '../store/authStore'





const Navbar = () => {


const {data: user} = useQuery(['user'], () => axios.get('http://localhost:3000/api/user', {withCredentials: true}).then(res => res.data))

const {userProfile, addUser, removeUser} : any = useAuthStore()

// console.log(user)

console.log('user',user)
// console.log('user',user)

return (
<div className='flex items-center justify-between p-6 border-b-2 border-gray-200'>
<Link href='/'>
<div className='flex items-center px-6 pr-12 text-3xl'>
<div className='flex items-center px-6 text-3xl cursor-pointer'>
<SiAnalogue />
<p className='p-2 texl-xl'>Ecom</p>
</div>
Expand All @@ -28,7 +34,7 @@ const Navbar = () => {
</div>
<div className='flex items-center justify-between px-6'>
<div>
{user?.name ? (
{userProfile.name ? (
<div className='flex items-center gap-2 p-1 rounded-lg cursor-pointer hover:bg-light-gray' onClick={() => {}}>
<img
className='w-8 h-8 rounded-full'
Expand All @@ -37,7 +43,7 @@ const Navbar = () => {
/>
<p>
<span className='text-gray-400 text-14'>Hi, </span>
<span className='ml-1 font-bold text-gray-400 text-14'>{user?.name}</span>
<span className='ml-1 font-bold text-gray-400 text-14'>{userProfile?.name}</span>
<MdKeyboardArrowDown className='text-gray-400 text-14' />
</p>
</div>
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"argon2": "^0.29.1",
"axios": "^0.27.2",
"cookie": "^0.5.0",
"csstype": "^3.1.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"next": "12.2.5",
Expand All @@ -24,7 +25,8 @@
"react-hook-form": "^7.34.2",
"react-hot-toast": "^2.3.0",
"react-icons": "^4.4.0",
"zod": "^3.18.0"
"zod": "^3.18.0",
"zustand": "^4.1.1"
},
"devDependencies": {
"@types/cookie": "^0.5.1",
Expand Down
15 changes: 15 additions & 0 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,33 @@ import '../styles/globals.css'
import type { AppProps } from 'next/app'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import Navbar from '../components/Navbar'
import { GoogleOAuthProvider } from '@react-oauth/google'
import { useEffect, useState } from 'react'

function MyApp({ Component, pageProps }: AppProps) {



const [isSSR, setIsSSR] = useState(true)

useEffect(()=> {
setIsSSR(false)
}, [])

if(isSSR) return null


const queryClient = new QueryClient()



return(
<GoogleOAuthProvider clientId={process.env.NEXT_PUBLIC_GOOGLE_API_TOKEN!}>
<QueryClientProvider client={queryClient}>
<Navbar />
<Component {...pageProps} />
</QueryClientProvider>
</GoogleOAuthProvider>
)
}

Expand Down
31 changes: 31 additions & 0 deletions pages/api/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { NextApiRequest, NextApiResponse } from 'next';
import prisma from '../../../lib/prisma';



export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if(req.method === 'POST') {
const user = req.body

// console.log(user)

// const findUser = await prisma.user.findUnique({where: {email : user.email}})

const upsertUser = await prisma.user.upsert({
where: {
email: user.email
},
update: {
email: user.email
},
create: user
})

console.log(upsertUser)





}
}
3 changes: 2 additions & 1 deletion pages/api/auth/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
path: '/'
})

const response = omit(user, "password")

res.setHeader('Set-Cookie', serialsed)

res.status(200).json({message: 'success'})
res.status(200).json({ ...response ,message: 'success'})

}
6 changes: 4 additions & 2 deletions pages/api/auth/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default async function(req: NextApiRequest, res: NextApiResponse){

const newUser = await prisma.user.create({
data: {
email, password: hash, name
email, password: hash, name, type: 'user'
}
})

Expand All @@ -35,9 +35,11 @@ export default async function(req: NextApiRequest, res: NextApiResponse){
path: '/'
})

const response = omit(newUser, 'password')


res.setHeader('Set-Cookie', serialsed)
res.json({message: 'success'})
res.json({...response, message: 'success'})
} catch (error) {
console.log(error)
}
Expand Down
5 changes: 5 additions & 0 deletions pages/auth/login.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import axios from 'axios'
import { omit } from 'lodash';
import { useRouter } from 'next/router'
import React from 'react'
import { useForm, SubmitHandler } from 'react-hook-form'
import useAuthStore from '../../store/authStore';

type Inputs = {
email: string,
Expand All @@ -13,6 +15,7 @@ const Login = () => {

const {register, handleSubmit, formState: {errors}} = useForm<Inputs>()
const router = useRouter()
const {addUser} = useAuthStore()


const onSubmit: SubmitHandler<Inputs> = async value => {
Expand All @@ -25,7 +28,9 @@ const Login = () => {
console.log("res", res)
const data = res.data
if(data.message === 'success'){
addUser(data)
router.push('/')
router.reload()
}
})
.then(err => console.log('err',err));
Expand Down
20 changes: 16 additions & 4 deletions pages/auth/register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/router';
import { SubmitHandler, useForm } from 'react-hook-form';
import axios from 'axios';
import { GoogleLogin } from '@react-oauth/google';
import { createOrGetUser } from '../../utils';
import useAuthStore from '../../store/authStore';


type Inputs = {
Expand Down Expand Up @@ -37,6 +40,8 @@ const createUserSchema = object({

const Register = () => {

const {addUser} = useAuthStore()


const {register, handleSubmit, formState: {errors}} = useForm<Inputs>({
resolver: zodResolver(createUserSchema)
Expand All @@ -53,10 +58,13 @@ const Register = () => {
value,
{ withCredentials: true }
).then(res => {
console.log("res", res)
// console.log("res", res)
const data = res.data
// console.log(data)
if(data.message === 'success'){
addUser(data)
router.push('/')
router.reload()
}
})
.then(err => console.log('err',err));
Expand All @@ -73,9 +81,13 @@ const Register = () => {

<div className="w-full h-full bg-gray-50 dark:bg-gray-900">
<div className="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0">
<a href="#" className="flex items-center mb-6 text-2xl font-semibold text-gray-900 dark:text-white">
googleLogin
</a>
<div className="flex items-center mb-6 text-2xl font-semibold text-gray-900 dark:text-white">
<GoogleLogin
onSuccess={response => createOrGetUser(response)}
onError={() => console.log('err')}

/>
</div>
<div className="w-full bg-white rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700">
<div className="p-6 space-y-4 md:space-y-6 sm:p-8">
<h1 className="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white">
Expand Down
31 changes: 26 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ datasource db {
}

model User {
id Int @id @default(autoincrement())
id String @id @default(cuid())
email String @unique
name String?
password String
password String?
picture String?
type String?
}
22 changes: 22 additions & 0 deletions store/authStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import create from "zustand";
import {persist} from 'zustand/middleware'





const authStore = (set: any) => ({
userProfile: null,
addUser: (user: any) => set({userProfile: user}),
removeUser: () => set({userProfile: null}),
})

const useAuthStore = create(
persist(authStore, {
name: 'auth'
})
)

export default useAuthStore
Loading

0 comments on commit 14d144b

Please sign in to comment.