Skip to content

Commit bed4347

Browse files
authored
Merge pull request #17 from Layyzyy/fix-user-details-visibility
Fix: Display user details on UI when user is logged in
2 parents 4f1a56b + 0d8cd6b commit bed4347

File tree

3 files changed

+92
-21
lines changed

3 files changed

+92
-21
lines changed

auth-server/handlers.go

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ func getReportsHandler(c *gin.Context) {
149149

150150
var reports []Report
151151
filter := bson.M{"user_id": userID}
152+
152153
cursor, err := reportsColl.Find(ctx, filter)
153154
if err != nil {
154155
if err == mongo.ErrNoDocuments {
@@ -191,4 +192,65 @@ func getReportsHandler(c *gin.Context) {
191192
Message: "Reports fetched successfully",
192193
Data: reports,
193194
})
194-
}
195+
}
196+
197+
// New handler to get user information
198+
func getUserInfoHandler(c *gin.Context) {
199+
userID := c.GetString("userID")
200+
log.Println("[DEBUG] Getting user info for userID:", userID)
201+
202+
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
203+
defer cancel()
204+
205+
// Convert userID string to ObjectID
206+
objectID, err := primitive.ObjectIDFromHex(userID)
207+
if err != nil {
208+
c.JSON(http.StatusBadRequest, ErrorResponse{
209+
Error: "invalid_user_id",
210+
Message: "Invalid user ID format",
211+
})
212+
return
213+
}
214+
215+
// Find user by ID
216+
var user User
217+
err = usersColl.FindOne(ctx, bson.M{"_id": objectID}).Decode(&user)
218+
if err != nil {
219+
if err == mongo.ErrNoDocuments {
220+
c.JSON(http.StatusNotFound, ErrorResponse{
221+
Error: "user_not_found",
222+
Message: "User not found",
223+
})
224+
return
225+
}
226+
c.JSON(http.StatusInternalServerError, ErrorResponse{
227+
Error: "database_error",
228+
Message: "Failed to fetch user information",
229+
})
230+
return
231+
}
232+
233+
// Count number of reports (attacks) for this user
234+
reportsCount, err := reportsColl.CountDocuments(ctx, bson.M{"user_id": userID})
235+
if err != nil {
236+
log.Println("[ERROR] Failed to count reports:", err)
237+
// Continue even if count fails, just set to 0
238+
reportsCount = 0
239+
}
240+
241+
// Prepare response with user info
242+
userInfo := map[string]interface{}{
243+
"user_id": user.ID.Hex(),
244+
"email": user.Email,
245+
"first_name": user.FirstName,
246+
"last_name": user.LastName,
247+
"username": user.FirstName + " " + user.LastName,
248+
"attacks_count": reportsCount,
249+
"created_at": user.CreatedAt,
250+
}
251+
252+
c.JSON(http.StatusOK, SuccessResponse{
253+
Message: "User information fetched successfully",
254+
Data: userInfo,
255+
})
256+
}

auth-server/main.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ var (
2222
)
2323

2424
func main() {
25-
2625
// Load Env Variables
2726
err := godotenv.Load()
2827
if err != nil {
@@ -70,6 +69,7 @@ func main() {
7069
{
7170
auth.POST("/signup", signupHandler)
7271
auth.POST("/login", loginHandler)
72+
auth.GET("/getUserInfo", authMiddleware(), getUserInfoHandler)
7373
}
7474
}
7575

@@ -97,7 +97,6 @@ func conn_DB() error {
9797
}
9898

9999
dbName := os.Getenv("DATABASE_NAME")
100-
101100
db = mongo_client.Database(dbName)
102101
usersColl = db.Collection("auth")
103102
reportsColl = db.Collection("reports")

frontend/src/components/Navbar.jsx

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import React, { useState } from 'react';
1+
import React, { useState, useEffect } from 'react';
22
import { Link, useNavigate } from "react-router-dom";
3-
import api from "../components/api";LayoutDashboard
3+
import api from "../components/api";
44
import { Shield, Home, History, Info, UserCircle, LogOut, X, LayoutDashboard } from 'lucide-react';
55
import { handleError } from './utils';
66

@@ -15,46 +15,54 @@ const Navbar = () => {
1515
navigate("/login");
1616
}, 1500);
1717
};
18+
1819
// State to manage the visibility of the profile card.
1920
const [showProfileCard, setShowProfileCard] = useState(false);
20-
const [userData, setUserData] = useState({});
21+
const [userData, setUserData] = useState({
22+
username: '',
23+
email: '',
24+
attacks_count: 0
25+
});
2126

