tableSecurityLogs.go (1798B)
1 package database 2 3 import ( 4 "github.com/sirupsen/logrus" 5 "time" 6 ) 7 8 type SecurityLog struct { 9 ID int64 10 Message string 11 UserID UserID 12 Typ int64 13 CreatedAt time.Time 14 User User 15 } 16 17 const ( 18 LoginSecurityLog = iota + 1 19 LogoutSecurityLog 20 ChangePasswordSecurityLog 21 TotpEnabledSecurityLog 22 TotpDisabledSecurityLog 23 Gpg2faEnabledSecurityLog 24 Gpg2faDisabledSecurityLog 25 UsernameChangedSecurityLog 26 ChangeDuressPasswordSecurityLog 27 ChangeSecretPhraseSecurityLog 28 PasswordRecoverySecurityLog 29 ) 30 31 func getMessageForType(typ int64) string { 32 switch typ { 33 case LoginSecurityLog: 34 return "Successful login" 35 case LogoutSecurityLog: 36 return "Logout" 37 case ChangePasswordSecurityLog: 38 return "Password changed" 39 case ChangeDuressPasswordSecurityLog: 40 return "Duress password changed" 41 case TotpEnabledSecurityLog: 42 return "TOTP enabled" 43 case TotpDisabledSecurityLog: 44 return "TOTP disabled" 45 case Gpg2faEnabledSecurityLog: 46 return "GPG 2FA enabled" 47 case Gpg2faDisabledSecurityLog: 48 return "GPG 2FA disabled" 49 case UsernameChangedSecurityLog: 50 return "Username changed" 51 case ChangeSecretPhraseSecurityLog: 52 return "Secret phrase changed" 53 case PasswordRecoverySecurityLog: 54 return "Password recovery" 55 } 56 return "" 57 } 58 59 func (d *DkfDB) CreateSecurityLog(userID UserID, typ int64) { 60 log := SecurityLog{ 61 Message: getMessageForType(typ), 62 UserID: userID, 63 Typ: typ, 64 } 65 if err := d.db.Create(&log).Error; err != nil { 66 logrus.Error(err) 67 } 68 } 69 70 func (d *DkfDB) GetSecurityLogs(userID UserID) (out []SecurityLog, err error) { 71 err = d.db.Order("id DESC").Find(&out, "user_id = ?", userID).Error 72 return 73 } 74 75 func (d *DkfDB) DeleteOldSecurityLogs() { 76 if err := d.db.Delete(SecurityLog{}, "created_at < date('now', '-7 Day')").Error; err != nil { 77 logrus.Error(err) 78 } 79 }