Skip to content
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: update lastLoginIp saving on login #1623

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "lastLoginIp" TEXT;
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ model User {
appxUserId String?
appxUsername String?
appxAuthToken String?
lastLoginIp String?
questions Question[]
answers Answer[]
certificate Certificate[]
Expand Down
13 changes: 8 additions & 5 deletions src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,14 @@ interface user {
token: string;
}

const generateJWT = async (payload: JWTPayload) => {
const generateJWT = async (payload: JWTPayload, userIp: string) => {
const secret = process.env.JWT_SECRET || 'secret';

const jwk = await importJWK({ k: secret, alg: 'HS256', kty: 'oct' });

const jwt = await new SignJWT({
...payload,
userIp,
iat: Math.floor(Date.now() / 1000),
jti: randomUUID(), // Adding a unique jti to ensure each token is unique. This helps generate a unique jwtToken on every login
})
Expand Down Expand Up @@ -119,16 +120,17 @@ export const authOptions = {
username: { label: 'email', type: 'text', placeholder: '' },
password: { label: 'password', type: 'password', placeholder: '' },
},
async authorize(credentials: any) {
async authorize(credentials: any, req: any) {
try {
const userIp = req.headers['x-forwarded-for']?.split(',')[0] || req.socket.remoteAddress;
if (process.env.LOCAL_CMS_PROVIDER) {
return {
id: '1',
name: 'test',
email: '[email protected]',
token: await generateJWT({
id: '1',
}),
}, userIp),
};
}
const hashedPassword = await bcrypt.hash(credentials.password, 10);
Expand All @@ -152,13 +154,14 @@ export const authOptions = {
) {
const jwt = await generateJWT({
id: userDb.id,
});
}, userIp);
await db.user.update({
where: {
id: userDb.id,
},
data: {
token: jwt,
lastLoginIp: userIp
},
});

Expand All @@ -177,7 +180,7 @@ export const authOptions = {

const jwt = await generateJWT({
id: user.data?.userid,
});
}, userIp);

if (user.data) {
try {
Expand Down
23 changes: 23 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ interface RequestWithUser extends NextRequest {
};
}

export const getClientIP = (req: NextRequest | NextRequestWithAuth): string => {
return (
req.headers.get('x-forwarded-for')?.split(',')[0] ||
req.ip ||
'127.0.0.1'
);
};

export const verifyJWT = async (token: string): Promise<JWTPayload | null> => {
const secret = process.env.JWT_SECRET || '';

Expand All @@ -29,6 +37,8 @@ export const verifyJWT = async (token: string): Promise<JWTPayload | null> => {
};

export const withMobileAuth = async (req: RequestWithUser) => {
const clientIP = getClientIP(req);

if (req.headers.get('Auth-Key')) {
return NextResponse.next();
}
Expand All @@ -41,6 +51,12 @@ export const withMobileAuth = async (req: RequestWithUser) => {
if (!payload) {
return NextResponse.json({ message: 'Unauthorized' }, { status: 403 });
}

if (payload.userIp !== clientIP) {
console.warn("IP Mismatch");
return NextResponse.json({ message: 'Unauthorized - ip verification Failed',}, { status: 403 });
}

const newHeaders = new Headers(req.headers);

/**
Expand All @@ -65,6 +81,8 @@ const withAuth = async (req: NextRequestWithAuth) => {
return NextResponse.redirect(new URL('/invalidsession', req.url));
}

const clientIP = getClientIP(req);

const user = await fetch(
`${process.env.NEXT_PUBLIC_BASE_URL_LOCAL}/api/user?token=${token.jwtToken}`,
);
Expand All @@ -73,6 +91,11 @@ const withAuth = async (req: NextRequestWithAuth) => {
if (!json.user) {
return NextResponse.redirect(new URL('/invalidsession', req.url));
}

if (token.userIp !== clientIP) {
console.warn("IP Mismatch");
return NextResponse.redirect(new URL('/invalidsession', req.url));
}
};

export async function middleware(req: NextRequestWithAuth) {
Expand Down
Loading