commit 79e225c8048e767f5214e7bf154a20d95a771d78 parent d8b3731f19c6246a5062b6a820585e2620c52592 Author: n0tr1v <n0tr1v@protonmail.com> Date: Fri, 2 Dec 2022 17:41:43 -0500 strongly typed UserID Diffstat:
42 files changed, 186 insertions(+), 183 deletions(-)
diff --git a/pkg/database/tableAuditLog.go b/pkg/database/tableAuditLog.go @@ -8,7 +8,7 @@ import ( type AuditLog struct { ID int64 - UserID int64 + UserID UserID Log string CreatedAt time.Time User User diff --git a/pkg/database/tableBadges.go b/pkg/database/tableBadges.go @@ -9,14 +9,14 @@ type Badge struct { } type UserBadge struct { - UserID int64 + UserID UserID BadgeID int64 CreatedAt time.Time User User Badge Badge } -func CreateUserBadge(userID, badgeID int64) error { +func CreateUserBadge(userID UserID, badgeID int64) error { ub := UserBadge{UserID: userID, BadgeID: badgeID} return DB.Create(&ub).Error } diff --git a/pkg/database/tableCaptchaRequests.go b/pkg/database/tableCaptchaRequests.go @@ -8,7 +8,7 @@ import ( type CaptchaRequest struct { ID int64 - UserID int64 + UserID UserID CaptchaImg string Answer string CreatedAt time.Time diff --git a/pkg/database/tableChatInbox.go b/pkg/database/tableChatInbox.go @@ -10,8 +10,8 @@ type ChatInboxMessage struct { ID int64 Message string RoomID int64 - UserID int64 - ToUserID int64 + UserID UserID + ToUserID UserID ChatMessageID *int64 IsRead bool IsPm bool @@ -22,7 +22,7 @@ type ChatInboxMessage struct { Room ChatRoom } -func GetUserChatInboxMessages(userID int64) (msgs []ChatInboxMessage, err error) { +func GetUserChatInboxMessages(userID UserID) (msgs []ChatInboxMessage, err error) { err = DB.Order("id DESC"). Limit(50). Preload("User"). @@ -39,7 +39,7 @@ func GetUserChatInboxMessages(userID int64) (msgs []ChatInboxMessage, err error) return } -func GetUserChatInboxMessagesSent(userID int64) (msgs []ChatInboxMessage, err error) { +func GetUserChatInboxMessagesSent(userID UserID) (msgs []ChatInboxMessage, err error) { err = DB.Order("id DESC"). Limit(50). Preload("User"). @@ -57,22 +57,22 @@ func DeleteChatInboxMessageByChatMessageID(chatMessageID int64) error { return DB.Where("chat_message_id = ?", chatMessageID).Delete(&ChatInboxMessage{}).Error } -func DeleteAllChatInbox(userID int64) error { +func DeleteAllChatInbox(userID UserID) error { return DB.Where("to_user_id = ?", userID).Delete(&ChatInboxMessage{}).Error } -func DeleteUserChatInboxMessages(userID int64) error { +func DeleteUserChatInboxMessages(userID UserID) error { return DB.Where("user_id = ?", userID).Delete(&ChatInboxMessage{}).Error } -func CreateInboxMessage(msg string, roomID, fromUserID, toUserID int64, isPm, moderators bool, msgID *int64) { +func CreateInboxMessage(msg string, roomID int64, fromUserID, toUserID UserID, isPm, moderators bool, msgID *int64) { inbox := ChatInboxMessage{Message: msg, RoomID: roomID, UserID: fromUserID, ToUserID: toUserID, IsPm: isPm, Moderators: moderators, ChatMessageID: msgID} if err := DB.Create(&inbox).Error; err != nil { logrus.Error(err) } } -func GetUserInboxMessagesCount(userID int64) (count int64) { +func GetUserInboxMessagesCount(userID UserID) (count int64) { DB.Table("chat_inbox_messages").Where("to_user_id = ? AND is_read = ?", userID, false).Count(&count) return } diff --git a/pkg/database/tableChatMessages.go b/pkg/database/tableChatMessages.go @@ -62,8 +62,8 @@ type ChatMessage struct { Message string RawMessage string RoomID int64 - UserID int64 - ToUserID *int64 + UserID UserID + ToUserID *UserID GroupID *int64 UploadID *int64 CreatedAt time.Time @@ -209,7 +209,7 @@ func (m *ChatMessage) DoSave() { } } -func GetUserLastChatMessageInRoom(userID, roomID int64) (out ChatMessage, err error) { +func GetUserLastChatMessageInRoom(userID UserID, roomID int64) (out ChatMessage, err error) { err = DB. Where("user_id = ? AND room_id = ?", userID, roomID). Order("id DESC"). @@ -243,7 +243,7 @@ func GetRoomChatMessageByUUID(roomID int64, msgUUID string) (out ChatMessage, er return } -func GetRoomChatMessageByDate(roomID, userID int64, dt time.Time) (out ChatMessage, err error) { +func GetRoomChatMessageByDate(roomID int64, userID UserID, dt time.Time) (out ChatMessage, err error) { err = DB. Select("*, strftime('%Y-%m-%d %H:%M:%S', created_at) as created_at1"). Where("room_id = ? AND user_id = ? AND created_at1 = ?", roomID, userID, dt.Format("2006-01-02 15:04:05")). @@ -266,7 +266,7 @@ func GetRoomChatMessagesByDate(roomID int64, dt time.Time) (out []ChatMessage, e return } -func GetChatMessages(roomID int64, username string, userID, displayPms int64, mentionsOnly, DisplayHellbanned, displayIgnored, displayModerators bool) (out ChatMessages, err error) { +func GetChatMessages(roomID int64, username string, userID UserID, displayPms int64, mentionsOnly, DisplayHellbanned, displayIgnored, displayModerators bool) (out ChatMessages, err error) { q := DB. Preload("User"). Preload("ToUser"). @@ -373,7 +373,7 @@ func DeleteChatMessageByUUID(messageUUID string) error { return DB.Where("uuid = ?", messageUUID).Delete(&ChatMessage{}).Error } -func DeleteUserChatMessages(userID int64) error { +func DeleteUserChatMessages(userID UserID) error { return DB.Where("user_id = ?", userID).Delete(&ChatMessage{}).Error } @@ -408,7 +408,7 @@ AND room_id = ? } } -func makeMsg(raw, txt string, roomID, userID int64) ChatMessage { +func makeMsg(raw, txt string, roomID int64, userID UserID) ChatMessage { msg := ChatMessage{ UUID: uuid.New().String(), Message: txt, @@ -419,7 +419,7 @@ func makeMsg(raw, txt string, roomID, userID int64) ChatMessage { return msg } -func CreateMsg(raw, txt, roomKey string, roomID, userID int64, toUserID *int64) (out ChatMessage, err error) { +func CreateMsg(raw, txt, roomKey string, roomID int64, userID UserID, toUserID *UserID) (out ChatMessage, err error) { if roomKey != "" { var err error txt, raw, err = encryptMessages(txt, raw, roomKey) @@ -436,7 +436,7 @@ func CreateMsg(raw, txt, roomKey string, roomID, userID int64, toUserID *int64) return } -func CreateSysMsg(raw, txt, roomKey string, roomID, userID int64) error { +func CreateSysMsg(raw, txt, roomKey string, roomID int64, userID UserID) error { if roomKey != "" { var err error txt, raw, err = encryptMessages(txt, raw, roomKey) @@ -452,8 +452,9 @@ func CreateSysMsg(raw, txt, roomKey string, roomID, userID int64) error { func CreateOrEditMessage( editMsg *ChatMessage, message, raw, roomKey string, - roomID, fromUserID int64, - toUserID *int64, + roomID int64, + fromUserID UserID, + toUserID *UserID, upload *Upload, groupID *int64, hellbanMsg, modMsg bool) (int64, error) { diff --git a/pkg/database/tableChatReactions.go b/pkg/database/tableChatReactions.go @@ -6,13 +6,13 @@ import ( type ChatReaction struct { ID int64 - UserID int64 + UserID UserID MessageID int64 Reaction int64 CreatedAt time.Time } -func CreateChatReaction(userID, messageID, reaction int64) error { +func CreateChatReaction(userID UserID, messageID, reaction int64) error { out := ChatReaction{ UserID: userID, MessageID: messageID, @@ -21,6 +21,6 @@ func CreateChatReaction(userID, messageID, reaction int64) error { return DB.Create(&out).Error } -func DeleteReaction(userID, messageID, reaction int64) error { +func DeleteReaction(userID UserID, messageID, reaction int64) error { return DB.Delete(ChatReaction{}, "user_id = ? AND message_id = ? AND reaction = ?", userID, messageID, reaction).Error } diff --git a/pkg/database/tableChatReadMarkers.go b/pkg/database/tableChatReadMarkers.go @@ -5,17 +5,17 @@ import ( ) type ChatReadMarker struct { - UserID int64 + UserID UserID RoomID int64 ReadAt time.Time } -func GetUserReadMarker(userID, roomID int64) (out ChatReadMarker, err error) { +func GetUserReadMarker(userID UserID, roomID int64) (out ChatReadMarker, err error) { err = DB.First(&out, "user_id = ? AND room_id = ?", userID, roomID).Error return } -func UpdateChatReadMarker(userID, roomID int64) { +func UpdateChatReadMarker(userID UserID, roomID int64) { now := time.Now() res := DB.Table("chat_read_markers").Where("user_id = ? AND room_id = ?", userID, roomID).Update("read_at", now) if res.RowsAffected == 0 { diff --git a/pkg/database/tableChatRoomGroups.go b/pkg/database/tableChatRoomGroups.go @@ -23,7 +23,7 @@ func (g *ChatRoomGroup) DoSave() { type ChatRoomUserGroup struct { GroupID int64 RoomID int64 - UserID int64 + UserID UserID User User } @@ -37,7 +37,7 @@ func GetRoomGroupByName(roomID int64, groupName string) (out ChatRoomGroup, err return } -func IsUserInGroupByID(userID, groupID int64) bool { +func IsUserInGroupByID(userID UserID, groupID int64) bool { var count int64 DB.Model(ChatRoomUserGroup{}).Where("group_id = ? AND user_id = ?", groupID, userID).Count(&count) return count == 1 @@ -59,13 +59,13 @@ func CreateChatRoomGroup(roomID int64, name, color string) (out ChatRoomGroup, e return } -func AddUserToRoomGroup(roomID, groupID, userID int64) (out ChatRoomUserGroup, err error) { +func AddUserToRoomGroup(roomID, groupID int64, userID UserID) (out ChatRoomUserGroup, err error) { out = ChatRoomUserGroup{GroupID: groupID, RoomID: roomID, UserID: userID} err = DB.Create(&out).Error return } -func RmUserFromRoomGroup(roomID, groupID, userID int64) (err error) { +func RmUserFromRoomGroup(roomID, groupID int64, userID UserID) (err error) { err = DB.Delete(&ChatRoomUserGroup{}, "user_id = ? AND group_id = ? AND room_id = ?", userID, groupID, roomID).Error return } diff --git a/pkg/database/tableChatRoomWhitelistedUsers.go b/pkg/database/tableChatRoomWhitelistedUsers.go @@ -7,7 +7,7 @@ import ( ) type ChatRoomWhitelistedUser struct { - UserID int64 + UserID UserID RoomID int64 CreatedAt time.Time User User @@ -19,7 +19,7 @@ func (r *ChatRoomWhitelistedUser) DoSave() { } } -func IsUserWhitelistedInRoom(userID, roomID int64) bool { +func IsUserWhitelistedInRoom(userID UserID, roomID int64) bool { var count int64 DB.Table("chat_room_whitelisted_users").Where("user_id = ? and room_id = ?", userID, roomID).Count(&count) return count == 1 @@ -30,13 +30,13 @@ func GetWhitelistedUsers(roomID int64) (out []ChatRoomWhitelistedUser, err error return } -func WhitelistUser(roomID, userID int64) (out ChatRoomWhitelistedUser, err error) { +func WhitelistUser(roomID int64, userID UserID) (out ChatRoomWhitelistedUser, err error) { out = ChatRoomWhitelistedUser{UserID: userID, RoomID: roomID} err = DB.Create(&out).Error return } -func DeWhitelistUser(roomID, userID int64) (err error) { +func DeWhitelistUser(roomID int64, userID UserID) (err error) { err = DB.Delete(ChatRoomWhitelistedUser{}, "user_id = ? and room_id = ?", userID, roomID).Error return } diff --git a/pkg/database/tableChatRooms.go b/pkg/database/tableChatRooms.go @@ -11,7 +11,7 @@ import ( type ChatRoom struct { ID int64 Name string - OwnerUserID *int64 + OwnerUserID *UserID Password string // Hashed password (sha512) IsListed bool IsEphemeral bool @@ -26,7 +26,7 @@ const ( UserWhitelistRoomMode = 1 ) -func CreateRoom(name string, passwordHash string, ownerID int64, isListed bool) (out ChatRoom, err error) { +func CreateRoom(name string, passwordHash string, ownerID UserID, isListed bool) (out ChatRoom, err error) { out = ChatRoom{ Name: name, Password: passwordHash, @@ -109,7 +109,7 @@ type ChatRoomAug struct { IsUnread bool } -func GetOfficialChatRooms1(userID int64) (out []ChatRoomAug, err error) { +func GetOfficialChatRooms1(userID UserID) (out []ChatRoomAug, err error) { err = DB.Raw(`SELECT r.*, COALESCE((rr.read_at < m.created_at), 1) as is_unread FROM chat_rooms r @@ -127,7 +127,7 @@ func GetOfficialChatRooms() (out []ChatRoom, err error) { return } -func GetListedChatRooms(userID int64) (out []ChatRoomAug, err error) { +func GetListedChatRooms(userID UserID) (out []ChatRoomAug, err error) { err = DB.Raw(`SELECT r.*, u.*, COALESCE((rr.read_at < m.created_at), 1) as is_unread @@ -153,7 +153,7 @@ WHERE owner_user_id IS NOT NULL } type ChatReadRecord struct { - UserID int64 + UserID UserID RoomID int64 ReadAt time.Time } diff --git a/pkg/database/tableDownloads.go b/pkg/database/tableDownloads.go @@ -7,21 +7,21 @@ import ( // Download table that keep tracks of downloaded files by the users. type Download struct { ID int64 - UserID int64 + UserID UserID User User Filename string CreatedAt time.Time } // CreateDownload ... -func CreateDownload(userID int64, filename string) (out Download, err error) { +func CreateDownload(userID UserID, filename string) (out Download, err error) { out = Download{UserID: userID, Filename: filename} err = DB.Create(&out).Error return } // UserNbDownloaded returns how many times a user downloaded a file -func UserNbDownloaded(userID int64, filename string) (out int64) { +func UserNbDownloaded(userID UserID, filename string) (out int64) { DB.Table("downloads").Where("user_id = ? AND filename = ?", userID, filename).Count(&out) return } diff --git a/pkg/database/tableGists.go b/pkg/database/tableGists.go @@ -11,7 +11,7 @@ import ( type Gist struct { ID int64 UUID string - UserID int64 + UserID UserID User User Name string Content string diff --git a/pkg/database/tableIgnoredUsers.go b/pkg/database/tableIgnoredUsers.go @@ -7,32 +7,32 @@ import ( ) type IgnoredUser struct { - UserID int64 - IgnoredUserID int64 + UserID UserID + IgnoredUserID UserID CreatedAt time.Time User User IgnoredUser User } -func GetIgnoredUsers(userID int64) (out []IgnoredUser, err error) { +func GetIgnoredUsers(userID UserID) (out []IgnoredUser, err error) { err = DB.Where("user_id = ?", userID).Preload("IgnoredUser").Find(&out).Error return } // GetIgnoredByUsers get a list of people who ignore userID -func GetIgnoredByUsers(userID int64) (out []IgnoredUser, err error) { +func GetIgnoredByUsers(userID UserID) (out []IgnoredUser, err error) { err = DB.Where("ignored_user_id = ?", userID).Find(&out).Error return } -func IgnoreUser(userID, ignoredUserID int64) { +func IgnoreUser(userID, ignoredUserID UserID) { ignore := IgnoredUser{UserID: userID, IgnoredUserID: ignoredUserID} if err := DB.Create(&ignore).Error; err != nil { logrus.Error(err) } } -func UnIgnoreUser(userID, ignoredUserID int64) { +func UnIgnoreUser(userID, ignoredUserID UserID) { if err := DB.Delete(IgnoredUser{}, "user_id = ? AND ignored_user_id = ?", userID, ignoredUserID).Error; err != nil { logrus.Error(err) } diff --git a/pkg/database/tableInvitations.go b/pkg/database/tableInvitations.go @@ -9,8 +9,8 @@ import ( type Invitation struct { ID int64 Token string - OwnerUserID int64 - InviteeUserID int64 + OwnerUserID UserID + InviteeUserID UserID CreatedAt time.Time UpdatedAt time.Time } @@ -27,7 +27,7 @@ func (i *Invitation) DoSave() { } } -func CreateInvitation(userID int64) (out Invitation, err error) { +func CreateInvitation(userID UserID) (out Invitation, err error) { out = Invitation{ Token: utils.GenerateToken32(), OwnerUserID: userID, @@ -42,12 +42,12 @@ func GetUnusedInvitationByToken(token string) (out Invitation, err error) { return } -func GetUserInvitations(userID int64) (out []Invitation, err error) { +func GetUserInvitations(userID UserID) (out []Invitation, err error) { err = DB.Find(&out, "owner_user_id = ?", userID).Error return } -func GetUserUnusedInvitations(userID int64) (out []Invitation, err error) { +func GetUserUnusedInvitations(userID UserID) (out []Invitation, err error) { err = DB.Find(&out, "owner_user_id = ? AND invitee_user_id == 1", userID).Error return } diff --git a/pkg/database/tableKarmaHistory.go b/pkg/database/tableKarmaHistory.go @@ -6,12 +6,12 @@ type KarmaHistory struct { ID int64 Karma int64 Description string - UserID int64 + UserID UserID FromUserID *int64 CreatedAt time.Time } -func CreateKarmaHistory(karma int64, description string, userID int64, fromUserID *int64) (out KarmaHistory, err error) { +func CreateKarmaHistory(karma int64, description string, userID UserID, fromUserID *int64) (out KarmaHistory, err error) { out = KarmaHistory{ Karma: karma, Description: description, diff --git a/pkg/database/tableNotifications.go b/pkg/database/tableNotifications.go @@ -9,7 +9,7 @@ import ( type Notification struct { ID int64 Message string - UserID int64 + UserID UserID IsRead bool ReadAt *time.Time CreatedAt time.Time @@ -26,7 +26,7 @@ type SessionNotification struct { User User } -func GetUserNotifications(userID int64) (msgs []Notification, err error) { +func GetUserNotifications(userID UserID) (msgs []Notification, err error) { err = DB.Order("id DESC"). Limit(50). Preload("User"). @@ -69,18 +69,18 @@ func DeleteSessionNotificationByID(sessionNotificationID int64) error { return DB.Where("id = ?", sessionNotificationID).Delete(&SessionNotification{}).Error } -func DeleteAllNotifications(userID int64) error { +func DeleteAllNotifications(userID UserID) error { return DB.Where("user_id = ?", userID).Delete(&Notification{}).Error } -func CreateNotification(msg string, userID int64) { +func CreateNotification(msg string, userID UserID) { inbox := Notification{Message: msg, UserID: userID, IsRead: false} if err := DB.Create(&inbox).Error; err != nil { logrus.Error(err) } } -func GetUserNotificationsCount(userID int64) (count int64) { +func GetUserNotificationsCount(userID UserID) (count int64) { DB.Table("notifications").Where("user_id = ? AND is_read = ?", userID, false).Count(&count) return } diff --git a/pkg/database/tablePmBlacklistedUsers.go b/pkg/database/tablePmBlacklistedUsers.go @@ -5,32 +5,32 @@ import ( ) type PmBlacklistedUsers struct { - UserID int64 - BlacklistedUserID int64 + UserID UserID + BlacklistedUserID UserID BlacklistedUser User } // IsUserPmBlacklisted returns either or not toUserID blacklisted fromUserID -func IsUserPmBlacklisted(fromUserID, toUserID int64) bool { +func IsUserPmBlacklisted(fromUserID, toUserID UserID) bool { var count int64 DB.Model(&PmBlacklistedUsers{}).Where("blacklisted_user_id = ? AND user_id = ?", fromUserID, toUserID).Count(&count) return count == 1 } // GetPmBlacklistedUsers returns a list of userID blacklisted users -func GetPmBlacklistedUsers(userID int64) (out []PmBlacklistedUsers, err error) { +func GetPmBlacklistedUsers(userID UserID) (out []PmBlacklistedUsers, err error) { err = DB.Where("user_id = ?", userID).Preload("BlacklistedUser").Find(&out).Error return } // GetPmBlacklistedByUsers returns a list of users that are blacklisting userID -func GetPmBlacklistedByUsers(userID int64) (out []PmBlacklistedUsers, err error) { +func GetPmBlacklistedByUsers(userID UserID) (out []PmBlacklistedUsers, err error) { err = DB.Where("blacklisted_user_id = ?", userID).Find(&out).Error return } // ToggleBlacklistedUser returns true if the user was added to the blacklist -func ToggleBlacklistedUser(userID, blacklistedUserID int64) bool { +func ToggleBlacklistedUser(userID, blacklistedUserID UserID) bool { if IsUserPmBlacklisted(blacklistedUserID, userID) { RmBlacklistedUser(userID, blacklistedUserID) return false @@ -39,14 +39,14 @@ func ToggleBlacklistedUser(userID, blacklistedUserID int64) bool { return true } -func AddBlacklistedUser(userID, blacklistedUserID int64) { +func AddBlacklistedUser(userID, blacklistedUserID UserID) { ignore := PmBlacklistedUsers{UserID: userID, BlacklistedUserID: blacklistedUserID} if err := DB.Create(&ignore).Error; err != nil { logrus.Error(err) } } -func RmBlacklistedUser(userID, blacklistedUserID int64) { +func RmBlacklistedUser(userID, blacklistedUserID UserID) { if err := DB.Delete(PmBlacklistedUsers{}, "user_id = ? AND blacklisted_user_id = ?", userID, blacklistedUserID).Error; err != nil { logrus.Error(err) } diff --git a/pkg/database/tablePmWhitelistedUsers.go b/pkg/database/tablePmWhitelistedUsers.go @@ -5,24 +5,24 @@ import ( ) type PmWhitelistedUsers struct { - UserID int64 - WhitelistedUserID int64 + UserID UserID + WhitelistedUserID UserID WhitelistedUser User } -func IsUserPmWhitelisted(fromUserID, toUserID int64) bool { +func IsUserPmWhitelisted(fromUserID, toUserID UserID) bool { var count int64 DB.Model(&PmWhitelistedUsers{}).Where("whitelisted_user_id = ? AND user_id = ?", fromUserID, toUserID).Count(&count) return count == 1 } -func GetPmWhitelistedUsers(userID int64) (out []PmWhitelistedUsers, err error) { +func GetPmWhitelistedUsers(userID UserID) (out []PmWhitelistedUsers, err error) { err = DB.Where("user_id = ?", userID).Preload("WhitelistedUser").Find(&out).Error return } // ToggleWhitelistedUser returns true if the user was added to the whitelist -func ToggleWhitelistedUser(userID, whitelistedUserID int64) bool { +func ToggleWhitelistedUser(userID, whitelistedUserID UserID) bool { if IsUserPmWhitelisted(whitelistedUserID, userID) { RmWhitelistedUser(userID, whitelistedUserID) return false @@ -31,14 +31,14 @@ func ToggleWhitelistedUser(userID, whitelistedUserID int64) bool { return true } -func AddWhitelistedUser(userID, whitelistedUserID int64) { +func AddWhitelistedUser(userID, whitelistedUserID UserID) { ignore := PmWhitelistedUsers{UserID: userID, WhitelistedUserID: whitelistedUserID} if err := DB.Create(&ignore).Error; err != nil { logrus.Error(err) } } -func RmWhitelistedUser(userID, whitelistedUserID int64) { +func RmWhitelistedUser(userID, whitelistedUserID UserID) { if err := DB.Delete(PmWhitelistedUsers{}, "user_id = ? AND whitelisted_user_id = ?", userID, whitelistedUserID).Error; err != nil { logrus.Error(err) } diff --git a/pkg/database/tableSecurityLogs.go b/pkg/database/tableSecurityLogs.go @@ -8,7 +8,7 @@ import ( type SecurityLog struct { ID int64 Message string - UserID int64 + UserID UserID Typ int64 CreatedAt time.Time User User @@ -53,7 +53,7 @@ func getMessageForType(typ int64) string { return "" } -func CreateSecurityLog(userID, typ int64) { +func CreateSecurityLog(userID UserID, typ int64) { log := SecurityLog{ Message: getMessageForType(typ), UserID: userID, @@ -64,7 +64,7 @@ func CreateSecurityLog(userID, typ int64) { } } -func GetSecurityLogs(userID int64) (out []SecurityLog, err error) { +func GetSecurityLogs(userID UserID) (out []SecurityLog, err error) { err = DB.Order("id DESC").Find(&out, "user_id = ?", userID).Error return } diff --git a/pkg/database/tableSessions.go b/pkg/database/tableSessions.go @@ -13,20 +13,20 @@ type Session struct { ExpiresAt time.Time // Time at which the session expires DeletedAt *time.Time // Time at which a session was soft deleted CreatedAt time.Time // Time at which a session was created - UserID int64 // User that owns the session + UserID UserID // User that owns the session ClientIP string // IP address used to create the session UserAgent string // Browser UserAgent that was used to create the session User User // User object for association queries } // GetActiveUserSessions gets all user sessions -func GetActiveUserSessions(userID int64) (out []Session) { +func GetActiveUserSessions(userID UserID) (out []Session) { DB.Order("created_at DESC").Find(&out, "user_id = ? AND expires_at > DATETIME('now') AND deleted_at IS NULL", userID) return } // CreateSession creates a session for a user -func CreateSession(userID int64, realIP, userAgent string) (Session, error) { +func CreateSession(userID UserID, realIP, userAgent string) (Session, error) { // Delete all sessions except the last 4 if err := DB.Exec(`DELETE FROM sessions WHERE user_id = ? AND token NOT IN (SELECT s2.token FROM sessions s2 WHERE s2.user_id = ? ORDER BY s2.created_at DESC LIMIT 4)`, userID, userID).Error; err != nil { logrus.Error(err) @@ -43,7 +43,7 @@ func CreateSession(userID int64, realIP, userAgent string) (Session, error) { } // DeleteUserSessions all sessions of the user. -func DeleteUserSessions(userID int64) error { +func DeleteUserSessions(userID UserID) error { return DB.Unscoped().Where("user_id = ?", userID).Delete(&Session{}).Error } @@ -52,11 +52,11 @@ func DeleteSessionByToken(token string) error { return DB.Unscoped().Where("token = ?", token).Delete(&Session{}).Error } -func DeleteUserSessionByToken(userID int64, token string) error { +func DeleteUserSessionByToken(userID UserID, token string) error { return DB.Unscoped().Where("user_id = ? AND token = ?", userID, token).Delete(&Session{}).Error } -func DeleteUserOtherSessions(userID int64, currentToken string) error { +func DeleteUserOtherSessions(userID UserID, currentToken string) error { return DB.Unscoped().Where("user_id = ? AND token != ?", userID, currentToken).Delete(&Session{}).Error } diff --git a/pkg/database/tableSnippets.go b/pkg/database/tableSnippets.go @@ -4,16 +4,16 @@ import "github.com/sirupsen/logrus" type Snippet struct { Name string - UserID int64 + UserID UserID Text string } -func GetUserSnippets(userID int64) (out []Snippet, err error) { +func GetUserSnippets(userID UserID) (out []Snippet, err error) { err = DB.Find(&out, "user_id = ?", userID).Error return } -func CreateSnippet(userID int64, name, text string) (out Snippet, err error) { +func CreateSnippet(userID UserID, name, text string) (out Snippet, err error) { out = Snippet{ Name: name, UserID: userID, @@ -23,7 +23,7 @@ func CreateSnippet(userID int64, name, text string) (out Snippet, err error) { return } -func DeleteSnippet(userID int64, name string) { +func DeleteSnippet(userID UserID, name string) { if err := DB.Delete(Snippet{}, "user_id = ? AND name = ?", userID, name).Error; err != nil { logrus.Error(err) } diff --git a/pkg/database/tableUploads.go b/pkg/database/tableUploads.go @@ -12,7 +12,7 @@ import ( type Upload struct { ID int64 - UserID int64 + UserID UserID FileName string OrigFileName string FileSize int64 @@ -22,11 +22,11 @@ type Upload struct { } // CreateUpload create file on disk in "uploads" folder, and save upload in database as well. -func CreateUpload(fileName string, content []byte, userID int64) (*Upload, error) { +func CreateUpload(fileName string, content []byte, userID UserID) (*Upload, error) { return CreateUploadWithSize(fileName, content, userID, int64(len(content))) } -func CreateUploadWithSize(fileName string, content []byte, userID, size int64) (*Upload, error) { +func CreateUploadWithSize(fileName string, content []byte, userID UserID, size int64) (*Upload, error) { newFileName := utils.MD5([]byte(utils.GenerateToken32())) if err := ioutil.WriteFile(filepath.Join("uploads", newFileName), content, 0644); err != nil { return nil, err @@ -58,12 +58,12 @@ func GetUploads() (out []Upload, err error) { return } -func GetUserUploads(userID int64) (out []Upload, err error) { +func GetUserUploads(userID UserID) (out []Upload, err error) { err = DB.Order("id DESC").Find(&out, "user_id = ?", userID).Error return } -func GetUserTotalUploadSize(userID int64) int64 { +func GetUserTotalUploadSize(userID UserID) int64 { var out struct{ TotalSize int64 } if err := DB.Raw(`SELECT SUM(file_size) as total_size FROM uploads WHERE user_id = ?`, userID).Scan(&out).Error; err != nil { logrus.Error(err) diff --git a/pkg/database/tableUserForumThreadSubscriptions.go b/pkg/database/tableUserForumThreadSubscriptions.go @@ -7,7 +7,7 @@ import ( ) type UserForumThreadSubscription struct { - UserID int64 + UserID UserID ThreadID int64 CreatedAt time.Time User User @@ -19,15 +19,15 @@ func (s *UserForumThreadSubscription) DoSave() { } } -func SubscribeToForumThread(userID, threadID int64) (err error) { +func SubscribeToForumThread(userID UserID, threadID int64) (err error) { return DB.Create(&UserForumThreadSubscription{UserID: userID, ThreadID: threadID}).Error } -func UnsubscribeFromForumThread(userID, threadID int64) (err error) { +func UnsubscribeFromForumThread(userID UserID, threadID int64) (err error) { return DB.Delete(&UserForumThreadSubscription{}, "user_id = ? AND thread_id = ?", userID, threadID).Error } -func IsUserSubscribedToForumThread(userID, threadID int64) bool { +func IsUserSubscribedToForumThread(userID UserID, threadID int64) bool { var count int64 DB.Model(UserForumThreadSubscription{}).Where("user_id = ? AND thread_id = ?", userID, threadID).Count(&count) return count == 1 diff --git a/pkg/database/tableUserPrivateNotes.go b/pkg/database/tableUserPrivateNotes.go @@ -8,18 +8,18 @@ import ( type UserPrivateNote struct { ID int64 - UserID int64 + UserID UserID Notes EncryptedString CreatedAt time.Time UpdatedAt time.Time } -func GetUserPrivateNotes(userID int64) (out UserPrivateNote, err error) { +func GetUserPrivateNotes(userID UserID) (out UserPrivateNote, err error) { err = DB.First(&out, "user_id = ?", userID).Error return } -func SetUserPrivateNotes(userID int64, notes string) error { +func SetUserPrivateNotes(userID UserID, notes string) error { if !govalidator.RuneLength(notes, "0", "10000") { return errors.New("notes must have 10000 characters maximum") } diff --git a/pkg/database/tableUserPublicNotes.go b/pkg/database/tableUserPublicNotes.go @@ -8,18 +8,18 @@ import ( type UserPublicNote struct { ID int64 - UserID int64 + UserID UserID Notes string CreatedAt time.Time UpdatedAt time.Time } -func GetUserPublicNotes(userID int64) (out UserPublicNote, err error) { +func GetUserPublicNotes(userID UserID) (out UserPublicNote, err error) { err = DB.First(&out, "user_id = ?", userID).Error return } -func SetUserPublicNotes(userID int64, notes string) error { +func SetUserPublicNotes(userID UserID, notes string) error { if !govalidator.RuneLength(notes, "0", "10000") { return errors.New("notes must have 10000 characters maximum") } diff --git a/pkg/database/tableUserRoomSubscriptions.go b/pkg/database/tableUserRoomSubscriptions.go @@ -7,7 +7,7 @@ import ( ) type UserRoomSubscription struct { - UserID int64 + UserID UserID RoomID int64 CreatedAt time.Time Room ChatRoom @@ -19,7 +19,7 @@ func (s *UserRoomSubscription) DoSave() { } } -func GetUserRoomSubscriptions(userID int64) (out []ChatRoomAug, err error) { +func GetUserRoomSubscriptions(userID UserID) (out []ChatRoomAug, err error) { err = DB.Raw(`SELECT r.*, COALESCE((rr.read_at < m.created_at), 1) as is_unread FROM user_room_subscriptions s @@ -33,15 +33,15 @@ ORDER BY r.id ASC`, userID, userID, userID).Scan(&out).Error return } -func SubscribeToRoom(userID, roomID int64) (err error) { +func SubscribeToRoom(userID UserID, roomID int64) (err error) { return DB.Create(&UserRoomSubscription{UserID: userID, RoomID: roomID}).Error } -func UnsubscribeFromRoom(userID, roomID int64) (err error) { +func UnsubscribeFromRoom(userID UserID, roomID int64) (err error) { return DB.Delete(&UserRoomSubscription{}, "user_id = ? AND room_id = ?", userID, roomID).Error } -func IsUserSubscribedToRoom(userID, roomID int64) bool { +func IsUserSubscribedToRoom(userID UserID, roomID int64) bool { var count int64 DB.Model(UserRoomSubscription{}).Where("user_id = ? AND room_id = ?", userID, roomID).Count(&count) return count == 1 diff --git a/pkg/database/tableUsers.go b/pkg/database/tableUsers.go @@ -13,9 +13,11 @@ import ( "github.com/sirupsen/logrus" ) +type UserID int64 + // User struct an internal representation of a user for our app type User struct { - ID int64 + ID UserID Avatar []byte Username string GPGPublicKey string @@ -109,7 +111,7 @@ const ( ) // UserPtrID given a User pointer, return the ID or nil -func UserPtrID(user *User) *int64 { +func UserPtrID(user *User) *UserID { if user != nil { return &user.ID } @@ -275,7 +277,7 @@ func GetUserByApiKey(user *User, apiKey string) error { } // GetUserByID ... -func GetUserByID(userID int64) (out User, err error) { +func GetUserByID(userID UserID) (out User, err error) { err = DB.First(&out, "id = ?", userID).Error return } diff --git a/pkg/database/tableXmrInvoices.go b/pkg/database/tableXmrInvoices.go @@ -13,7 +13,7 @@ import ( type XmrInvoice struct { ID int64 - UserID int64 + UserID UserID ProductID int64 Address string AmountRequested int64 @@ -22,7 +22,7 @@ type XmrInvoice struct { CreatedAt time.Time } -func CreateXmrInvoice(userID, productID int64) (out XmrInvoice, err error) { +func CreateXmrInvoice(userID UserID, productID int64) (out XmrInvoice, err error) { err = DB.Where("user_id = ? AND product_id = ? AND amount_received IS NULL", userID, productID).First(&out).Error if err == nil { return diff --git a/pkg/database/table_forum_threads.go b/pkg/database/table_forum_threads.go @@ -26,7 +26,7 @@ type ForumThread struct { ID int64 UUID string Name string - UserID int64 + UserID UserID CategoryID int64 CreatedAt time.Time User User @@ -53,14 +53,14 @@ type ForumMessage struct { ID int64 UUID string Message string - UserID int64 + UserID UserID ThreadID int64 CreatedAt time.Time User User } type ForumReadRecord struct { - UserID int64 + UserID UserID ThreadID int64 ReadAt time.Time } @@ -200,7 +200,7 @@ type ForumThreadAug struct { RepliesCount int64 } -func GetClubForumThreads(userID int64) (out []ForumThreadAug, err error) { +func GetClubForumThreads(userID UserID) (out []ForumThreadAug, err error) { err = DB.Raw(`SELECT t.*, u.username as author, u.chat_color as author_chat_color, @@ -219,7 +219,7 @@ ORDER BY t.id DESC`, userID).Scan(&out).Error return } -func GetPublicForumCategoryThreads(userID, categoryID int64) (out []ForumThreadAug, err error) { +func GetPublicForumCategoryThreads(userID UserID, categoryID int64) (out []ForumThreadAug, err error) { err = DB.Raw(`SELECT t.*, u.username as author, u.chat_color as author_chat_color, diff --git a/pkg/global/global.go b/pkg/global/global.go @@ -6,13 +6,13 @@ import ( "time" ) -var notifCountCache = cache.NewWithKey[int64, int64](30*time.Second, time.Minute) +var notifCountCache = cache.NewWithKey[database.UserID, int64](30*time.Second, time.Minute) -func DeleteUserNotificationCount(userID int64) { +func DeleteUserNotificationCount(userID database.UserID) { notifCountCache.Delete(userID) } -func GetUserNotificationCount(userID int64, sessionToken string) int64 { +func GetUserNotificationCount(userID database.UserID, sessionToken string) int64 { count, found := notifCountCache.Get(userID) if found { return count diff --git a/pkg/managers/managers.go b/pkg/managers/managers.go @@ -19,7 +19,7 @@ func init() { } type UserInfo struct { - UserID int64 + UserID database.UserID Username string Color string RefreshRate int64 @@ -187,7 +187,7 @@ func (m *ActiveUsersManager) GetRoomUsers(room database.ChatRoom, ignoredSet *ha } // RemoveUser from active users -func (m *ActiveUsersManager) RemoveUser(userID int64) { +func (m *ActiveUsersManager) RemoveUser(userID database.UserID) { m.Lock() defer m.Unlock() for _, usersMap := range m.activeUsers { @@ -199,7 +199,7 @@ func (m *ActiveUsersManager) RemoveUser(userID int64) { } } -func (m *ActiveUsersManager) IsUserActiveInRoom(userID int64, room database.ChatRoom) (found bool) { +func (m *ActiveUsersManager) IsUserActiveInRoom(userID database.UserID, room database.ChatRoom) (found bool) { m.RLock() defer m.RUnlock() usersMap, found := m.activeUsers[getRoomKey(room)] diff --git a/pkg/template/templates.go b/pkg/template/templates.go @@ -109,7 +109,7 @@ func GetBaseSSETopics(c echo.Context) []string { sseTopics = append(sseTopics, test...) } sseTopics = append(sseTopics, "global_notifications") - sseTopics = append(sseTopics, "user_"+utils.FormatInt64(authUser.ID)) + sseTopics = append(sseTopics, "user_"+utils.FormatInt64(int64(authUser.ID))) return sseTopics } diff --git a/pkg/web/handlers/admin.go b/pkg/web/handlers/admin.go @@ -540,7 +540,7 @@ func AdminUserSecurityLogsHandler(c echo.Context) error { } var data settingsSecurityData data.ActiveTab = "security" - data.Logs, _ = database.GetSecurityLogs(userID) + data.Logs, _ = database.GetSecurityLogs(database.UserID(userID)) return c.Render(http.StatusOK, "admin.user-security-logs", data) } diff --git a/pkg/web/handlers/api/v1/battleship.go b/pkg/web/handlers/api/v1/battleship.go @@ -38,7 +38,7 @@ type BSCoordinate struct { } type BSPlayer struct { - id int64 + id database.UserID username string userStyle string card *BSCard @@ -207,7 +207,7 @@ func newGame(player1, player2 database.User) *BSGame { return g } -func (g BSGame) IsPlayerTurn(playerID int64) bool { +func (g BSGame) IsPlayerTurn(playerID database.UserID) bool { return g.turn == 0 && g.player1.id == playerID || g.turn == 1 && g.player2.id == playerID } @@ -238,7 +238,7 @@ func (g *BSGame) Shot(pos string) (shipStr string, shipDead, gameEnded bool, err type Battleship struct { sync.Mutex - zeroID int64 + zeroID database.UserID games map[string]*BSGame } diff --git a/pkg/web/handlers/api/v1/chess.go b/pkg/web/handlers/api/v1/chess.go @@ -27,7 +27,7 @@ import ( ) type ChessPlayer struct { - ID int64 + ID database.UserID Username string UserStyle string NotifyChessMove bool @@ -64,7 +64,7 @@ func newChessGame(gameKey string, player1, player2 database.User) *ChessGame { type Chess struct { sync.Mutex - zeroID int64 + zeroID database.UserID games map[string]*ChessGame } @@ -403,7 +403,7 @@ func (b *Chess) NewGame(gameKey string, user1, user2 database.User) *ChessGame { return g } -func (b *Chess) SendMove(gameKey string, userID int64, g *ChessGame, c echo.Context) error { +func (b *Chess) SendMove(gameKey string, userID database.UserID, g *ChessGame, c echo.Context) error { if (g.Game.Position().Turn() == chess.White && userID != g.Player1.ID) || (g.Game.Position().Turn() == chess.Black && userID != g.Player2.ID) { return errors.New("not your turn") diff --git a/pkg/web/handlers/api/v1/handlers.go b/pkg/web/handlers/api/v1/handlers.go @@ -167,7 +167,7 @@ func ChatMessagesHandler(c echo.Context) error { func UserHellbanHandler(c echo.Context) error { authUser := c.Get("authUser").(*database.User) if authUser.IsModerator() { - userID := utils.DoParseInt64(c.Param("userID")) + userID := database.UserID(utils.DoParseInt64(c.Param("userID"))) user, err := database.GetUserByID(userID) if err != nil { return c.Redirect(http.StatusFound, c.Request().Referer()) @@ -188,7 +188,7 @@ func UserHellbanHandler(c echo.Context) error { func KickHandler(c echo.Context) error { authUser := c.Get("authUser").(*database.User) if authUser.IsModerator() { - userID := utils.DoParseInt64(c.Param("userID")) + userID := database.UserID(utils.DoParseInt64(c.Param("userID"))) user, err := database.GetUserByID(userID) if err != nil { return c.Redirect(http.StatusFound, c.Request().Referer()) diff --git a/pkg/web/handlers/api/v1/msgInterceptor.go b/pkg/web/handlers/api/v1/msgInterceptor.go @@ -63,7 +63,7 @@ func generalRoomKarma(authUser *database.User) { // ProcessRawMessage return the new html, and a map of tagged users used for notifications // This function takes an "unsafe" user input "in", and return html which will be safe to render. -func ProcessRawMessage(in, roomKey string, authUserID, roomID int64, upload *database.Upload) (string, map[int64]database.User) { +func ProcessRawMessage(in, roomKey string, authUserID database.UserID, roomID int64, upload *database.Upload) (string, map[database.UserID]database.User) { html, quoted := convertQuote(in, roomKey, roomID) // Get raw quote text which is not safe to render html = html2.EscapeString(html) // Makes user input safe to render // All html generated from this point on shall be safe to render. @@ -85,7 +85,7 @@ func ProcessRawMessage(in, roomKey string, authUserID, roomID int64, upload *dat } func sendInboxes(room database.ChatRoom, authUser, toUser *database.User, msgID int64, groupID *int64, html string, modMsg bool, - taggedUsersIDsMap map[int64]database.User) { + taggedUsersIDsMap map[database.UserID]database.User) { // Only have chat inbox for unencrypted messages if room.IsProtected() { return @@ -100,13 +100,13 @@ func sendInboxes(room database.ChatRoom, authUser, toUser *database.User, msgID } blacklistedBy, _ := database.GetPmBlacklistedByUsers(authUser.ID) - blacklistedByMap := make(map[int64]struct{}) + blacklistedByMap := make(map[database.UserID]struct{}) for _, b := range blacklistedBy { blacklistedByMap[b.UserID] = struct{}{} } ignoredBy, _ := database.GetIgnoredByUsers(authUser.ID) - ignoredByMap := make(map[int64]struct{}) + ignoredByMap := make(map[database.UserID]struct{}) for _, b := range ignoredBy { ignoredByMap[b.UserID] = struct{}{} } diff --git a/pkg/web/handlers/api/v1/snippetInterceptor.go b/pkg/web/handlers/api/v1/snippetInterceptor.go @@ -21,7 +21,7 @@ func (i SnippetInterceptor) InterceptMsg(cmd *Command) { var snippetRgx = regexp.MustCompile(`!\w{1,20}`) -func snippets(authUserID int64, html string) string { +func snippets(authUserID database.UserID, html string) string { if snippetRgx.MatchString(html) { userSnippets, _ := database.GetUserSnippets(authUserID) if len(userSnippets) > 0 { diff --git a/pkg/web/handlers/api/v1/topBarHandler.go b/pkg/web/handlers/api/v1/topBarHandler.go @@ -448,7 +448,7 @@ type Command struct { room database.ChatRoom // Room the user is in roomKey string // Room password (if any) authUser *database.User // Authenticated user - fromUserID int64 // Sender of message + fromUserID database.UserID // Sender of message toUser *database.User // If not nil, will be a PM upload *database.Upload // If the message contains an uploaded file editMsg *database.ChatMessage // If we're editing a message @@ -512,7 +512,7 @@ func (c *Command) rawMsg(user1 database.User, user2 *database.User, raw, msg str } func rawMsgRoom(user1 database.User, user2 *database.User, raw, msg, roomKey string, roomID int64) { - var toUserID *int64 + var toUserID *database.UserID if user2 != nil { toUserID = &user2.ID } @@ -574,7 +574,7 @@ func sanitizeUserInput(html string) string { // Convert timestamps such as 01:23:45 to an archive link if a message with that timestamp exists. // eg: "Some text 14:31:46 some more text" -func convertArchiveLinks(html string, roomID, authUserID int64) string { +func convertArchiveLinks(html string, roomID int64, authUserID database.UserID) string { start, rest := "", html // Do not replace timestamps that are inside a quote text @@ -625,7 +625,7 @@ type getUsersByUsernameFn func(usernames []string) ([]database.User, error) // Update the given html to add user style for tags. // Return the new html, and a map[userID]User of tagged users. -func colorifyTaggedUsers(html string, getUsersByUsername getUsersByUsernameFn) (string, map[int64]database.User) { +func colorifyTaggedUsers(html string, getUsersByUsername getUsersByUsernameFn) (string, map[database.UserID]database.User) { usernameMatches := tagRgx.FindAllStringSubmatch(html, -1) usernames := hashset.New[string]() for _, usernameMatch := range usernameMatches { @@ -634,7 +634,7 @@ func colorifyTaggedUsers(html string, getUsersByUsername getUsersByUsernameFn) ( taggedUsers, _ := getUsersByUsername(usernames.ToArray()) taggedUsersMap := make(map[string]database.User) - taggedUsersIDsMap := make(map[int64]database.User) + taggedUsersIDsMap := make(map[database.UserID]database.User) for _, taggedUser := range taggedUsers { taggedUsersMap["@"+taggedUser.Username] = taggedUser if taggedUser.Username != "0" { @@ -991,7 +991,7 @@ func extractPGPMessage(html string) (out string) { } // Auto convert pasted pgp message into uploaded file -func convertPGPMessageToFile(html string, authUserID int64) string { +func convertPGPMessageToFile(html string, authUserID database.UserID) string { startIdx := strings.Index(html, pgpPrefix) endIdx := strings.Index(html, pgpSuffix) if startIdx != -1 && endIdx != -1 { @@ -1012,7 +1012,7 @@ func convertPGPMessageToFile(html string, authUserID int64) string { } // Auto convert pasted pgp public key into uploaded file -func convertPGPPublicKeyToFile(html string, authUserID int64) string { +func convertPGPPublicKeyToFile(html string, authUserID database.UserID) string { startIdx := strings.Index(html, pgpPKeyPrefix) endIdx := strings.Index(html, pgpPKeySuffix) if startIdx != -1 && endIdx != -1 { @@ -1069,7 +1069,7 @@ func convertInlinePGPPublicKey(inlinePKey string) string { } // Auto convert pasted age message into uploaded file -func convertAgeMessageToFile(html string, authUserID int64) string { +func convertAgeMessageToFile(html string, authUserID database.UserID) string { startIdx := strings.Index(html, agePrefix) endIdx := strings.Index(html, ageSuffix) if startIdx != -1 && endIdx != -1 { diff --git a/pkg/web/handlers/api/v1/werewolf.go b/pkg/web/handlers/api/v1/werewolf.go @@ -40,30 +40,30 @@ type Werewolf struct { ctx context.Context cancel context.CancelFunc readyCh chan bool - narratorID int64 + narratorID database.UserID roomID int64 werewolfGroupID int64 spectatorGroupID int64 deadGroupID int64 players map[string]*Player playersAlive map[string]*Player - spectators map[int64]struct{} + spectators map[database.UserID]struct{} werewolves []int64 state int64 - werewolfSet *hashset.HashSet[int64] - spectatorSet *hashset.HashSet[int64] - healerID *int64 - seerID *int64 - townspersonSet *hashset.HashSet[int64] + werewolfSet *hashset.HashSet[database.UserID] + spectatorSet *hashset.HashSet[database.UserID] + healerID *database.UserID + seerID *database.UserID + townspersonSet *hashset.HashSet[database.UserID] werewolfCh chan string seerCh chan string healerCh chan string votesCh chan string - voted *hashset.HashSet[int64] // Keep track of which user voted already + voted *hashset.HashSet[database.UserID] // Keep track of which user voted already } // Return either or not the userID is an active player (alive) -func (b *Werewolf) isAlivePlayer(userID int64) bool { +func (b *Werewolf) isAlivePlayer(userID database.UserID) bool { for _, player := range b.playersAlive { if player.UserID == userID { return true @@ -328,12 +328,12 @@ func (b *Werewolf) isValidPlayerName(name string) bool { } // Narrate register a chat message on behalf of the narrator user -func (b *Werewolf) Narrate(msg string, toUserID, groupID *int64) { +func (b *Werewolf) Narrate(msg string, toUserID *database.UserID, groupID *int64) { html, _ := ProcessRawMessage(msg, "", b.narratorID, b.roomID, nil) b.NarrateRaw(html, toUserID, groupID) } -func (b *Werewolf) NarrateRaw(msg string, toUserID, groupID *int64) { +func (b *Werewolf) NarrateRaw(msg string, toUserID *database.UserID, groupID *int64) { _, _ = database.CreateOrEditMessage(nil, msg, msg, "", b.roomID, b.narratorID, toUserID, nil, groupID, false, false) } @@ -444,7 +444,7 @@ func (b *Werewolf) StartGame() { } b.state = VoteState - b.voted = hashset.New[int64]() + b.voted = hashset.New[database.UserID]() b.Narrate("It's now time to vote for execution. PM me the name you vote to execute or \"none\"", nil, nil) killName := b.killVote() if killName == "" { @@ -655,7 +655,7 @@ func (b *Werewolf) UnlockGroup(groupName string) { } type Player struct { - UserID int64 + UserID database.UserID Username string Role string } @@ -663,13 +663,13 @@ type Player struct { func (b *Werewolf) reset() { b.ctx, b.cancel = context.WithCancel(context.Background()) b.state = PreGameState - b.spectators = make(map[int64]struct{}) + b.spectators = make(map[database.UserID]struct{}) b.players = make(map[string]*Player) b.playersAlive = make(map[string]*Player) - b.werewolfSet = hashset.New[int64]() - b.spectatorSet = hashset.New[int64]() - b.townspersonSet = hashset.New[int64]() - b.voted = hashset.New[int64]() + b.werewolfSet = hashset.New[database.UserID]() + b.spectatorSet = hashset.New[database.UserID]() + b.townspersonSet = hashset.New[database.UserID]() + b.voted = hashset.New[database.UserID]() b.werewolfCh = make(chan string) b.seerCh = make(chan string) b.healerCh = make(chan string) diff --git a/pkg/web/handlers/handlers.go b/pkg/web/handlers/handlers.go @@ -198,7 +198,7 @@ func HomeHandler(c echo.Context) error { // partialAuthCache keep track of partial auth token -> user id. // When a user login and have 2fa enabled, we create a "partial" auth cookie. // The token can be used to complete the 2fa authentication. -var partialAuthCache = cache1.New[int64](10*time.Minute, time.Hour) +var partialAuthCache = cache1.New[database.UserID](10*time.Minute, time.Hour) func LoginHandler(c echo.Context) error { @@ -2493,7 +2493,7 @@ func SettingsChatPMHandler(c echo.Context) error { return c.Redirect(http.StatusFound, c.Request().Referer()) } else if formName == "rmWhitelist" { - userID := utils.DoParseInt64(c.Request().PostFormValue("userID")) + userID := database.UserID(utils.DoParseInt64(c.Request().PostFormValue("userID"))) database.RmWhitelistedUser(authUser.ID, userID) return c.Redirect(http.StatusFound, c.Request().Referer()) @@ -2508,7 +2508,7 @@ func SettingsChatPMHandler(c echo.Context) error { return c.Redirect(http.StatusFound, c.Request().Referer()) } else if formName == "rmBlacklist" { - userID := utils.DoParseInt64(c.Request().PostFormValue("userID")) + userID := database.UserID(utils.DoParseInt64(c.Request().PostFormValue("userID"))) database.RmBlacklistedUser(authUser.ID, userID) return c.Redirect(http.StatusFound, c.Request().Referer()) } @@ -2545,7 +2545,7 @@ func SettingsChatIgnoreHandler(c echo.Context) error { return c.Redirect(http.StatusFound, c.Request().Referer()) } else if formName == "rmIgnored" { - userID := utils.DoParseInt64(c.Request().PostFormValue("userID")) + userID := database.UserID(utils.DoParseInt64(c.Request().PostFormValue("userID"))) database.UnIgnoreUser(authUser.ID, userID) return c.Redirect(http.StatusFound, c.Request().Referer()) } @@ -3280,8 +3280,8 @@ type ValueTokenCache struct { PKey string // age/pgp public key } -var ageTokenCache = cache1.NewWithKey[int64, ValueTokenCache](10*time.Minute, time.Hour) -var pgpTokenCache = cache1.NewWithKey[int64, ValueTokenCache](10*time.Minute, time.Hour) +var ageTokenCache = cache1.NewWithKey[database.UserID, ValueTokenCache](10*time.Minute, time.Hour) +var pgpTokenCache = cache1.NewWithKey[database.UserID, ValueTokenCache](10*time.Minute, time.Hour) func SettingsPGPHandler(c echo.Context) error { authUser := c.Get("authUser").(*database.User) @@ -3309,7 +3309,7 @@ func SettingsAgeHandler(c echo.Context) error { return c.Render(http.StatusOK, "settings.age", data) } -func generateAgeEncryptedTokenMessage(userID int64, pkey string) (string, error) { +func generateAgeEncryptedTokenMessage(userID database.UserID, pkey string) (string, error) { token := utils.GenerateToken32() ageTokenCache.Set(userID, ValueTokenCache{Value: token, PKey: pkey}, 10*time.Minute) @@ -3333,14 +3333,14 @@ func generateAgeEncryptedTokenMessage(userID int64, pkey string) (string, error) return out.String(), nil } -func generatePgpEncryptedTokenMessage(userID int64, pkey string) (string, error) { +func generatePgpEncryptedTokenMessage(userID database.UserID, pkey string) (string, error) { token := utils.GenerateToken32() pgpTokenCache.Set(userID, ValueTokenCache{Value: token, PKey: pkey}, 10*time.Minute) msg := "The required code is below the line.\n----------------------------------------------------------------------------------\n" + token + "\n" return utils.GeneratePgpEncryptedMessage(pkey, msg) } -func generatePgpToBeSignedTokenMessage(userID int64, txt, pkey string) string { +func generatePgpToBeSignedTokenMessage(userID database.UserID, txt, pkey string) string { token := utils.GenerateToken10() msg := fmt.Sprintf("%s\n%s\n%s", txt, token, time.Now().UTC().Format("Jan 02, 2006")) pgpTokenCache.Set(userID, ValueTokenCache{Value: msg, PKey: pkey}, 10*time.Minute) @@ -3445,7 +3445,7 @@ func AddAgeHandler(c echo.Context) error { } // twoFactorCache ... -var twoFactorCache = cache1.NewWithKey[int64, twoFactorObj](10*time.Minute, time.Hour) +var twoFactorCache = cache1.NewWithKey[database.UserID, twoFactorObj](10*time.Minute, time.Hour) type twoFactorObj struct { key *otp.Key @@ -3691,7 +3691,7 @@ func TorchessDownloadsHandler(c echo.Context) error { return c.Render(http.StatusOK, "torchess-downloads", data) } -var flagValidationCache = cache1.NewWithKey[int64, bool](time.Minute, time.Hour) +var flagValidationCache = cache1.NewWithKey[database.UserID, bool](time.Minute, time.Hour) // VipDownloadsHandler ... func VipDownloadsHandler(c echo.Context) error { @@ -4011,7 +4011,7 @@ func GetFileContentType(out io.ReadSeeker) (string, error) { } var byteRoadSignUpSessionCache = cache1.New[bool](10*time.Minute, 10*time.Minute) -var byteRoadUsersCountCache = cache1.NewWithKey[int64, ByteRoadPayload](5*time.Minute, 10*time.Minute) +var byteRoadUsersCountCache = cache1.NewWithKey[database.UserID, ByteRoadPayload](5*time.Minute, 10*time.Minute) type ByteRoadPayload struct { Count int64 diff --git a/pkg/web/middlewares/middlewares.go b/pkg/web/middlewares/middlewares.go @@ -82,7 +82,7 @@ func GenericRateLimitMiddleware(period time.Duration, limit int64) echo.Middlewa return func(c echo.Context) error { key := "ip_" + c.RealIP() if authUser, ok := c.Get("authUser").(*database.User); ok && authUser != nil { - key = "userid_" + utils.FormatInt64(authUser.ID) + key = "userid_" + utils.FormatInt64(int64(authUser.ID)) } else if conn, ok := c.Request().Context().Value("conn").(net.Conn); ok { circuitID := config.ConnMap.Get(conn) key = "circuitid_" + utils.FormatInt64(circuitID) @@ -142,7 +142,7 @@ func AuthRateLimitMiddleware(period time.Duration, limit int64) echo.MiddlewareF return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { authUser := c.Get("authUser").(*database.User) - context, err := limiterInstance.Get(c.Request().Context(), utils.FormatInt64(authUser.ID)) + context, err := limiterInstance.Get(c.Request().Context(), utils.FormatInt64(int64(authUser.ID))) if err != nil { // fmt.Errorf("could not get context for IP %s - %v", c.RealIP(), err) return next(c)