Skip to content
This repository was archived by the owner on Nov 23, 2025. It is now read-only.

Commit aa67391

Browse files
authored
Merge pull request #17 from TechTorque-2025/randitha-superbranch
Randitha superbranch
2 parents 9c90c17 + 5b84c00 commit aa67391

14 files changed

Lines changed: 751 additions & 252 deletions

File tree

COMPLETE_FIX.sh

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
#!/bin/bash
2+
3+
echo "=========================================="
4+
echo "🔧 Complete Fix for User Roles Issue"
5+
echo "=========================================="
6+
echo ""
7+
8+
# Database connection details (adjust if needed)
9+
DB_HOST="${DB_HOST:-localhost}"
10+
DB_PORT="${DB_PORT:-5432}"
11+
DB_NAME="${DB_NAME:-techtorque}"
12+
DB_USER="${DB_USER:-techtorque}"
13+
DB_PASS="${DB_PASS:-techtorque123}"
14+
15+
echo "Step 1: Fixing database - Assigning roles to existing users"
16+
echo "Database: $DB_NAME @ $DB_HOST:$DB_PORT"
17+
echo ""
18+
19+
# SQL to fix existing data
20+
SQL=$(cat <<'EOSQL'
21+
-- Display current state
22+
SELECT 'BEFORE FIX:' as status;
23+
SELECT u.username, COUNT(ur.role_id) as role_count
24+
FROM users u
25+
LEFT JOIN user_roles ur ON u.id = ur.user_id
26+
GROUP BY u.id, u.username
27+
ORDER BY u.id;
28+
29+
-- Assign roles to all users based on their username
30+
-- Assign SUPER_ADMIN role
31+
INSERT INTO user_roles (user_id, role_id)
32+
SELECT u.id, r.id
33+
FROM users u
34+
CROSS JOIN roles r
35+
WHERE u.username = 'superadmin'
36+
AND r.name = 'SUPER_ADMIN'
37+
AND NOT EXISTS (
38+
SELECT 1 FROM user_roles ur
39+
WHERE ur.user_id = u.id AND ur.role_id = r.id
40+
);
41+
42+
-- Assign ADMIN role
43+
INSERT INTO user_roles (user_id, role_id)
44+
SELECT u.id, r.id
45+
FROM users u
46+
CROSS JOIN roles r
47+
WHERE u.username = 'admin'
48+
AND r.name = 'ADMIN'
49+
AND NOT EXISTS (
50+
SELECT 1 FROM user_roles ur
51+
WHERE ur.user_id = u.id AND ur.role_id = r.id
52+
);
53+
54+
-- Assign EMPLOYEE role
55+
INSERT INTO user_roles (user_id, role_id)
56+
SELECT u.id, r.id
57+
FROM users u
58+
CROSS JOIN roles r
59+
WHERE u.username = 'employee'
60+
AND r.name = 'EMPLOYEE'
61+
AND NOT EXISTS (
62+
SELECT 1 FROM user_roles ur
63+
WHERE ur.user_id = u.id AND ur.role_id = r.id
64+
);
65+
66+
-- Assign CUSTOMER role to customer and test users
67+
INSERT INTO user_roles (user_id, role_id)
68+
SELECT u.id, r.id
69+
FROM users u
70+
CROSS JOIN roles r
71+
WHERE u.username IN ('customer', 'user', 'testuser', 'demo', 'test')
72+
AND r.name = 'CUSTOMER'
73+
AND NOT EXISTS (
74+
SELECT 1 FROM user_roles ur
75+
WHERE ur.user_id = u.id AND ur.role_id = r.id
76+
);
77+
78+
-- Display fixed state
79+
SELECT 'AFTER FIX:' as status;
80+
SELECT u.username, u.email, r.name as role_name
81+
FROM users u
82+
INNER JOIN user_roles ur ON u.id = ur.user_id
83+
INNER JOIN roles r ON ur.role_id = r.id
84+
ORDER BY u.id, r.name;
85+
86+
-- Summary
87+
SELECT 'SUMMARY:' as status;
88+
SELECT u.username,
89+
ARRAY_AGG(r.name ORDER BY r.name) as roles
90+
FROM users u
91+
LEFT JOIN user_roles ur ON u.id = ur.user_id
92+
LEFT JOIN roles r ON ur.role_id = r.id
93+
GROUP BY u.id, u.username
94+
ORDER BY u.id;
95+
EOSQL
96+
)
97+
98+
# Execute SQL
99+
echo "Executing SQL fixes..."
100+
PGPASSWORD="$DB_PASS" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" << EOF
101+
$SQL
102+
EOF
103+
104+
echo ""
105+
echo "=========================================="
106+
echo "Step 2: Restart Authentication Service"
107+
echo "=========================================="
108+
echo ""
109+
echo "The User entity has been fixed with cascade settings."
110+
echo "You need to rebuild and restart the service:"
111+
echo ""
112+
echo " cd Authentication/auth-service"
113+
echo " mvn clean install -DskipTests"
114+
echo " mvn spring-boot:run"
115+
echo ""
116+
echo "Or if running in Docker:"
117+
echo " docker-compose restart auth-service"
118+
echo ""
119+
echo "=========================================="
120+
echo "✅ Fix Complete!"
121+
echo "=========================================="
122+
echo ""
123+
echo "What was fixed:"
124+
echo "1. ✅ Added cascade settings to User entity @ManyToMany relationship"
125+
echo "2. ✅ Assigned roles to all existing users in database"
126+
echo ""
127+
echo "Test the fix:"
128+
echo "1. Login again:"
129+
echo ' curl -X POST http://localhost:8081/login \'
130+
echo ' -H "Content-Type: application/json" \'
131+
echo ' -d '"'"'{"username":"customer","password":"cust123"}'"'"
132+
echo ""
133+
echo "2. Decode JWT at https://jwt.io - should show roles"
134+
echo ""
135+
echo "3. Test /users/me with the new token"
136+
echo ""

