Skip to content

Commit 77c5f93

Browse files
committed
feat: Implement User Activity Logging System
- Added a comprehensive activity logging system to track user actions for security auditing and compliance. - Introduced new endpoints for retrieving user activity logs with pagination and filtering. - Implemented logging for various user actions including login, logout, registration, password changes, and 2FA events. - Enhanced API documentation to include new activity log features and updated response formats. - Created a dedicated service and repository for managing activity logs in the database. - Updated user and social authentication handlers to log relevant activities. - Added utility functions to extract client IP and user agent for logging purposes.
1 parent e1a2d58 commit 77c5f93

File tree

20 files changed

+2148
-100
lines changed

20 files changed

+2148
-100
lines changed

README.md

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ A modern, production-ready Go REST API for authentication and authorization, fea
77
## 🚀 Features
88
- Secure user registration & login (JWT access/refresh tokens)
99
- **Two-Factor Authentication (2FA) with TOTP and recovery codes**
10+
- **User Activity Logs with pagination and filtering**
1011
- Social login: Google, Facebook, GitHub
1112
- Email verification & password reset
1213
- Role-based access control (middleware)
@@ -24,6 +25,7 @@ internal/ # Core logic
2425
├── user/ # User management
2526
├── social/ # Social authentication (OAuth2)
2627
├── twofa/ # Two-Factor Authentication
28+
├── log/ # Activity logging system
2729
├── email/ # Email verification & password reset
2830
├── middleware/ # JWT auth middleware
2931
├── database/ # Database connection & migrations
@@ -158,6 +160,12 @@ The following `make` commands are available for development, testing, building,
158160
### User Management
159161
- `GET /profile` — Get user profile (protected)
160162

