Skip to content

Commit 6df1a9d

Browse files
authored
Merge pull request #117 from nileshdev0707/fix/login_issue
Fixed the login sub issue and fixed the redirect url issue
2 parents 5bb11e7 + 4848f89 commit 6df1a9d

File tree

7 files changed

+92
-76
lines changed

7 files changed

+92
-76
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
"axios": "^1.3.4",
2727
"chart.js": "^4.2.1",
2828
"ethers": "^5.7.2",
29+
"jwt-decode": "^3.1.2",
2930
"lodash": "^4.17.21",
3031
"memory-cache": "^0.2.0",
3132
"moment": "^2.29.4",

src/components/global/navbar/User.tsx

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,24 @@ import IconButton from '@mui/material/IconButton';
99
import Button from '@mui/material/Button';
1010
import Logout from '@mui/icons-material/Logout';
1111
import Login from '@mui/icons-material/Login';
12-
import { useRouter } from "next/router";
13-
import { useSession, signOut } from "next-auth/react"
12+
import {useRouter} from "next/router";
13+
import {useSession, signOut} from "next-auth/react"
1414

1515
function User() {
1616
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
1717
const open = Boolean(anchorEl);
1818
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
1919
setAnchorEl(event.currentTarget);
2020
};
21-
const { data: sessions } = useSession()
21+
const {data: sessions} = useSession()
2222
const router = useRouter();
2323