LOGIN_ISSUE_FIX.md

Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
# 🔧 Login Issue Fix - Empty Roles in JWT Token
2+
3+
## 🎯 Problem Summary
4+
5+
**Symptom**: User can login successfully but gets `403 Forbidden` when accessing `/api/v1/users/me`
6+
7+
**Root Cause**: The JWT token contains `"roles":[]` (empty array) because the user in the database has no roles assigned in the `user_roles` table.
8+
9+
**Error in logs**:
10+
```
11+
Access denied: Access Denied
12+
AuthorizationDeniedException: Access Denied
13+
```
14+
15+
## 🔍 Diagnosis
16+
17+
Your JWT token shows:
18+
```json
19+
{
20+
"roles": [], // <-- EMPTY! This is the problem
21+
"sub": "customer",
22+
"iat": 1762805825,
23+
"exp": 1762892225
24+
}
25+
```
26+
27+
The endpoint requires:
28+
```java
29+
@PreAuthorize("hasRole('CUSTOMER') or hasRole('EMPLOYEE') or hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
30+
```
31+
32+
Since the roles array is empty, Spring Security denies access.
33+
34+
## ✅ Solution Options
35+
36+
### Option 1: Fix via SQL (Immediate Fix)
37+
38+
Connect to your database and run:
39+
40+
```bash
41+
# Connect to MySQL/MariaDB
42+
mysql -u root -p techtorque
43+
44+
# Or connect to PostgreSQL
45+
# psql -U postgres -d techtorque
46+
```
47+
48+
Then execute:
49+
```sql
50+
-- Check current user roles
51+
SELECT u.username, u.email, r.name as role_name
52+
FROM users u
53+
LEFT JOIN user_roles ur ON u.id = ur.user_id
54+
LEFT JOIN roles r ON ur.role_id = r.id
55+
WHERE u.username = 'customer';
56+
57+
-- Assign CUSTOMER role if missing
58+
INSERT INTO user_roles (user_id, role_id)
59+
SELECT u.id, r.id
60+
FROM users u, roles r
61+
WHERE u.username = 'customer'
62+
AND r.name = 'CUSTOMER'
63+
AND NOT EXISTS (
64+
SELECT 1 FROM user_roles ur
65+
WHERE ur.user_id = u.id AND ur.role_id = r.id
66+
);
67+
68+
-- Verify fix
69+
SELECT u.username, r.name as role_name
70+
FROM users u
71+
INNER JOIN user_roles ur ON u.id = ur.user_id
72+
INNER JOIN roles r ON ur.role_id = r.id
73+
WHERE u.username = 'customer';
74+
```
75+
76+
**Quick script included**: Run `Authentication/fix_user_roles.sql`
77+
78+
### Option 2: Delete and Recreate Users (Clean Slate)
79+
80+
If you want to start fresh:
81+
82+
```sql
83+
-- Delete all users (roles and other tables will be preserved)
84+
DELETE FROM user_roles;
85+
DELETE FROM users;
86+
87+
-- Restart your Authentication service to trigger DataSeeder
88+
# The DataSeeder will recreate all default users with proper roles
89+
```
90+
91+
Then restart the Authentication service:
92+
```bash
93+
cd Authentication/auth-service
94+
mvn spring-boot:run
95+
```
96+
97+
### Option 3: Use Admin Endpoint to Assign Role
98+
99+
If you have access to an admin account with a valid token:
100+
101+
```bash
102+
ADMIN_TOKEN="your-admin-jwt-token"
103+
104+
curl -X POST "http://localhost:8081/users/customer/roles" \
105+
-H "Authorization: Bearer $ADMIN_TOKEN" \
106+
-H "Content-Type: application/json" \
107+
-d '{
108+
"role": "CUSTOMER",
109+
"action": "ASSIGN"
110+
}'
111+
```
112+
113+
## 🧪 Verify the Fix
114+
115+
After applying the fix:
116+
117+
### 1. Login Again
118+
```bash
119+
curl -X POST http://localhost:8081/login \
120+
-H "Content-Type: application/json" \
121+
-d '{
122+
"username": "customer",
123+
"password": "cust123"
124+
}' | jq
125+
```
126+
127+
### 2. Check JWT Token
128+
Decode the token at https://jwt.io and verify it now shows:
129+
```json
130+
{
131+
"roles": ["CUSTOMER"], // <-- Should have role now!
132+
"sub": "customer",
133+
...
134+
}
135+
```
136+
137+
### 3. Test /users/me Endpoint
138+
```bash
139+
TOKEN="your-new-jwt-token"
140+
141+
curl -X GET http://localhost:8081/users/me \
142+
-H "Authorization: Bearer $TOKEN" | jq
143+
```
144+
145+
**Expected**: Should return `200 OK` with user profile
146+
147+
### 4. Test via API Gateway
148+
```bash
149+
curl -X GET http://localhost:8080/api/v1/users/me \
150+
-H "Authorization: Bearer $TOKEN" | jq
151+
```
152+
153+
## 🔧 Prevention - Ensure Data Seeder Works
154+
155+
Check your `application.properties` or `application.yml`:
156+
157+
```properties
158+
# Make sure dev profile is active for development
159+
spring.profiles.active=dev
160+
161+
# Or set environment variable
162+
# SPRING_PROFILES_ACTIVE=dev
163+
```
164+
165+
The `DataSeeder` only creates test users in `dev` profile. Make sure it's active:
166+
167+
```bash
168+
# Check if seeder ran on startup
169+
# Look for these logs when starting the service:
170+
# "Starting data seeding..."
171+
# "Created role: CUSTOMER"
172+
# "Created user: customer with role CUSTOMER"
173+
# "Data seeding completed successfully!"
174+
```
175+
176+
## 📊 Database Schema Reference
177+
178+
Correct structure for user-role assignment:
179+
180+
```
181+
users table:
182+
+----+----------+-------------------+
183+
| id | username | email |
184+
+----+----------+-------------------+
185+
| 1 | customer | customer@... |
186+
+----+----------+-------------------+
187+
188+
roles table:
189+
+----+----------+
190+
| id | name |
191+
+----+----------+
192+
| 1 | CUSTOMER |
193+
+----+----------+
194+
195+
user_roles table (join table):
196+
+---------+---------+
197+
| user_id | role_id |
198+
+---------+---------+
199+
| 1 | 1 | <-- This row MUST exist!
200+
+---------+---------+
201+
```
202+
203+
## 🚨 Common Causes
204+
205+
1. **DataSeeder didn't run** - Not in dev profile
206+
2. **Database was reset** - Roles exist but user_roles table is empty
207+
3. **Manual user creation** - User created without assigning roles
208+
4. **Transaction rollback** - Role assignment failed during user creation
209+
210+
## 📞 Still Having Issues?
211+
212+
Check Authentication service logs for:
213+
```
214+
Hibernate: select r1_0.user_id ... from user_roles r1_0 ... where r1_0.user_id=?
215+
```
216+
217+
If this query returns 0 rows, the user has no roles assigned.
218+
219+
Enable debug logging in `application.properties`:
220+
```properties
221+
logging.level.com.techtorque.auth_service=DEBUG
222+
logging.level.org.hibernate.SQL=DEBUG
223+
logging.level.org.springframework.security=DEBUG
224+
```
225+
226+
## ✅ Summary Checklist
227+
228+
- [ ] User exists in database
229+
- [ ] Roles exist in database (CUSTOMER, EMPLOYEE, ADMIN, SUPER_ADMIN)
230+
- [ ] User-role mapping exists in `user_roles` table
231+
- [ ] JWT token contains roles array with at least one role
232+
- [ ] Can access `/users/me` endpoint with 200 response
233+
- [ ] DataSeeder ran successfully on service startup
234+
235+
---
236+
237+
**Created**: 2025-11-11
238+
**Issue**: Empty roles in JWT causing 403 Forbidden on authenticated endpoints
239+
**Resolution**: Ensure user has roles assigned in user_roles table

0 commit comments

Comments
 (0)