-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feat/mobile auth #772
Closed
Closed
Feat/mobile auth #772
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
7848d89
added routes for mobile login and changed middleware for authorization
nimit9 2541797
Merge branch 'main' of github.com:nimit9/cms-new into feat/mobile-auth
nimit9 79e8f99
added check for mobile device
nimit9 a9db646
fix: typo in payload destructuring
devsargam File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import { NextRequest, NextResponse } from 'next/server'; | ||
import { authorize } from '@/lib/auth'; | ||
|
||
export async function POST(request: NextRequest) { | ||
try { | ||
const reqBody = await request.json(); | ||
const { username, password } = reqBody; | ||
|
||
const user = await authorize({ username, password }); | ||
|
||
if (!user) { | ||
return NextResponse.json( | ||
{ error: 'User does not exist' }, | ||
{ status: 400 }, | ||
); | ||
} | ||
const { token, ...otherProperties } = user; | ||
const response = NextResponse.json({ | ||
message: 'Login successful', | ||
token, | ||
user: { ...otherProperties }, | ||
}); | ||
return response; | ||
} catch (error: any) { | ||
return NextResponse.json({ error: error.message }, { status: 500 }); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import { NextRequest, NextResponse } from 'next/server'; | ||
import db from '@/db'; | ||
|
||
export async function POST(request: NextRequest) { | ||
try { | ||
// TODO: Get userid from somewhere not body | ||
const body = await request.json(); | ||
nimit9 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
await db.user.update({ | ||
where: { | ||
id: body.userId, | ||
}, | ||
data: { | ||
token: null, | ||
}, | ||
}); | ||
return NextResponse.json({ | ||
message: 'Logout successful', | ||
success: true, | ||
}); | ||
} catch (error: any) { | ||
return NextResponse.json({ error: error.message }, { status: 500 }); | ||
} | ||
} | ||
|
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -50,6 +50,7 @@ const generateJWT = async (payload: JWTPayload) => { | |
|
||
return jwt; | ||
}; | ||
|
||
async function validateUser( | ||
email: string, | ||
password: string, | ||
|
@@ -106,6 +107,110 @@ async function validateUser( | |
}; | ||
} | ||
|
||
export const authorize = async (credentials?: { | ||
username: string; | ||
password: string; | ||
}) => { | ||
if (!credentials?.username || !credentials?.password) { | ||
return null; | ||
} | ||
try { | ||
if (process.env.LOCAL_CMS_PROVIDER) { | ||
return { | ||
id: '1', | ||
name: 'test', | ||
email: '[email protected]', | ||
token: await generateJWT({ | ||
id: '1', | ||
}), | ||
}; | ||
} | ||
const hashedPassword = await bcrypt.hash(credentials.password, 10); | ||
|
||
const userDb = await prisma.user.findFirst({ | ||
where: { | ||
email: credentials.username, | ||
}, | ||
select: { | ||
password: true, | ||
id: true, | ||
name: true, | ||
}, | ||
}); | ||
if ( | ||
userDb && | ||
userDb.password && | ||
(await bcrypt.compare(credentials.password, userDb.password)) | ||
) { | ||
const jwt = await generateJWT({ | ||
id: userDb.id, | ||
}); | ||
await db.user.update({ | ||
where: { | ||
id: userDb.id, | ||
}, | ||
data: { | ||
token: jwt, | ||
}, | ||
}); | ||
|
||
return { | ||
id: userDb.id, | ||
name: userDb.name, | ||
email: credentials.username, | ||
token: jwt, | ||
}; | ||
} | ||
const user: AppxSigninResponse = await validateUser( | ||
credentials.username, | ||
credentials.password, | ||
); | ||
|
||
const jwt = await generateJWT({ | ||
id: user.data?.userid, | ||
}); | ||
|
||
if (user.data) { | ||
try { | ||
await db.user.upsert({ | ||
where: { | ||
id: user.data.userid, | ||
}, | ||
create: { | ||
id: user.data.userid, | ||
name: user.data.name, | ||
email: credentials.username, | ||
token: jwt, | ||
password: hashedPassword, | ||
}, | ||
update: { | ||
id: user.data.userid, | ||
name: user.data.name, | ||
email: credentials.username, | ||
token: jwt, | ||
password: hashedPassword, | ||
}, | ||
}); | ||
} catch (e) { | ||
console.log(e); | ||
} | ||
|
||
return { | ||
id: user.data.userid, | ||
name: user.data.name, | ||
email: credentials.username, | ||
token: jwt, | ||
}; | ||
} | ||
|
||
// Return null if user data could not be retrieved | ||
return null; | ||
} catch (e) { | ||
console.error(e); | ||
} | ||
return null; | ||
}; | ||
|
||
export const authOptions = { | ||
providers: [ | ||
CredentialsProvider({ | ||
|
@@ -114,104 +219,7 @@ export const authOptions = { | |
username: { label: 'email', type: 'text', placeholder: '' }, | ||
password: { label: 'password', type: 'password', placeholder: '' }, | ||
}, | ||
async authorize(credentials: any) { | ||
try { | ||
if (process.env.LOCAL_CMS_PROVIDER) { | ||
return { | ||
id: '1', | ||
name: 'test', | ||
email: '[email protected]', | ||
token: await generateJWT({ | ||
id: '1', | ||
}), | ||
}; | ||
} | ||
const hashedPassword = await bcrypt.hash(credentials.password, 10); | ||
|
||
const userDb = await prisma.user.findFirst({ | ||
where: { | ||
email: credentials.username, | ||
}, | ||
select: { | ||
password: true, | ||
id: true, | ||
name: true, | ||
}, | ||
}); | ||
if ( | ||
userDb && | ||
userDb.password && | ||
(await bcrypt.compare(credentials.password, userDb.password)) | ||
) { | ||
const jwt = await generateJWT({ | ||
id: userDb.id, | ||
}); | ||
await db.user.update({ | ||
where: { | ||
id: userDb.id, | ||
}, | ||
data: { | ||
token: jwt, | ||
}, | ||
}); | ||
|
||
return { | ||
id: userDb.id, | ||
name: userDb.name, | ||
email: credentials.username, | ||
token: jwt, | ||
}; | ||
} | ||
console.log('not in db'); | ||
const user: AppxSigninResponse = await validateUser( | ||
credentials.username, | ||
credentials.password, | ||
); | ||
|
||
const jwt = await generateJWT({ | ||
id: user.data?.userid, | ||
}); | ||
|
||
if (user.data) { | ||
try { | ||
await db.user.upsert({ | ||
where: { | ||
id: user.data.userid, | ||
}, | ||
create: { | ||
id: user.data.userid, | ||
name: user.data.name, | ||
email: credentials.username, | ||
token: jwt, | ||
password: hashedPassword, | ||
}, | ||
update: { | ||
id: user.data.userid, | ||
name: user.data.name, | ||
email: credentials.username, | ||
token: jwt, | ||
password: hashedPassword, | ||
}, | ||
}); | ||
} catch (e) { | ||
console.log(e); | ||
} | ||
|
||
return { | ||
id: user.data.userid, | ||
name: user.data.name, | ||
email: credentials.username, | ||
token: jwt, | ||
}; | ||
} | ||
|
||
// Return null if user data could not be retrieved | ||
return null; | ||
} catch (e) { | ||
console.error(e); | ||
} | ||
return null; | ||
}, | ||
authorize, | ||
}), | ||
], | ||
secret: process.env.NEXTAUTH_SECRET || 'secr3t', | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
import { importJWK, jwtVerify } from 'jose'; | ||
import { NextRequestWithAuth, withAuth } from 'next-auth/middleware'; | ||
import { NextRequest, NextResponse, userAgent } from 'next/server'; | ||
|
||
const PRIVATE_MOBILE_ROUTES = ['/api/auth/mobile/logout']; | ||
const SINGLE_USER_ROUTES = ['/courses', '/questions', '/bookmarks']; | ||
|
||
const shouldRestrictSingleUser = (pathname: string) => { | ||
return SINGLE_USER_ROUTES.some((route) => pathname.startsWith(route)); | ||
}; | ||
|
||
const verifyJWT = async (token: string) => { | ||
const secret = process.env.JWT_SECRET || 'secret'; | ||
const jwk = await importJWK({ k: secret, alg: 'HS256', kty: 'oct' }); | ||
const payload = await jwtVerify(token, jwk); | ||
return payload; | ||
}; | ||
|
||
export const handleMobileAuth = async (request: NextRequestWithAuth) => { | ||
const token = request.headers.get('Authorization')?.split(' ')[1]; | ||
const pathname = request.nextUrl.pathname; | ||
if (token) { | ||
try { | ||
const payload: any = await verifyJWT(token); | ||
// @typo here | ||
const userId = payload.payload.userid; | ||
console.log(userId); | ||
return NextResponse.next(); | ||
} catch (error) { | ||
return NextResponse.json({ message: 'Unauthorized' }, { status: 401 }); | ||
} | ||
} else if (PRIVATE_MOBILE_ROUTES.includes(pathname)) { | ||
return NextResponse.json({ message: 'Unauthorized' }, { status: 401 }); | ||
} | ||
}; | ||
|
||
export const nextAuthMiddleware = withAuth(async (req) => { | ||
if (process.env.LOCAL_CMS_PROVIDER) return; | ||
|
||
const pathname = req.nextUrl.pathname; | ||
|
||
if (shouldRestrictSingleUser(pathname)) { | ||
const token = req.nextauth.token; | ||
if (!token) { | ||
return NextResponse.redirect(new URL('/invalidsession', req.url)); | ||
} | ||
const user = await fetch( | ||
`${process.env.NEXT_PUBLIC_BASE_URL_LOCAL}/api/user?token=${token.jwtToken}`, | ||
); | ||
|
||
const json = await user.json(); | ||
if (!json.user) { | ||
return NextResponse.redirect(new URL('/invalidsession', req.url)); | ||
} | ||
} | ||
}); | ||
|
||
export const getDeviceType = (request: NextRequest) => { | ||
const { device } = userAgent(request); | ||
return device.type; | ||
}; | ||
|
||
export const isMobile = (request: NextRequest) => { | ||
const deviceType = getDeviceType(request); | ||
return deviceType === 'mobile' || deviceType === 'tablet'; | ||
}; | ||
|
||
export const isDesktop = (request: NextRequest) => { | ||
return !isMobile(request); | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lets wait for this to be solved