-
-
Notifications
You must be signed in to change notification settings - Fork 1k
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
Feature/added GraphQl Quries in server to verify User Role and Its authorization So that it can be helpFul for client side. #3094
Conversation
Warning Rate limit exceeded@PurnenduMIshra129th has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 25 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (8)
WalkthroughThis pull request introduces a new GraphQL query Changes
Assessment against linked issues
Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
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.
Actionable comments posted: 4
🧹 Nitpick comments (4)
src/resolvers/Query/verifyRole.ts (2)
37-38
: Prefer standard "Bearer " parsing.
To adhere to common API security patterns, split the token from "Bearer " instead of using the entire header string.- const token = authHeader; + const token = authHeader.split(' ')[1] || '';
66-69
: Maintain consistent error handling strategy.
Returning{ role: "", isAuthorized: false }
on any token verification failure is valid, but consider providing additional context or using standardized error handling for consistent logging & debugging.src/typeDefs/queries.ts (1)
228-228
: Add optional field documentation.
While the new field is self-explanatory, consider adding a short doc comment describing the purpose and usage ofverifyRole
for uniformity and clarity alongside other queries.src/typeDefs/types.ts (1)
846-849
: Maintain alphabetical ordering of types.According to the file's comment: "Place fields alphabetically to ensure easier lookup and navigation." The
VerifyRoleResponse
type should be moved to maintain alphabetical ordering.Move the type definition between
VerifyRoleResponse
andVenue
types to maintain alphabetical ordering.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
schema.graphql
(2 hunks)src/resolvers/Query/index.ts
(2 hunks)src/resolvers/Query/verifyRole.ts
(1 hunks)src/typeDefs/queries.ts
(1 hunks)src/typeDefs/types.ts
(1 hunks)src/types/generatedGraphQLTypes.ts
(7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Testing Application (22.x)
- GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (8)
src/resolvers/Query/verifyRole.ts (2)
7-22
: Good documentation approach.
The comprehensive docstring provides a clear explanation of the resolver's purpose, parameters, and return type, which improves maintainability.
50-53
: Confirm the hard-coded filter on user profile.
You’re filtering user profiles bytokenVersion: 0
andappLanguageCode: "en"
. Verify that this is the desired behavior, as users with different languages or token versions may experience unexpected access denials.✅ Verification successful
The hard-coded filters are intentional security and localization features.
ThetokenVersion: 0
matches the schema's default value and is part of the token validation system, whileappLanguageCode: "en"
sets the default language. These filters are working as designed and won't cause unexpected access denials.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify user profiles alignment with tokenVersion=0 and appLanguageCode="en" # Additionally, confirm no users are missed. # Searching for any code references that assume different tokenVersion or appLanguageCode usage rg -A 5 'AppUserProfile\.findOne'Length of output: 74075
Script:
#!/bin/bash # Search for tokenVersion related code and comments echo "=== Searching for tokenVersion usage and related comments ===" rg -B 3 -A 3 'tokenVersion' echo -e "\n=== Looking for AppUserProfile schema/model definition ===" fd -e ts -e js AppUserProfile echo -e "\n=== Searching for documentation about these fields ===" rg -B 3 -A 3 -i "appLanguageCode|tokenVersion" "*.md"Length of output: 27900
src/resolvers/Query/index.ts (2)
60-60
: Import statement looks good.
Adding theverifyRole
import cleanly integrates the new resolver; no issues found here.
121-121
: Query object update is correct.
RegisteringverifyRole
aligns with the GraphQL definitions, enabling the new query at runtime.src/typeDefs/types.ts (1)
846-849
: Verify resolver implementation for security.Since this type is used for authorization decisions, ensure that the resolver implementation:
- Properly validates the JWT token
- Has comprehensive error handling
- Logs security-relevant events
- Returns appropriate error responses
Let's verify the resolver implementation:
✅ Verification successful
Implementation follows security best practices ✅
The resolver implementation demonstrates robust security measures including proper JWT validation, database verification, and comprehensive error handling. The code follows security best practices for authentication and authorization flows.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for the resolver implementation echo "Searching for verifyRole resolver implementation..." rg -l "verifyRole.*resolver" src/ # Check for JWT validation echo "Checking JWT validation in the resolver..." rg "verify.*token" src/ # Check for error handling echo "Checking error handling..." rg "throw|catch|error" src/ -g "verifyRole*"Length of output: 523
Script:
#!/bin/bash # Get the complete implementation of verifyRole resolver echo "Fetching verifyRole resolver implementation..." cat src/resolvers/Query/verifyRole.ts # Check for JWT-related imports and utilities echo -e "\nChecking for JWT-related imports..." rg "import.*jwt" src/ rg "import.*token" src/Length of output: 3678
src/types/generatedGraphQLTypes.ts (3)
3349-3354
: LGTM! Clean type definition for VerifyRoleResponse.The type definition is well-structured with appropriate nullable fields for authorization status and role.
2410-2410
: LGTM! Well-defined query addition.The verifyRole query is properly integrated into the Query type with appropriate return type.
5115-5120
: LGTM! Resolver implementation follows best practices.The VerifyRoleResponse resolver is correctly implemented with proper typing for all fields.
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.
Actionable comments posted: 5
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/resolvers/Query/verifyRole.ts
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Testing Application (22.x)
- GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (2)
src/resolvers/Query/verifyRole.ts (2)
1-23
: Well-documented implementation with appropriate imports!The imports are well-organized and the JSDoc documentation comprehensively explains the query's purpose, parameters, and behavior.
24-28
: Clean resolver signature with proper typing!The function signature follows GraphQL resolver patterns and demonstrates good TypeScript practices by explicitly typing unused parameters as
unknown
.
Closing. You are not assigned the issue |
@palisadoes yes i knew it but for frontend to start this one need to implemented . And i am waited too much for this issue to be fixed . |
As an exception |
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.
Actionable comments posted: 3
♻️ Duplicate comments (1)
schema.graphql (1)
1618-1618
:⚠️ Potential issueAdd authentication to the verifyRole query.
The
verifyRole
query should be protected with the@auth
directive to ensure it's only accessible to authenticated users.Apply this diff to secure the query:
- verifyRole: VerifyRoleResponse + """ + Verifies the role and authorization status of the current user. + Returns the user's role and whether they are authorized. + """ + verifyRole: VerifyRoleResponse @auth
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
schema.graphql
(2 hunks)src/resolvers/Query/verifyRole.ts
(1 hunks)src/typeDefs/types.ts
(1 hunks)src/types/generatedGraphQLTypes.ts
(7 hunks)tests/resolvers/Query/getVolunteerRanks.spec.ts
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/typeDefs/types.ts
- src/resolvers/Query/verifyRole.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
- GitHub Check: Testing Application (22.x)
- GitHub Check: Testing Application (22.x)
- GitHub Check: Analyse Code With CodeQL (typescript)
- GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (2)
tests/resolvers/Query/getVolunteerRanks.spec.ts (1)
80-80
: Verify the updated volunteer hours expectations.The test expectations for
hoursVolunteered
have been changed from 2 to 6 hours for both monthly and yearly time frames. Please ensure this aligns with changes in the implementation ofgetVolunteerRanks
.Run this script to check the implementation:
Also applies to: 97-97
✅ Verification successful
Test expectations correctly reflect the hours calculation logic
The change from 2 to 6 hours in the test expectations is correct. The implementation sums all volunteer hours within the specified timeframe, and for the monthly period, it correctly adds:
- 2 hours (today)
- 4 hours (two weeks ago)
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check the implementation of getVolunteerRanks to verify the hours calculation logic # Search for the implementation ast-grep --pattern 'getVolunteerRanks = async ($$$) => { $$$ }' # Search for any related test data setup rg -A 5 'createVolunteerAndActions'Length of output: 11232
Script:
#!/bin/bash # Find and examine the implementation and test data setup # Find the implementation file fd getVolunteerRanks.ts --type f # Check the implementation ast-grep --pattern 'export const getVolunteerRanks = async ($$$) => { $$$ }' # Check the helper function implementation cat tests/helpers/volunteers.tsLength of output: 7412
Script:
#!/bin/bash # Examine the implementation file cat src/resolvers/Query/getVolunteerRanks.tsLength of output: 4386
schema.graphql (1)
2169-2175
: 🛠️ Refactor suggestionUse the UserType enum for the role field.
The
role
field should use the existingUserType
enum instead ofString
to ensure type safety and consistent role values across the schema.Apply this diff to improve type safety:
type VerifyRoleResponse { """Whether the user is authorized for the requested action.""" isAuthorized: Boolean! """The role of the user (e.g., 'ADMIN', 'USER', etc.).""" - role: String! + role: UserType! }Likely invalid or redundant comment.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #3094 +/- ##
===========================================
- Coverage 97.68% 97.65% -0.03%
===========================================
Files 364 365 +1
Lines 18563 18630 +67
Branches 2677 2699 +22
===========================================
+ Hits 18133 18194 +61
- Misses 425 431 +6
Partials 5 5 ☔ View full report in Codecov by Sentry. |
Please fix the failing tests and make code rabbit approve the PR |
how will i solve the these two falling test cases ? is this due to test case not written for that component or what ? will any guide how to write test cases? small guidance can help me a lot. |
|
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.
- CodeCov states that 57 lines are missing covering tests. We need you work to get as close to 100% test code coverage.
- Please add test cases for your work. We cannot afford for such an important piece of code to be untested.
@palisadoes ok thanks |
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.
@palisadoes will i make separate test file like verifyRole.spec.ts then add test cases for these failed line. I did not know much about writing test it is my first time |
Thanks. You will learn a lot |
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.
Actionable comments posted: 0
🧹 Nitpick comments (13)
tests/resolvers/Query/verifyRole.spec.ts (3)
20-20
: Consider using a more specific type instead ofany
.Replace
any
with a proper type definition to improve type safety.- let req: any; + interface TestRequest { + headers: { + authorization: string; + }; + } + let req: TestRequest;🧰 Tools
🪛 GitHub Check: Check for linting, formatting, and type errors
[warning] 20-20:
Unexpected any. Specify a different type
121-121
: Avoid using the delete operator for better performance.The delete operator can impact performance. Consider using undefined assignment instead.
- delete process.env.ACCESS_TOKEN_SECRET; + process.env.ACCESS_TOKEN_SECRET = undefined;🧰 Tools
🪛 Biome (1.9.4)
[error] 121-121: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
34-38
: Consider reducing test setup duplication.The request object setup is repeated across multiple tests. Consider moving it to a helper function.
function createTestRequest(token: string = "Bearer validToken"): TestRequest { return { headers: { authorization: token, }, }; }Then use it in tests:
- const req = { - headers: { - authorization: "Bearer validToken", - }, - }; + const req = createTestRequest();Also applies to: 57-61, 80-84, 102-106
🧰 Tools
🪛 GitHub Check: CodeQL
[failure] 36-36: Hard-coded credentials
The hard-coded value "Bearer validToken" is used as authorization header.Dockerfile.dev (2)
9-9
: Consider pinning the npm version for reproducibility.For consistent builds across environments, consider specifying the exact npm version.
-RUN npm install +RUN npm install -g [email protected] \ + && npm install
15-19
: Add HEALTHCHECK instruction for container monitoring.Adding a healthcheck helps Docker monitor the container's health status.
EXPOSE 4000 +# Add healthcheck +HEALTHCHECK --interval=30s --timeout=3s \ + CMD curl -f http://localhost:4000/graphql || exit 1 + # Start the application CMD ["npm", "run", "dev"]Dockerfile.prod (2)
9-9
: Consider pinning the npm version for reproducibility.For consistent builds across environments, consider specifying the exact npm version.
-RUN npm install +RUN npm install -g [email protected] \ + && npm install
27-31
: Add security enhancements and healthcheck.Consider adding a non-root user and healthcheck for better security and monitoring.
# Expose the application port EXPOSE 4000 +# Create non-root user +RUN addgroup -S nodejs && adduser -S nodejs -G nodejs +USER nodejs + +# Add healthcheck +HEALTHCHECK --interval=30s --timeout=3s \ + CMD curl -f http://localhost:4000/graphql || exit 1 + # Start the application CMD ["npm", "run", "start"]docker-compose.dev.yaml (2)
116-116
: Add missing newline at end of file.Add a newline character at the end of the file to comply with POSIX standards.
talawa-network: +
🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 116-116: no new line character at the end of file
(new-line-at-end-of-file)
Line range hint
4-27
: Consider adding restart policies for all services.While
caddy
has a restart policy, other services don't. Consider adding restart policies for better reliability.Add
restart: unless-stopped
to mongo, redis-stack-server, minio, and talawa-api-dev services.Also applies to: 29-41, 43-61
docker-compose.prod.yaml (3)
42-60
: Minio Service Configuration
Theminio
service is properly set with environment variables, command, and resource limits.
- Note: Line 47 contains trailing spaces which should be removed to satisfy YAML lint requirements.
Proposed diff to remove trailing spaces on line 47:
- environment: + environment:🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 47-47: trailing spaces
(trailing-spaces)
89-106
: Caddy Service Addition
A newcaddy
service is added to support reverse proxy functionality with its own resource limits, port mappings, and volume mounts.
- Note: Trailing spaces are detected on line 106. Removing these will help maintain clean YAML formatting.
Proposed diff to fix trailing spaces on line 106:
- cpus: '0.25' - + cpus: '0.25'🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 106-106: trailing spaces
(trailing-spaces)
110-115
: Volume and Network Declarations
The volumes (mongo_data
,caddy_data
,caddy_config
) and the network (talawa-network
) are declared as expected.
- Note: The file is missing a newline at the end (line 115), which may trigger linting warnings. Please add a newline at the end of the file.
🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 115-115: no new line character at the end of file
(new-line-at-end-of-file)
src/resolvers/Query/verifyRole.ts (1)
53-60
: User Profile Retrieval
The code retrieves the user profile using the decoded token’suserId
along with configuration-based parameters (DEFAULT_LANGUAGE_CODE
andTOKEN_VERSION
).
- Suggestion: The check
if (appUserProfile == null || appUserProfile == undefined)
is redundant. This can be simplified toif (!appUserProfile)
.Proposed diff:
- if (appUserProfile == null || appUserProfile == undefined) { + if (!appUserProfile) {
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.json
is excluded by!**/package-lock.json
📒 Files selected for processing (8)
Dockerfile.dev
(1 hunks)Dockerfile.prod
(1 hunks)docker-compose.dev.yaml
(7 hunks)docker-compose.prod.yaml
(1 hunks)package.json
(3 hunks)src/resolvers/Query/verifyRole.ts
(1 hunks)tests/resolvers/Query/getVolunteerRanks.spec.ts
(4 hunks)tests/resolvers/Query/verifyRole.spec.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/resolvers/Query/getVolunteerRanks.spec.ts
🧰 Additional context used
📓 Learnings (1)
Dockerfile.prod (1)
Learnt from: PurnenduMIshra129th
PR: PalisadoesFoundation/talawa-api#2828
File: Dockerfile.prod:27-28
Timestamp: 2025-01-19T18:42:42.806Z
Learning: In the Talawa API project's Dockerfile.prod, use `node:alpine` as the final stage base image as per mentor's guidance, instead of version-specific Alpine images.
🪛 Biome (1.9.4)
tests/resolvers/Query/verifyRole.spec.ts
[error] 121-121: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
🪛 GitHub Check: CodeQL
tests/resolvers/Query/verifyRole.spec.ts
[failure] 24-24: Hard-coded credentials
The hard-coded value "Bearer validToken" is used as authorization header.
[failure] 36-36: Hard-coded credentials
The hard-coded value "Bearer validToken" is used as authorization header.
[failure] 59-59: Hard-coded credentials
The hard-coded value "Bearer validToken" is used as authorization header.
[failure] 82-82: Hard-coded credentials
The hard-coded value "Bearer validToken" is used as authorization header.
[failure] 104-104: Hard-coded credentials
The hard-coded value "Bearer validToken" is used as authorization header.
🪛 GitHub Check: Check for linting, formatting, and type errors
tests/resolvers/Query/verifyRole.spec.ts
[warning] 20-20:
Unexpected any. Specify a different type
🪛 YAMLlint (1.35.1)
docker-compose.prod.yaml
[error] 47-47: trailing spaces
(trailing-spaces)
[error] 106-106: trailing spaces
(trailing-spaces)
[error] 115-115: no new line character at the end of file
(new-line-at-end-of-file)
docker-compose.dev.yaml
[error] 116-116: no new line character at the end of file
(new-line-at-end-of-file)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Testing Application (22.x)
- GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (11)
docker-compose.dev.yaml (1)
29-29
: Verify Redis version compatibility.The switch from
redis-stack-server
toredis:8.0-M02-alpine
might affect functionality. Please ensure compatibility with your application's Redis usage patterns.✅ Verification successful
Below is an additional shell script command to more broadly search for advanced Redis commands (e.g., those associated with Redis modules like RediSearch, RedisJSON, RedisGraph, and RedisTimeSeries). This should help verify that there's no inadvertent dependency on features provided only by redis-stack-server that might be missing in
redis:8.0-M02-alpine
.Please run this script and share the results for further confirmation.
Redis version compatibility verified.
Our searches for advanced Redis module commands (FT., JSON., GRAPH., TS.) did not reveal any usage within the codebase, indicating that there are no dependencies on Redis Stack–specific features. This suggests that switching toredis:8.0-M02-alpine
should not affect Redis functionality within the application.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for Redis-specific features in the codebase echo "Searching for Redis commands that might not be available in redis:8.0-M02-alpine..." rg -i "redis\.(json|search|graph|timeseries)" -A 3Length of output: 229
Script:
#!/bin/bash echo "Searching for advanced Redis commands (e.g., FT.*, JSON.*, GRAPH.*, TS.*) usage in the codebase..." rg -i "(FT\.ADD|FT\.SEARCH|JSON\.SET|JSON\.GET|GRAPH\.QUERY|TS\.ADD)" -A 3Length of output: 283
docker-compose.prod.yaml (3)
3-26
: Mongo Service Configuration Update
Themongo
service is now defined with an updated image, container name, and healthcheck along with resource limits and bindings (ports restricted to 127.0.0.1). This configuration is aligned with best practices for production deployments.
28-35
: Redis Service Configuration Update
Theredis-stack-server
service now uses a specificredis:8.0-M02-alpine
image along with defined resource limits. The updated configuration ensures improved performance and better resource allocation.
61-89
: Talawa API Production Service Updates
The service previously known astalawa-api-prod-container
is now renamed totalawa-api-prod
with updated container naming, port mapping, volume declarations, and connection URLs reflecting the newmongo
service. These changes integrate well with the overall architecture.src/resolvers/Query/verifyRole.ts (4)
29-40
: Token Extraction and Preliminary Checks
The resolver correctly extracts the JWT from the request'sAuthorization
header. It handles missing headers and tokens by returning an unauthorized status, ensuring that further processing occurs only when a valid token is present.
65-75
: User Role Determination
The role assignment logic is clear and functions as intended. The default role is "user", and it upgrades to "superAdmin" or "admin" based onisSuperAdmin
and the presence of items inadminFor
.
80-93
: Error Handling and Response
The catch block sanitizes error logs to avoid exposing sensitive details and returns a differentiated error message based on whether the error is a JWT-specific issue. This approach enhances the security of error reporting.
41-48
: JWT Verification Security Note
Token verification is performed usingjwt.verify()
with a check to ensure that theACCESS_TOKEN_SECRET
is defined. For enhanced security, consider explicitly specifying options (such asalgorithms: ['HS256']
and an appropriatemaxAge
) when verifying the token.Example diff:
- const decoded = jwt.verify( - token, - process.env.ACCESS_TOKEN_SECRET as string, - ); + const decoded = jwt.verify( + token, + process.env.ACCESS_TOKEN_SECRET as string, + { algorithms: ['HS256'], maxAge: '1h' } + );package.json (3)
10-12
: Script Updates for Minio Checks and Startup
The"minio:check"
script now runs the build process before executing the Minio installation check. Similarly,"start:with-minio"
is updated to runindex.js
(instead ofserver.js
) and concurrently execute the Minio check. These modifications improve deployment consistency and startup reliability.
25-25
: Prepare Script Improvement
The"prepare"
script now conditionally executeshusky
only if it is installed, preventing errors during setup whenhusky
is absent. This change enhances the robustness of the development workflow.
106-108
: Dependency Updates
The dependency section now reflects the addition of"cls-bluebird"
and maintains"cls-hooked"
. Also,"zod-error"
is positioned appropriately. Please verify that these dependencies are correctly integrated with related modules and do not introduce conflicts.
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.
Actionable comments posted: 1
🧹 Nitpick comments (1)
tests/resolvers/Query/verifyRole.spec.ts (1)
183-206
: Test: Duplicate Validation for a Valid User Profile
This test again validates the “user” role for a valid user profile and is largely similar to the earlier valid user token test. Consider consolidating similar tests to reduce redundancy unless the slight differences are intentional.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
tests/resolvers/Query/verifyRole.spec.ts
(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
tests/resolvers/Query/verifyRole.spec.ts
[error] 231-231: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
🪛 GitHub Check: CodeQL
tests/resolvers/Query/verifyRole.spec.ts
[failure] 11-11: Hard-coded credentials
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
[failure] 42-42: Hard-coded credentials
The hard-coded value "validToken" is used as authorization header.
🪛 GitHub Check: Check for linting, formatting, and type errors
tests/resolvers/Query/verifyRole.spec.ts
[warning] 21-21:
Unexpected any. Specify a different type
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Testing Application (22.x)
- GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (14)
tests/resolvers/Query/verifyRole.spec.ts (14)
1-5
: Import Statements and Module Setup
The import statements are clear and organized. Consider adding stricter type definitions when applicable to reduce reliance on “any” later in the tests.
7-11
: Environment Variable Initialization & Hard-coded Token
Environment variables are set for testing, and a test token is defined as"validToken"
. Note that the hard-coded token value is flagged by static analysis for hard-coded credentials. While it may be acceptable in a trusted test environment, consider parameterizing or externalizing such values if the test suite is shared broadly.🧰 Tools
🪛 GitHub Check: CodeQL
[failure] 11-11: Hard-coded credentials
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
12-19
: Mocking the Database Call for AppUserProfile
The use ofvi.mock
to simulate the database call with a predefinedlean
method is appropriate. Ensure that this mock remains in sync with any future changes toAppUserProfile
’s API.
21-29
: BeforeEach Setup and Global Mock Restoration
Initializing the request object (req
) in thebeforeEach
hook is good practice. However, callingvi.restoreAllMocks()
after setting upreq
might reset some spies or mocks needed for the current test. Consider restoring mocks at the beginning of the hook or confirming that all necessary mocks are reinitialized per test.🧰 Tools
🪛 GitHub Check: Check for linting, formatting, and type errors
[warning] 21-21:
Unexpected any. Specify a different type
31-40
: Test: Authorization Header Missing
This test properly verifies that the absence of an Authorization header leads to an unauthorized result. The defensive check ensuringverifyRole
is defined is cautious and acceptable.
41-60
: Test: Token Without 'Bearer' Prefix
The test correctly simulates the scenario where the token does not include the “Bearer” prefix by manually setting the header. The use of hard-coded credentials (“validToken”) is consistent with previous lines but remains flagged. Consider reusing a test configuration variable if this pattern repeats in other tests.🧰 Tools
🪛 GitHub Check: CodeQL
[failure] 42-42: Hard-coded credentials
The hard-coded value "validToken" is used as authorization header.
62-81
: Test: Correct Token Extraction with 'Bearer ' Prefix
This test confirms that when the token is prefixed with “Bearer ” the extraction logic functions correctly. All mocks are set up properly for this scenario.
82-92
: Test: Token Missing After 'Bearer' Prefix
The test elegantly captures the edge case where the Authorization header contains “Bearer ” but no actual token. It asserts the expected unauthorized result.
93-114
: Test: Missing userId in Decoded Token
By simulating a decoded token without a userId, this test validates that the resolver returns an appropriate error message. The expected outcome, including the “Authentication failed” error, is clear.
116-137
: Test: Valid User Token Scenario
This test confirms that a valid user token (withuserId: "user123"
) leads to the correct role assignment and authorization. The mocked database response is consistent with the expected behavior.
138-159
: Test: Valid Admin Token Scenario
The test accurately simulates an admin scenario by checking that a user with an admin role (indicated by a non-emptyadminFor
list) receives the “admin” role. All assertions align with the intended logic.
160-182
: Test: Valid SuperAdmin Token Scenario
This test case effectively validates the superAdmin path by ensuring the resolver returns “superAdmin” for an appropriately flagged user.
207-228
: Test: User Not Found in Database
The test simulates the scenario where the database returns no matching user and checks for the correct error response. The logic is sound and clear.
245-262
: Test: Malformed Token Handling
The test usesvi.stubGlobal
to overridejwt.verify
so that it throws an error, simulating a malformed token. This is an effective way to test the error handling. However, overriding global objects can lead to unintended side effects. Verify that the override is properly confined to this test’s scope and restored afterward.
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.
Actionable comments posted: 0
🧹 Nitpick comments (4)
tests/resolvers/Query/verifyRole.spec.ts (4)
21-21
: Avoid Usingany
for Request Object
The declarationlet req: any;
could be replaced with a more specific type (for example, a custom interface mimicking the expected request shape) to improve type safety within the tests.🧰 Tools
🪛 GitHub Check: Check for linting, formatting, and type errors
[warning] 21-21:
Unexpected any. Specify a different type
31-262
: Consolidate Verification ofverifyRole
Existence
Each test checks ifverifyRole
is defined before proceeding. To reduce repetitive code, consider asserting its existence once in abeforeAll
block. This will simplify individual test cases and make the suite easier to maintain.
183-206
: Consolidate Duplicate User Role Test
There are two test cases that validate returning the role"user"
for a valid token (one between lines 116–137 and another between lines 183–206). Consider consolidating these to avoid redundancy while still covering all necessary conditions.
246-262
: Refactor Global Stub for Malformed Token Handling
In the test for a malformed token,vi.stubGlobal
is used to overridejwt.verify
. This approach can lead to unintended side effects if the global override isn’t properly restored. A safer alternative is to usevi.spyOn(jwt, "verify").mockImplementationOnce(...)
to simulate the error condition. For example:- const verify = vi.fn().mockImplementation(() => { - throw new Error("jwt malformed"); - }); - vi.stubGlobal("jwt", { ...jwt, verify }); + vi.spyOn(jwt, "verify").mockImplementationOnce(() => { + throw new Error("jwt malformed"); + });This change ensures the override is limited to a single call and will be automatically restored by the test framework.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
tests/resolvers/Query/getVolunteerRanks.spec.ts
(3 hunks)tests/resolvers/Query/verifyRole.spec.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/resolvers/Query/getVolunteerRanks.spec.ts
🧰 Additional context used
🪛 GitHub Check: CodeQL
tests/resolvers/Query/verifyRole.spec.ts
[failure] 11-11: Hard-coded credentials
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
🪛 GitHub Check: Check for linting, formatting, and type errors
tests/resolvers/Query/verifyRole.spec.ts
[warning] 21-21:
Unexpected any. Specify a different type
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Testing Application (22.x)
- GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (2)
tests/resolvers/Query/verifyRole.spec.ts (2)
7-11
: Test Environment Setup & Hard-Coded Token
The test setup uses hard-coded environment variables and a token ("validToken"
). While this is acceptable in a test context, be aware that static analysis flags hard-coded credentials. Consider defining these values as constants or fixtures if they will be reused across multiple tests.🧰 Tools
🪛 GitHub Check: CodeQL
[failure] 11-11: Hard-coded credentials
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
11-11
: Hard-Coded Credential Warning
The literal token value"validToken"
is used directly (and later in authorization headers). For clarity and maintainability, you might consider using a dedicated constant or a fixture for test tokens.🧰 Tools
🪛 GitHub Check: CodeQL
[failure] 11-11: Hard-coded credentials
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
The hard-coded value "validToken" is used as authorization header.
line-30 Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
line -86 Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
line - 1618 Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
line - 37 Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
line-44 Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
line-52 Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
The merge-base changed after approval.
ee1d152
to
c47c565
Compare
Please fix the failing CodeQL tests for file |
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.
Will this cause the develop
branch of Talawa Admin to break?
@palisadoes No because the token is the part of login and signin process. We do not need to be generated in our test case. So it will not break |
595feaa
into
PalisadoesFoundation:develop
What kind of change does this PR introduce?
Feature
Issue Number:
Fixes #2835
Snapshots/Videos:
this is for user
this is for admin and superadmin
If relevant, did you update the documentation?
For now i am not updated the documentaion,because it is not assigned to me.
Summary
1.Added query for to check authorization and role for user from server side.
2.During routing process in each pages the user will visit it will go via through this query if it is validate then only user will be able to visit the page.
3.As a result the user have limited access to the pages and can't access the unauthorized pages.
4.Previously user is able to access the unauthorized pages by directly changing the url.
5.Also by this method the tampering of jwt token will be prevented.
Does this PR introduce a breaking change?
No
Checklist
CodeRabbit AI Review
Test Coverage
Have you read the contributing guide?
Yes
Summary by CodeRabbit
New Features
VerifyRoleResponse
to return role and authorization status.Documentation
These changes enable users to verify their current role and authorization status through a new GraphQL query, enhancing the application's access control mechanisms.