2227
const fetchUserData = async () => {
2328
try {
24-
const res = await api.get('/api/user/profile');
29+
const res = await api.get('/api/auth/getUserInfo');
2530
const data = await res.data;
26-
setUserData(data);
31+
if (data && data.data) {
32+
setUserData(data.data);
33+
}
2734
} catch (err) {
2835
handleError('Error fetching user data:', err);
29-
setTimeout(() => {
30-
Logout();
31-
navigate("/login");
32-
}, 1500);
3336
}
3437
};
3538

39+
// Fetch user data when component mounts
40+
useEffect(() => {
41+
fetchUserData();
42+
}, []);
43+
3644
// The main JSX for the Navbar.
3745
return (
3846
<nav className="fixed top-0 inset-x-0 z-20 bg-black/40 backdrop-blur-md rounded-b-xl px-6 py-4 shadow-xl">
3947
<div className="container mx-auto flex items-center justify-between">
4048
{/* Logo/App Title */}
41-
<a href="#" className="flex items-center text-white text-xl font-bold tracking-wider">
49+
<a className="flex items-center text-white text-xl font-bold tracking-wider" href="#">
4250
<Shield className="w-8 h-8 mr-2 text-green-400" />
4351
VULN<span className="text-green-400">ORA</span>
4452
</a>
4553

4654
{/* Navigation Links */}
4755
<div className="flex items-center space-x-6">
48-
<Link to="/" className="flex items-center text-gray-400 hover:text-green-400 transition-colors">
56+
<Link className="flex items-center text-gray-400 hover:text-green-400 transition-colors" to="/">
4957
<Home className="w-5 h-5 mr-1" /> Home
5058
</Link>
51-
<Link to="/home" className="flex items-center text-gray-400 hover:text-green-400 transition-colors">
59+
<Link className="flex items-center text-gray-400 hover:text-green-400 transition-colors" to="/home">
5260
<LayoutDashboard className="w-5 h-5 mr-1" /> Dashboard
5361
</Link>
54-
<Link to="/history" className="flex items-center text-gray-400 hover:text-green-400 transition-colors">
62+
<Link className="flex items-center text-gray-400 hover:text-green-400 transition-colors" to="/history">
5563
<History className="w-5 h-5 mr-1" /> History
5664
</Link>
57-
<Link to="/#about" className="flex items-center text-gray-400 hover:text-green-400 transition-colors">
65+
<Link className="flex items-center text-gray-400 hover:text-green-400 transition-colors" to="/#about">
5866
<Info className="w-5 h-5 mr-1" /> About
5967
</Link>
6068
</div>
@@ -82,15 +90,17 @@ const Navbar = () => {
8290
<div className="flex items-center mb-4">
8391
<UserCircle className="w-10 h-10 text-green-400 mr-3" />
8492
<div>
85-
<h4 className="font-bold text-lg">{userData.firstName}</h4>
86-
<p className="text-xs text-gray-400">{userData.email}</p>
93+
<h4 className="font-bold text-lg">{userData.username || 'User'}</h4>
94+
<p className="text-xs text-gray-400">{userData.email || ''}</p>
8795
</div>
8896
</div>
97+
8998
<div className="text-sm border-t border-gray-700 pt-3 mb-3">
90-
<p className="text-gray-300">Scans Completed: <span className="text-green-400 font-semibold">
91-
{/* {userData.scansDone} */} XX {/*TODO: replace with actual value*/}
99+
<p className="text-gray-300">Attacks Run: <span className="text-green-400 font-semibold">
100+
{userData.attacks_count || 0}
92101
</span></p>
93102
</div>
103+
94104
<button
95105
onClick={() => {
96106
Logout();

0 commit comments

Comments
 (0)