Skip to content

Commit

Permalink
Merge pull request #6 from ptk1729/kukreja
Browse files Browse the repository at this point in the history
Kukreja
  • Loading branch information
ptk1729 authored Sep 20, 2024
2 parents 1ef185c + 9f22e7d commit 2981ad0
Show file tree
Hide file tree
Showing 10 changed files with 538 additions and 5,143 deletions.
57 changes: 40 additions & 17 deletions app/AuthContext.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,63 @@
// context/AuthContext.js
"use client";
'use client'

import { createContext, useState, useEffect } from "react";
import Cookies from "js-cookie";
import { createContext, useState, useEffect } from 'react'
import Cookies from 'js-cookie'
import { jwtDecode } from 'jwt-decode'

export const AuthContext = createContext();
export const AuthContext = createContext()

export default function AuthProvider({ children }) {
const [token, setToken] = useState(null);
const [token, setToken] = useState(null)

useEffect(() => {
// Check if token exists in cookies on initial load
const savedToken = Cookies.get("jwt");
const savedToken = Cookies.get('jwt')
if (savedToken) {
setToken(savedToken);
const isTokenValid = checkTokenExpiry(savedToken)
if (isTokenValid) {
setToken(savedToken)
} else {
logout()
}
} else {
logout()
}
}, []);
}, [])

const checkTokenExpiry = (token) => {
try {
const decodeToken = jwtDecode(token)
const currentTime = new Date() / 1000 //Get current time in seconds

if (decodeToken.exp < currentTime) {
return false // Token is expired
}
return true // Token is still valid
} catch (error) {
console.error('Error decoding token:', error)
return false // If decoding fails, consider the token invalid
}
}

const loginSaveCookie = (jwt) => {
const expiresDate = new Date();
expiresDate.setDate(expiresDate.getDate() + "8h"); // Set expiry 8 hours from now
const expiresDate = new Date()
expiresDate.setHours(expiresDate.getHours() + 8) // Set expiry 8 hours from now

Cookies.set("jwt", token, { expires: expiresDate });
Cookies.set('jwt', jwt, { expires: expiresDate })

// Cookies.set("jwt", jwt, { expires: 7 }); // Expires in 7 days
setToken(jwt);
};
setToken(jwt)
}

const logout = () => {
Cookies.remove("jwt");
setToken(null);
};
Cookies.remove('jwt')
setToken(null)
}

return (
<AuthContext.Provider value={{ token, loginSaveCookie, logout }}>
{children}
</AuthContext.Provider>
);
)
}
19 changes: 19 additions & 0 deletions app/UserContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use client'

import { createContext, useState } from 'react'

export const UserContext = createContext()

export default function UserProvider({ children }) {
const [user, setUser] = useState(null)

const updateUser = (userData) => {
setUser(userData)
}

return (
<UserContext.Provider value={{ user, updateUser }}>
{children}
</UserContext.Provider>
)
}
86 changes: 86 additions & 0 deletions app/email-verification/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
'use client'

import { UserContext } from '../UserContext'
import { useRouter } from 'next/navigation'
import { useState, useEffect, useContext } from 'react'
import { AuthContext } from '../AuthContext'

export default function Verification() {
const webURL = process.env.NEXT_PUBLIC_WEB_URL
// const [user, setUser] = useState('')
const [otp, setOtp] = useState('')
const { user } = useContext(UserContext)
const { loginSaveCookie } = useContext(AuthContext)

// useEffect(() => {
// const { user } = userData
// console.log(user)
// setUser(user)
// }, [])

const router = useRouter()

const handleVerifyOtp = async (e) => {
e.preventDefault()

try {
const res = await fetch(webURL + 'auth/verify-otp', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({
...user,
otp: otp,
}),
})

if (!res.ok) {
const errorData = await res.json()
throw new Error(errorData.message || 'Failed to sign up')
}

const { token } = await res.json()
loginSaveCookie(token)
router.push('/')
} catch (error) {
console.error(error)
}
}

return (
<div className="flex items-center justify-center min-h-screen bg-gray-100 p-4">
<div className="w-full max-w-md bg-white rounded shadow-md p-6">
<h2 className="text-2xl font-bold mb-6 text-gray-800">
{' '}
Please check your email
</h2>
<form onSubmit={handleVerifyOtp}>
{/* OTP Verification */}
<div className="mb-4">
<label htmlFor="email" className="block text-gray-700 mb-2">
We've sent a code to
</label>
<input
type="text"
name="email"
id="email"
value={otp}
onChange={(e) => setOtp(e.target.value)}
required
className="w-full px-3 py-2 border rounded focus:outline-none focus:border-teal-500"
/>
</div>

<button
type="submit"
className="w-full bg-teal-500 hover:bg-teal-700 text-white font-bold py-2 px-4 rounded"
>
Verify OTP
</button>
</form>
</div>
</div>
)
}
25 changes: 14 additions & 11 deletions app/layout.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// import localFont from "next/font/local";
import AuthProvider from "./AuthContext"
import "./globals.css";
import Navbar from "./navbar"
import AuthProvider from './AuthContext'
import UserProvider from './UserContext'
import './globals.css'
import Navbar from './navbar'

// const geistSans = localFont({
// src: "./fonts/GeistVF.woff",
Expand All @@ -15,22 +16,24 @@ import Navbar from "./navbar"
// });

export const metadata = {
title: "Gehe.fyi",
description: "A simple to use url shortener service",
};
title: 'Gehe.fyi',
description: 'A simple to use url shortener service',
}

export default function RootLayout({ children }) {
return (
<html lang="en">
<title>{metadata.title}</title>
<body
// className={`${geistSans.variable} ${geistMono.variable} antialiased`}
// className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<AuthProvider>
<Navbar />
{children}
</AuthProvider>
<UserProvider>
<Navbar />
{children}
</UserProvider>
</AuthProvider>
</body>
</html>
);
)
}
Loading

0 comments on commit 2981ad0

Please sign in to comment.