feat: referral code validation in registration with tests

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
2026-05-29 16:06:19 +01:00
co-authored by Sisyphus
parent 0f118205d6
commit 9deae1b0d7
2 changed files with 161 additions and 0 deletions
+36
View File
@@ -63,6 +63,7 @@ type RegisterRequest struct {
Phone string `json:"phone"`
DateOfBirth string `json:"dateOfBirth"`
AgreedToPolicy bool `json:"agreedToPolicy"`
ReferralCode string `json:"referralCode,omitempty"`
}
type LoginRequest struct {
@@ -160,6 +161,28 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
return
}
// Validate referral code if provided
var referrerID *string
req.ReferralCode = strings.TrimSpace(req.ReferralCode)
if req.ReferralCode != "" {
if len(req.ReferralCode) != 12 {
http.Error(w, "referral code must be exactly 12 characters", http.StatusBadRequest)
return
}
referralCodeRegex := regexp.MustCompile(`^[a-zA-Z0-9]{12}$`)
if !referralCodeRegex.MatchString(req.ReferralCode) {
http.Error(w, "referral code must be alphanumeric", http.StatusBadRequest)
return
}
// Look up referrer by referral code
err := db.DB.QueryRow(r.Context(),
"SELECT id FROM users WHERE referral_code = $1", req.ReferralCode).Scan(&referrerID)
if err != nil {
http.Error(w, "invalid referral code", http.StatusBadRequest)
return
}
}
// Hash password
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
@@ -197,6 +220,19 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
return
}
// Record referral relationship if referral code was provided
if referrerID != nil {
_, err = tx.Exec(r.Context(), `
INSERT INTO user_referrals (referrer_id, referred_id)
VALUES ($1, $2)
ON CONFLICT DO NOTHING
`, *referrerID, userID)
if err != nil {
http.Error(w, "could not process referral", http.StatusInternalServerError)
return
}
}
if err := tx.Commit(r.Context()); err != nil {
http.Error(w, "server error", http.StatusInternalServerError)
return