-
Notifications
You must be signed in to change notification settings - Fork 44
test(user): add unit tests for UserUtils token generation and verification #53
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
base: master
Are you sure you want to change the base?
test(user): add unit tests for UserUtils token generation and verification #53
Conversation
Summary of ChangesHello @morningstarxcdcode, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request lays the groundwork for the LocalMind backend, a platform designed to offer flexible AI model interaction and data processing. It delivers a full-fledged user authentication system, integrates with various AI providers like Google Gemini, Groq, and Ollama, and provides a structured way for users to configure their AI agents. A key feature is the AI-powered processing of uploaded datasets for intelligent information extraction. The changes also include essential project setup, environment management, and a suite of tests to ensure the stability of these new functionalities. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
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.
Code Review
This pull request, titled "test(user): add unit tests for UserUtils token generation and verification", introduces a vast number of files, effectively creating the entire backend application. While the added tests for UserUtils are a good start, the scope of this PR is much larger than described, making it difficult to review thoroughly. In the future, please try to keep pull requests focused on a single feature or bug fix.
My review focuses on critical issues related to security, correctness, and maintainability. I've found several critical problems, including invalid package dependencies that will prevent the project from installing, use of hardcoded secrets, and significant bugs in business logic. Please address these high-priority issues.
| public async findAiModelConfigByUserId(id: string): Promise<IAiModelConfig | null> { | ||
| return await AiModelConfig.findById(id).exec() | ||
| } |
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.
The method findAiModelConfigByUserId is using findById, which searches by the document's _id. However, it's being called with a userId. This should be changed to findOne({ userId }) to correctly find the configuration document for a given user.
| public async findAiModelConfigByUserId(id: string): Promise<IAiModelConfig | null> { | |
| return await AiModelConfig.findById(id).exec() | |
| } | |
| public async findAiModelConfigByUserId(userId: string): Promise<IAiModelConfig | null> { | |
| return await AiModelConfig.findOne({ userId }).exec() | |
| } |
src/validator/env.ts
Outdated
|
|
||
| ENCRYPTION_KEY: z.string(), | ||
|
|
||
| SERVER_HMAC_SECRET: z.string(), |
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.
The SERVER_HMAC_SECRET is a critical security variable and should be enforced to be present and have a minimum length to ensure strong keys are used. An empty string would be a security risk.
| SERVER_HMAC_SECRET: z.string(), | |
| SERVER_HMAC_SECRET: z.string().min(32, 'SERVER_HMAC_SECRET must be at least 32 characters long'), |
src/validator/env.ts
Outdated
| .transform((v) => v === 'true') | ||
| .default(false), | ||
|
|
||
| JWT_SECRET: z.string(), |
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.
The JWT_SECRET is a critical security variable and should be enforced to be present and have a minimum length to ensure strong keys are used. An empty or short secret is a security risk.
| JWT_SECRET: z.string(), | |
| JWT_SECRET: z.string().min(32, 'JWT_SECRET must be at least 32 characters long'), |
| { | ||
| "name": "localmind-backend", | ||
| "version": "1.0.0", | ||
| "main": "index.js", | ||
| "scripts": { | ||
| "test": "jest", | ||
| "start-tunnel": "lt --port 5000", | ||
| "setup:backend": "ts-node src/script/project-setup.ts", | ||
| "format": "prettier --write .", | ||
| "build": "tsc", | ||
| "dev": "ts-node-dev --respawn --transpile-only src/server.ts" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/NexGenStudioDev/LocalMind-Backend.git" | ||
| }, | ||
| "author": "", | ||
| "license": "ISC", | ||
| "bugs": { | ||
| "url": "https://github.com/NexGenStudioDev/LocalMind-Backend/issues" | ||
| }, | ||
| "homepage": "https://github.com/NexGenStudioDev/LocalMind-Backend#readme", | ||
| "description": "", | ||
| "devDependencies": { | ||
| "@babel/preset-typescript": "^7.27.1", | ||
| "@types/argon2": "^0.15.4", | ||
| "@types/bcrypt": "^6.0.0", | ||
| "@types/express": "^5.0.3", | ||
| "@types/node": "^24.7.2", | ||
| "@types/nodemailer": "^7.0.3", | ||
| "jest": "^30.2.0", | ||
| "prettier": "3.6.2", | ||
| "ts-jest": "^29.4.5", | ||
| "ts-node": "^10.9.2", | ||
| "ts-node-dev": "^2.0.0", | ||
| "typescript": "^5.9.3" | ||
| }, | ||
| "dependencies": { | ||
| "@jest/globals": "^30.2.0", | ||
| "@langchain/community": "^0.3.57", | ||
| "@langchain/core": "^0.3.78", | ||
| "@langchain/google-genai": "^0.2.18", | ||
| "@langchain/groq": "^0.2.4", | ||
| "@langchain/ollama": "^0.2.4", | ||
| "@types/cookie-parser": "^1.4.9", | ||
| "@types/jsonwebtoken": "^9.0.10", | ||
| "@types/mongoose": "^5.11.97", | ||
| "@types/morgan": "^1.9.10", | ||
| "argon2": "^0.44.0", | ||
| "axios": "^1.12.2", | ||
| "bcrypt": "^6.0.0", | ||
| "chalk": "^5.6.2", | ||
| "cloudflared-tunnel": "^1.0.3", | ||
| "cookie-parser": "^1.4.7", | ||
| "d3-dsv": "^2.0.0", | ||
| "dotenv": "^17.2.3", | ||
| "express": "^5.1.0", | ||
| "figlet": "^1.9.3", | ||
| "jsonwebtoken": "^9.0.2", | ||
| "langchain": "^0.3.36", | ||
| "mongoose": "^8.19.1", | ||
| "morgan": "^1.10.1", | ||
| "ngrok": "5.0.0-beta.2", | ||
| "nodemailer": "^7.0.10", | ||
| "ora": "^9.0.0", | ||
| "zod": "^4.1.12" | ||
| } | ||
| } |
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.
Many of the dependency versions listed in package.json do not exist on the npm registry (e.g., @types/express@^5.0.3, jest@^30.2.0, axios@^1.12.2, mongoose@^8.19.1, etc.). This will prevent the project from being installed and run. Please correct the versions to valid, existing ones. You can use npm view <package-name> versions to check for available versions, or npm install <package-name>@latest to get the latest stable version.
| if (!existingConfig) { | ||
| CreateConfig = await AiModelConfigService.setupAiModelConfig({ | ||
| userId: String(FindUserByToken._id), | ||
| agents: [{} as IAgent], | ||
| system_prompt, | ||
| }) | ||
| } |
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.
Creating a new AiModelConfig with agents: [{} as IAgent] is incorrect. The IAgent interface and AgentSchema have required fields like provider, type, and model. This will lead to a database validation error. If a new configuration is being created, it should be with the validated agents from the request body.
|
|
||
| describe('UserUtils token helpers', () => { | ||
| test('generateToken and verifyToken roundtrip', () => { | ||
| const payload = { userId: 'abc123', email: 'a@b.com', role: 'user' } |
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.
| public static verifyToken(token: string): IUser | null { | ||
| try { | ||
| const decoded = jwt.verify(token, this.JWT_SECRET) | ||
|
|
||
| if (typeof decoded === 'object' && decoded !== null) { | ||
| return { | ||
| email: decoded.email as string, | ||
| _id: decoded.userId as string, | ||
| role: decoded.role as string, | ||
| } | ||
| } | ||
|
|
||
| return null | ||
| } catch { | ||
| return null | ||
| } |
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.
To align with the suggested change to use _id in JwtPayload, this method should be updated to use decoded._id. Also, casting decoded to JwtPayload provides better type safety and removes the need for individual property casting.
| public static verifyToken(token: string): IUser | null { | |
| try { | |
| const decoded = jwt.verify(token, this.JWT_SECRET) | |
| if (typeof decoded === 'object' && decoded !== null) { | |
| return { | |
| email: decoded.email as string, | |
| _id: decoded.userId as string, | |
| role: decoded.role as string, | |
| } | |
| } | |
| return null | |
| } catch { | |
| return null | |
| } | |
| public static verifyToken(token: string): IUser | null { | |
| try { | |
| const decoded = jwt.verify(token, this.JWT_SECRET) as JwtPayload | |
| if (typeof decoded === 'object' && decoded !== null) { | |
| return { | |
| email: decoded.email as string, | |
| _id: decoded._id as string, | |
| role: decoded.role as string, | |
| } | |
| } | |
| return null | |
| } catch { | |
| return null | |
| } | |
| } |
| console.log('Ai_Response', Ai_Response) | ||
|
|
||
| SendResponse.success(res, 'AI response generated successfully', Ai_Response, 200) | ||
| } catch (err: any) { | ||
| console.log('err', err) |
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.
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.
Pull request overview
This PR adds unit tests for UserUtils token generation and verification methods, along with a comprehensive backend setup including user authentication, AI model integration, and configuration management. The tests ensure JWT token operations work correctly by testing roundtrip token generation/verification and invalid token handling.
- Unit tests for
generateTokenandverifyTokenin UserUtils - Integration tests for user registration with database interaction
- Complete backend infrastructure including user management, AI model services (Ollama, Groq, Google Gemini), and dataset processing
Reviewed changes
Copilot reviewed 59 out of 67 changed files in this pull request and generated 23 comments.
Show a summary per file
| File | Description |
|---|---|
src/api/v1/user/__test__/user.utils.test.ts |
Adds unit tests for token generation and verification with proper env setup |
src/api/v1/user/__test__/user.test.ts |
Adds integration tests for user registration endpoints |
src/api/v1/user/user.utils.ts |
Implements JWT token helpers and user authentication utilities |
src/api/v1/user/user.validator.ts |
Defines Zod schemas for user registration and login validation |
src/api/v1/user/user.controller.ts |
Implements user authentication endpoints (register, login, profile) |
src/api/v1/user/user.service.ts |
Provides user creation and API key generation services |
src/api/v1/user/user.routes.ts |
Defines authentication routes with middleware protection |
src/api/v1/user/user.model.ts |
Mongoose schema for User model with authentication fields |
src/api/v1/user/user.type.ts |
TypeScript interface for User entity |
src/api/v1/user/user.constant.ts |
Centralized user-related message constants |
src/api/v1/user/user.middleware.ts |
JWT authentication middleware for protected routes |
src/validator/env.ts |
Zod schema for environment variable validation |
src/constant/env.constant.ts |
Exports validated environment configuration |
src/utils/safeJson.util.ts |
Safe JSON parsing utility with fallback |
src/utils/__test__/safeJson.util.test.ts |
Unit tests for safe JSON parsing |
src/utils/SendResponse.utils.ts |
Standardized API response formatting |
src/api/v1/AiModelConfig/* |
AI model configuration management (models, services, validators) |
src/api/v1/Ai-model/Ollama/* |
Ollama AI integration with embeddings and text generation |
src/api/v1/Ai-model/Groq/* |
Groq AI service integration |
src/api/v1/Ai-model/Google/* |
Google Gemini AI integration utilities |
src/api/v1/DataSet/v1/* |
Dataset processing and validation services |
src/Template/v1/* |
AI prompt templates and formatters |
tsconfig.json |
TypeScript compiler configuration |
package.json |
Project dependencies and scripts |
jest.config.ts |
Jest test framework configuration |
.env.example |
Environment variable template |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
morningstarxcdcode
left a comment
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.
see now
… user controller error handling and token usage; security: enforce env secrets min length; update Ollama and DataSet utilities; fix AiModelConfig agent handling and service
|
Thanks @gemini-code-assist and @copilot for the detailed review — I addressed the critical/high comments and pushed fixes:
If I missed anything else called out by the bots, please point me to the exact comment and I'll iterate further. Ready for re-review — I can also run CI locally if you want (need to install dependencies first). |
|
Thanks for the detailed update, @morningstarxcdcode! It's great to see that you've addressed the critical and high-priority feedback. Your proactive approach to improving the codebase is much appreciated. I'll initiate a re-review of the pull request to ensure all changes are thoroughly checked and to identify any further areas for improvement. I'll provide specific comments if I find anything that needs attention. Looking forward to seeing the updated code! |
|
@morningstarxcdcode please be active for the project configure ecwoc sentinel and Merge PRs with ECWoC label |
Fixes #52\n\nSummary: Adds tests for and . The test file sets required env vars before importing modules that parse to avoid errors in test environment.