163+
### Activity Logs
164+
- `GET /activity-logs` — Get authenticated user's activity logs with pagination and filtering (protected)
165+
- `GET /activity-logs/:id` — Get specific activity log by ID (protected)
166+
- `GET /activity-logs/event-types` — Get available event types for filtering (protected)
167+
- `GET /admin/activity-logs` — Get all users' activity logs for admin use (protected)
168+
161169
## 📦 API Response Format
162170
**Success:**
163171
```json
@@ -193,6 +201,83 @@ The following `make` commands are available for development, testing, building,
193201
3. Provider redirects back to callback endpoint
194202
4. JWT tokens are issued for authenticated user
195203

204+
## 📋 Activity Logs
205+
206+
### Overview
207+
The Activity Logs system provides comprehensive tracking of user actions for security auditing, compliance, and debugging purposes. All user activities are automatically logged with detailed context information.
208+
209+
### Tracked Events
210+
The following events are automatically logged:
211+
- `LOGIN` — User successfully logged in
212+
- `LOGOUT` — User logged out
213+
- `REGISTER` — New user registration
214+
- `PASSWORD_CHANGE` — User changed their password
215+
- `PASSWORD_RESET` — User reset their password
216+
- `EMAIL_VERIFY` — User verified their email address
217+
- `2FA_ENABLE` — User enabled two-factor authentication
218+
- `2FA_DISABLE` — User disabled two-factor authentication
219+
- `2FA_LOGIN` — User logged in using 2FA
220+
- `TOKEN_REFRESH` — User refreshed their access token
221+
- `SOCIAL_LOGIN` — User logged in via social media (Google, Facebook, GitHub)
222+
- `PROFILE_ACCESS` — User accessed their profile
223+
- `RECOVERY_CODE_USED` — User used a 2FA recovery code
224+
- `RECOVERY_CODE_GEN` — User generated new 2FA recovery codes
225+
226+
### Features
227+
- **Pagination**: Efficient handling of large datasets with configurable page sizes (1-100 items)
228+
- **Filtering**: Filter by event type, date ranges (YYYY-MM-DD format)
229+
- **Security**: Users can only access their own logs; admin endpoint for comprehensive access
230+
- **Performance**: Optimized database queries with proper indexing on UserID, EventType, and Timestamp
231+
- **Audit Trail**: IP addresses, user agents, and contextual details captured for forensic analysis
232+
233+
### API Examples
234+
235+
#### Get User's Recent Login Activities
236+
```bash
237+
curl -X GET "http://localhost:8080/activity-logs?event_type=LOGIN&limit=5" \
238+
-H "Authorization: Bearer your-jwt-token"
239+
```
240+
241+
#### Get Activities from Date Range
242+
```bash
243+
curl -X GET "http://localhost:8080/activity-logs?start_date=2024-01-01&end_date=2024-01-31&page=1&limit=20" \
244+
-H "Authorization: Bearer your-jwt-token"
245+
```
246+
247+
#### Get Available Event Types
248+
```bash
249+
curl -X GET "http://localhost:8080/activity-logs/event-types" \
250+
-H "Authorization: Bearer your-jwt-token"
251+
```
252+
253+
### Response Format
254+
```json
255+
{
256+
"data": [
257+
{
258+
"id": "123e4567-e89b-12d3-a456-426614174000",
259+
"user_id": "987fcdeb-51a2-43d8-a456-426614174001",
260+
"event_type": "LOGIN",
261+
"timestamp": "2024-01-15T10:30:00Z",
262+
"ip_address": "192.168.1.100",
263+
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
264+
"details": {
265+
"login_method": "password",
266+
"success": true
267+
}
268+
}
269+
],
270+
"pagination": {
271+
"page": 1,
272+
"limit": 20,
273+
"total_records": 45,
274+
"total_pages": 3,
275+
"has_next": true,
276+
"has_previous": false
277+
}
278+
}
279+
```
280+
196281
## 🧪 Testing
197282

198283
### Automated Testing

cmd/api/main.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
_ "github.com/gjovanovicst/auth_api/docs" // docs is generated by Swag CLI
1212
"github.com/gjovanovicst/auth_api/internal/database"
1313
"github.com/gjovanovicst/auth_api/internal/email"
14+
logService "github.com/gjovanovicst/auth_api/internal/log"
1415
"github.com/gjovanovicst/auth_api/internal/middleware"
1516
"github.com/gjovanovicst/auth_api/internal/redis"
1617
"github.com/gjovanovicst/auth_api/internal/social"
@@ -61,16 +62,22 @@ func main() {
6162
// Run database migrations
6263
database.MigrateDatabase()
6364

65+
// Initialize Activity Log Service
66+
logService.InitializeLogService()
67+
6468
// Initialize Services and Handlers
6569
userRepo := user.NewRepository(database.DB)
6670
socialRepo := social.NewRepository(database.DB)
71+
logRepo := logService.NewRepository(database.DB)
6772
emailService := email.NewService()
6873
userService := user.NewService(userRepo, emailService)
6974
socialService := social.NewService(userRepo, socialRepo)
7075
twofaService := twofa.NewService(userRepo)
76+
logQueryService := logService.NewQueryService(logRepo)
7177
userHandler := user.NewHandler(userService)
7278
socialHandler := social.NewHandler(socialService)
7379
twofaHandler := twofa.NewHandler(twofaService)
80+
logHandler := logService.NewHandler(logQueryService)
7481

7582
// Setup Gin Router
7683
r := gin.Default()
@@ -117,6 +124,19 @@ func main() {
117124
protected.POST("/2fa/enable", twofaHandler.Enable2FA)
118125
protected.POST("/2fa/disable", twofaHandler.Disable2FA)
119126
protected.POST("/2fa/recovery-codes", twofaHandler.GenerateRecoveryCodes)
127+
128+
// Activity log routes
129+
protected.GET("/activity-logs", logHandler.GetUserActivityLogs)
130+
protected.GET("/activity-logs/event-types", logHandler.GetEventTypes)
131+
protected.GET("/activity-logs/:id", logHandler.GetActivityLogByID)
132+
}
133+
134+
// Admin routes (for future role-based access control)
135+
admin := r.Group("/admin")
136+
admin.Use(middleware.AuthMiddleware())
137+
// TODO: Add admin role check middleware
138+
{
139+
admin.GET("/activity-logs", logHandler.GetAllActivityLogs)
120140
}
121141

122142
// Add Swagger UI endpoint

0 commit comments

Comments
 (0)