Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

user/mysql: Fix session delete bug. #1681

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 44 additions & 12 deletions politeiawww/legacy/user/mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -964,24 +964,35 @@ func (m *mysql) SessionsDeleteByUserID(uid uuid.UUID, exemptSessionIDs []string)
ctx, cancel := ctxWithTimeout()
defer cancel()

// Session primary key is a SHA256 hash of the session ID.
exempt := make([]string, 0, len(exemptSessionIDs))
// Build the sql query. Using an empty NOT IN() set
// results in no records being deleted, so the queries
// will differ when exempt session IDs are present.
var q string
if len(exemptSessionIDs) == 0 {
q = "DELETE FROM sessions WHERE user_id = ?"
} else {
q = fmt.Sprintf("DELETE FROM sessions WHERE user_id = ? AND k NOT IN %v",
buildPlaceholders(len(exemptSessionIDs)))
}

// Prepare the query arguments
args := []interface{}{
uid.String(),
}
for _, v := range exemptSessionIDs {
exempt = append(exempt, hex.EncodeToString(util.Digest([]byte(v))))
// Convert the exemptSessionIDs to hex encoded
// SHA256 hashes. These hashes are the primary
// keys for the sessions in the database.
h := hex.EncodeToString(util.Digest([]byte(v)))
args = append(args, h)
}

// Using an empty NOT IN() set will result in no records being
// deleted.
if len(exempt) == 0 {
_, err := m.userDB.
ExecContext(ctx, "DELETE FROM sessions WHERE user_id = ?", uid.String())
_, err := m.userDB.ExecContext(ctx, q, args...)
if err != nil {
return err
}

_, err := m.userDB.
ExecContext(ctx, "DELETE FROM sessions WHERE user_id = ? AND k NOT IN (?)",
uid.String(), exempt)
return err
return nil
}

// SetPaywallAddressIndex updates the paywall address index.
Expand Down Expand Up @@ -1413,3 +1424,24 @@ func New(host, password, network, encryptionKey string) (*mysql, error) {
encryptionKey: key,
}, nil
}

// buildPlaceholders builds and returns a parameter placeholder string with the
// specified number of placeholders.
//
// Input: 1 Output: "(?)"
// Input: 3 Output: "(?,?,?)"
func buildPlaceholders(placeholders int) string {
var b strings.Builder

b.WriteString("(")
for i := 0; i < placeholders; i++ {
b.WriteString("?")
// Don't add a comma on the last one
if i < placeholders-1 {
b.WriteString(",")
}
}
b.WriteString(")")

return b.String()
}