24-
const { id_token, idToken } = sessions?.user as { id_token?: string, idToken?: string} || {};
24+
const {id_token, idToken} = sessions?.user as { id_token?: string, idToken?: string } || {};
2525
const handleClose = (url?: string) => {
2626
setAnchorEl(null);
2727
url && router.push(url)
2828
};
29-
29+
3030
const dropdown = [
3131
["My Profile", "/my-profile", "/images/icon-container (2).svg"],
3232
["API Plans", "/apiplans", "/images/API.svg"],
@@ -61,55 +61,55 @@ function User() {
6161
}
6262
return (
6363
<div className="flex items-center gap-1">
64-
{ (id_token || idToken) ? <>
65-
<IconImgButton icon="/images/icon-container (1).svg" />
66-
<Box sx={{ display: 'flex', alignItems: 'center', textAlign: 'center' }}>
64+
{(id_token || idToken) ? <>
65+
<IconImgButton icon="/images/icon-container (1).svg"/>
66+
<Box sx={{display: 'flex', alignItems: 'center', textAlign: 'center'}}>
6767
<IconButton
68-
onClick={handleClick}
69-
size="small"
70-
aria-controls={open ? 'user-menu' : undefined}
71-
aria-haspopup="true"
72-
aria-expanded={open ? 'true' : undefined}
73-
>
74-
<img src={"/images/icon-container (2).svg"} alt="user" />
68+
onClick={handleClick}
69+
size="small"
70+
aria-controls={open ? 'user-menu' : undefined}
71+
aria-haspopup="true"
72+
aria-expanded={open ? 'true' : undefined}
73+
>
74+
<img src={"/images/icon-container (2).svg"} alt="user"/>
7575
</IconButton>
7676
</Box>
7777
<Menu
7878
anchorEl={anchorEl}
7979
id="user-menu"
8080
open={open}
81-
onClose={()=>handleClose()}
82-
onClick={()=>handleClose()}
83-
PaperProps={ propsConfig}
84-
transformOrigin={{ horizontal: 'right', vertical: 'top' }}
85-
anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
81+
onClose={() => handleClose()}
82+
onClick={() => handleClose()}
83+
PaperProps={propsConfig}
84+
transformOrigin={{horizontal: 'right', vertical: 'top'}}
85+
anchorOrigin={{horizontal: 'right', vertical: 'bottom'}}
8686
>
87-
{dropdown?.map((menuItem, index) => (
88-
<MenuItem key={index} className="ml-0" onClick={() =>handleClose(menuItem[1])}>
87+
{dropdown?.map((menuItem, index) => (
88+
<MenuItem key={index} className="ml-0" onClick={() => handleClose(menuItem[1])}>
8989
<ListItemIcon>
90-
<img src={menuItem[2]} alt="" />
90+
<img src={menuItem[2]} alt=""/>
9191
</ListItemIcon>
9292
<span className="mr-3.5"> {menuItem[0]}</span>
9393
</MenuItem>
94-
))
94+
))
9595
}
96-
<Divider />
96+
<Divider/>
9797
<MenuItem>
9898
<Button fullWidth color="inherit"
9999
variant="outlined"
100100
onClick={() => signOut()}
101-
startIcon={<Logout fontSize="inherit" />}>
101+
startIcon={<Logout fontSize="inherit"/>}>
102102
Sign Out
103103
</Button>
104104
</MenuItem>
105-
</Menu></>: <>
105+
</Menu></> : <>
106106
<Button fullWidth color="inherit"
107107
variant="outlined"
108-
onClick={()=> router.push('/login')}
109-
startIcon={<Login fontSize="inherit" />}>
110-
Sign In
111-
</Button>
112-
</> }
108+
onClick={() => router.push(`/login?callBack=${router?.asPath ? router?.asPath : '/'}`)}
109+
startIcon={<Login fontSize="inherit"/>}>
110+
Sign In
111+
</Button>
112+
</>}
113113
</div>
114114
);
115115
}

src/lib/auth.tsx

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,12 @@ export const authOptions = {
9595
async redirect(url: any) {
9696
console.log("Url======>", url)
9797
// Return the url to redirect to after successful sign in.
98-
return url.url.startsWith(url.baseUrl)
99-
? url.url
100-
: url.baseUrl
98+
// Allows relative callback URLs
99+
100+
if (url.url.startsWith("/")) return `${url.baseUrl}${url.url}`
101+
// Allows callback URLs on the same origin
102+
else if (new URL(url.url)?.origin === url.baseUrl) return url.url
103+
return url.baseUrl
101104
},
102105
jwt: jwt,
103106
// async jwt({token, account, profile, user}: any) {

src/lib/authorize.tsx

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {CognitoIdentityProvider} from "@aws-sdk/client-cognito-identity-provider";
2+
import jwt_decode from "jwt-decode";
23

34
const COGNITO_REGION = process.env.NEXT_PUBLIC_COGNITO_REGION;
45
const LOGIN_REGISTER_COGNITO_CLIENT_ID = process.env.NEXT_PUBLIC_LOGIN_REGISTER_COGNITO_CLIENT_ID;
@@ -21,14 +22,19 @@ export default async function authorize(credentials: any) {
2122
console.log("signInResponse:", signInResponse);
2223
// Process signInResponse and return a user object if successful
2324
if (signInResponse.AuthenticationResult) {
24-
return {
25-
accessToken: signInResponse.AuthenticationResult.AccessToken,
26-
idToken: signInResponse.AuthenticationResult.IdToken,
27-
refreshToken: signInResponse.AuthenticationResult.RefreshToken,
28-
user: {
29-
email: credentials.email,
25+
if (signInResponse.AuthenticationResult.IdToken != null) {
26+
const decoded = jwt_decode(signInResponse.AuthenticationResult.IdToken);
27+
if (decoded) {
28+
return {
29+
accessToken: signInResponse.AuthenticationResult.AccessToken,
30+
idToken: signInResponse.AuthenticationResult.IdToken,
31+
refreshToken: signInResponse.AuthenticationResult.RefreshToken,
32+
...decoded
33+
}
3034
}
35+
return null
3136
}
37+
3238
} else {
3339
console.log('Error signing in:', signInResponse, signInParams);
3440
throw new Error('Failed to authenticate')
Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
import NextAuth from 'next-auth'
22
import {authOptions} from "@/lib/auth";
3-
export default NextAuth(authOptions)
3+
import {NextApiRequest, NextApiResponse} from "next";
4+
5+
export default (req: NextApiRequest, res: NextApiResponse) => {
6+
return NextAuth(req, res, authOptions)
7+
}
48
// export { handler as GET, handler as POST }

src/views/login/login.tsx

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,24 @@
1-
import React, { useEffect, useState } from 'react';
1+
import React, {useEffect, useState} from 'react';
22
import Image from 'next/image';
33
import logo from '../../../public/images/logo.png';
44
import Link from 'next/link';
55
import MiniFooter from '@/components/global/minifooter';
6-
import { signIn, useSession } from 'next-auth/react';
7-
import { useRouter } from 'next/router';
6+
import {signIn, useSession} from 'next-auth/react';
7+
import {useRouter} from 'next/router';
88
import Spinner from '@/components/common/Spinner';
9-
import { mockProviders } from 'next-auth/client/__tests__/helpers/mocks';
9+
import {mockProviders} from 'next-auth/client/__tests__/helpers/mocks';
1010
import callbackUrl = mockProviders.github.callbackUrl;
11-
import { TextField } from '@mui/material';
11+
import {TextField} from '@mui/material';
1212

1313
const LoginComponent = () => {
14-
const { data: session, status, update } = useSession();
14+
const {data: session, status, update} = useSession();
1515
const [email, setEmail] = useState('');
1616
const [password, setPassword] = useState('');
1717
const [successMessage, setSuccessMessage] = useState('');
1818
const router = useRouter();
1919
const [errorMessage, setErrorMessage] = useState('');
2020
const [loading, setLoading] = useState(false);
21-
const { query } = router;
22-
23-
console.log('session',session);
21+
const {query} = router;
2422

2523
const handleLoginWithGoogle = async () => {
2624
try {
@@ -49,7 +47,7 @@ const LoginComponent = () => {
4947
email,
5048
password,
5149
redirect: true,
52-
callbackUrl: query?.callBack ? `http://localhost:3000${query?.callBack}`: 'http://localhost:3000',
50+
callbackUrl: query?.callBack ? `${query?.callBack}` : '/',
5351
});
5452
console.log('signInResponse:', signInResponse);
5553
if (signInResponse?.error) {
@@ -68,41 +66,43 @@ const LoginComponent = () => {
6866
// }, []
6967
// )
7068
return (
71-
<div className="main-box bg-dark-600" style={{ height: 'auto !important', minHeight: '100vh' }}>
72-
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
73-
<Image src={logo} alt="logo" className="mt-10 text-center" />
74-
<div className="px-10 py-5 bg-white rounded whitebox mt-11" style={{ height: '546px', width: '464px' }}>
75-
<p className="mt-4 text-xl text-center text-black font-weight-bold" style={{ fontSize: '1.4rem' }}>
69+
<div className="main-box bg-dark-600" style={{height: 'auto !important', minHeight: '100vh'}}>
70+
<div style={{display: 'flex', flexDirection: 'column', alignItems: 'center'}}>
71+
<Image src={logo} alt="logo" className="mt-10 text-center"/>
72+
<div className="px-10 py-5 bg-white rounded whitebox mt-11" style={{height: '546px', width: '464px'}}>
73+
<p className="mt-4 text-xl text-center text-black font-weight-bold" style={{fontSize: '1.4rem'}}>
7674
Login
7775
</p>
7876
{errorMessage && (
79-
<div className="relative block w-full p-4 mt-5 text-base leading-5 text-white bg-red-500 rounded-lg opacity-100 font-regular">
77+
<div
78+
className="relative block w-full p-4 mt-5 text-base leading-5 text-white bg-red-500 rounded-lg opacity-100 font-regular">
8079
{errorMessage}
8180
</div>
8281
)}
8382
{successMessage && (
84-
<div className="relative block w-full p-4 mt-5 text-base leading-5 text-white bg-green-500 rounded-lg opacity-100 font-regular">
83+
<div
84+
className="relative block w-full p-4 mt-5 text-base leading-5 text-white bg-green-500 rounded-lg opacity-100 font-regular">
8585
{successMessage}
8686
</div>
8787
)}
8888
{loading && (
8989
<div className={'align-items-center d-flex flex justify-center mt-3'}>
90-
<Spinner height={'1rem'} width={'1rem'} />
90+
<Spinner height={'1rem'} width={'1rem'}/>
9191
</div>
9292
)}
9393
<button
9494
type="button"
9595
onClick={() => handleLoginWithGoogle()}
9696
className="w-full mt-5 text-center hidden justify-center focus:ring-0 focus:outline-none rounded border border-dark-200 md:text-md sm:text-sm text-[10px] px-5 py-3 inline-flex items-center mb-2"
9797
>
98-
<img src="/images/google.svg" alt="" />
98+
<img src="/images/google.svg" alt=""/>
9999
<span className="uppercase font-medium text-dark-600 ml-1 sm:ml-2 tracking-[1.5px]">continue with google</span>
100100
</button>
101101

102102
{/* <p className="mt-5 text-center text-black text-md font-weight-bold">or</p> */}
103-
<br />
104-
<br />
105-
<br />
103+
<br/>
104+
<br/>
105+
<br/>
106106
<TextField
107107
label="Email"
108108
id="email"
@@ -130,12 +130,13 @@ const LoginComponent = () => {
130130
>
131131
LOGIN
132132
</button>
133-
<p className="text-xl text-center text-black font-weight-bold mt-9" style={{ color: '#1976D2', fontSize: '14px' }}>
133+
<p className="text-xl text-center text-black font-weight-bold mt-9"
134+
style={{color: '#1976D2', fontSize: '14px'}}>
134135
Reset Password
135136
</p>
136-
<Link href="/register">
137-
<p className="mt-5 text-xl text-center text-black font-weight-bold" style={{ fontSize: '14px' }}>
138-
No account? <span style={{ color: '#1976D2' }}>Create one</span>
137+
<Link href={`/register?callBack=${router.query.callBack ? router.query.callBack : '/'}`}>
138+
<p className="mt-5 text-xl text-center text-black font-weight-bold" style={{fontSize: '14px'}}>
139+
No account? <span style={{color: '#1976D2'}}>Create one</span>
139140
</p>
140141
</Link>
141142
<style>
@@ -186,7 +187,7 @@ const LoginComponent = () => {
186187
</style>
187188
</div>
188189
</div>
189-
<MiniFooter />
190+
<MiniFooter/>
190191
</div>
191192
);
192193
};

src/views/register/register.tsx

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ const COGNITO_USER_POOL_ID = process.env.NEXT_PUBLIC_COGNITO_USER_POOL_ID;
1818
type userProps = {
1919
name: string,
2020
designation: string,
21-
companyName:string,
21+
companyName: string,
2222
receiveUpdates: string
2323
};
2424

@@ -63,11 +63,12 @@ const RegisterComponent = () => {
6363
userPoolWebClientId: LOGIN_REGISTER_COGNITO_CLIENT_ID
6464
}
6565
Amplify.configure(awsAmplifyConfig)
66-
const { name, designation, companyName, receiveUpdates}: userProps = user;
66+
const {name, designation, companyName, receiveUpdates}: userProps = user;
6767
const params = {
6868
password: password,
6969
username: email,
70-
attributes: {email,
70+
attributes: {
71+
email,
7172
name,
7273
'custom:receiveUpdates': receiveUpdates ?? "",
7374
'custom:designation': designation ?? "",
@@ -97,9 +98,9 @@ const RegisterComponent = () => {
9798
await signIn("cognito_google", {redirect: false, callbackUrl: `http://localhost:3000${query?.callBack}`})
9899
};
99100

100-
const handleUser = async ({validates, user}: any) => {
101+
const handleUser = async ({validates, user}: any) => {
101102
if (validates['name'].error) {
102-
setErrorMessage( validates['name'].msg);
103+
setErrorMessage(validates['name'].msg);
103104
} else {
104105
setErrorMessage('');
105106
}
@@ -210,7 +211,7 @@ const RegisterComponent = () => {
210211
onChange={(e) => setConfirmPassword(e.target.value)}
211212
required
212213
/>
213-
<UserInfo handleInfo={handleUser} />
214+
<UserInfo handleInfo={handleUser}/>
214215
<button
215216
className="w-full py-2 text-center text-white rounded font-weight-bold bg-dark-600 mt-9"
216217
onClick={handleRegistration}
@@ -240,7 +241,7 @@ const RegisterComponent = () => {
240241
</a>
241242
</p>
242243

243-
<Link href="/login">
244+
<Link href={`/login?callBack=${query.callBack ? query.callBack : '/'}`}>
244245
<p className="mt-5 text-center text-black text-md font-weight-bold">
245246
Already have an account? <span style={{color: '#1976D2'}}>Log in</span>
246247
</p>

0 commit comments

Comments
 (0)