1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
| // 安全审计日志
class SecurityAuditLogger {
private auditLog: any
constructor(auditLog: any) {
this.auditLog = auditLog
}
logAuthenticationAttempt(userId: string, success: boolean, ip: string) {
this.auditLog.create({
eventType: 'AUTH_ATTEMPT',
userId,
success,
ip,
timestamp: new Date(),
userAgent: undefined
})
}
logAuthorizationAttempt(userId: string, resource: string, action: string, success: boolean) {
this.auditLog.create({
eventType: 'AUTHZ_ATTEMPT',
userId,
resource,
action,
success,
timestamp: new Date()
})
}
logDataAccess(userId: string, resourceType: string, resourceId: string) {
this.auditLog.create({
eventType: 'DATA_ACCESS',
userId,
resourceType,
resourceId,
timestamp: new Date()
})
}
logSecurityEvent(eventType: string, details: any) {
this.auditLog.create({
eventType,
details,
timestamp: new Date()
})
}
}
// 使用示例
const securityLogger = new SecurityAuditLogger(auditLog)
app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body
const ip = req.ip
try {
const result = await authService.login(email, password)
securityLogger.logAuthenticationAttempt(result.user.id, true, ip)
res.json(result)
} catch (error) {
securityLogger.logAuthenticationAttempt(email, false, ip)
res.status(401).json({ error: 'Invalid credentials' })
}
})
|