internal/store/registration.go

0db33b1ad160bda8a1fd2900e84c654ba25f1218
gitbay/internal/store/registration.go history · blame · raw

187 lines · 5950 bytes

  1package store
  2
  3import (
  4	"errors"
  5	"time"
  6)
  7
  8// CreateInvite stores an invite code hash bound to an email address.
  9func (s *Store) CreateInvite(codeHash, email string) error {
 10	_, err := s.DB.Exec("INSERT INTO invites (code_hash, email) VALUES (?, ?)", codeHash, email)
 11	return err
 12}
 13
 14// ConsumeInvite redeems an invite exactly once, returning the address it was
 15// issued for. Used and unknown codes fail identically.
 16func (s *Store) ConsumeInvite(codeHash string) (string, error) {
 17	res, err := s.DB.Exec(
 18		"UPDATE invites SET used_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE code_hash = ? AND used_at IS NULL",
 19		codeHash)
 20	if err != nil {
 21		return "", err
 22	}
 23	if n, _ := res.RowsAffected(); n == 0 {
 24		return "", ErrNotFound
 25	}
 26	var email string
 27	err = s.DB.QueryRow("SELECT email FROM invites WHERE code_hash = ?", codeHash).Scan(&email)
 28	return email, err
 29}
 30
 31// CreateEmailToken stores a verification code hash for one address.
 32func (s *Store) CreateEmailToken(userID int64, address, tokenHash string, ttl time.Duration) error {
 33	_, err := s.DB.Exec(
 34		"INSERT INTO email_tokens (token_hash, user_id, address, expires_at) VALUES (?, ?, ?, ?)",
 35		tokenHash, userID, address, fmtTime(time.Now().Add(ttl)))
 36	return err
 37}
 38
 39// ConsumeEmailToken redeems a verification code for the given user.
 40func (s *Store) ConsumeEmailToken(userID int64, tokenHash string) (string, error) {
 41	res, err := s.DB.Exec(`
 42		UPDATE email_tokens SET used_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
 43		WHERE token_hash = ? AND user_id = ? AND used_at IS NULL AND expires_at > ?`,
 44		tokenHash, userID, fmtTime(time.Now()))
 45	if err != nil {
 46		return "", err
 47	}
 48	if n, _ := res.RowsAffected(); n == 0 {
 49		return "", ErrNotFound
 50	}
 51	var address string
 52	err = s.DB.QueryRow("SELECT address FROM email_tokens WHERE token_hash = ?", tokenHash).Scan(&address)
 53	return address, err
 54}
 55
 56// CreateRegisteredUser makes a self-registered account, pending until its
 57// email is verified.
 58func (s *Store) CreateRegisteredUser(username string, pending bool) (int64, error) {
 59	if taken, err := ownerNameTaken(s.DB, username); err != nil {
 60		return 0, err
 61	} else if taken {
 62		return 0, errors.New("that username is taken")
 63	}
 64	res, err := s.DB.Exec("INSERT INTO users (username, pending) VALUES (?, ?)", username, boolInt(pending))
 65	if err != nil {
 66		if isUniqueErr(err) {
 67			return 0, errors.New("that username is taken")
 68		}
 69		return 0, err
 70	}
 71	return res.LastInsertId()
 72}
 73
 74// ClearPending activates a pending account.
 75func (s *Store) ClearPending(userID int64) error {
 76	_, err := s.DB.Exec("UPDATE users SET pending = 0 WHERE id = ?", userID)
 77	return err
 78}
 79
 80// EmailInUse reports whether an address is attached to any account.
 81func (s *Store) EmailInUse(address string) (bool, error) {
 82	var n int
 83	err := s.DB.QueryRow("SELECT COUNT(*) FROM emails WHERE address = ?", address).Scan(&n)
 84	return n > 0, err
 85}
 86
 87// RedeemInvite performs the whole invite registration in one transaction:
 88// consume the code, create the user, attach the invite's email as verified,
 89// register the key. Any failure rolls everything back — the invite stays
 90// redeemable and no partial account exists.
 91func (s *Store) RedeemInvite(codeHash, username, keyFP, keyAlgo string, keyBlob []byte) (string, error) {
 92	tx, err := s.DB.Begin()
 93	if err != nil {
 94		return "", err
 95	}
 96	defer tx.Rollback()
 97
 98	res, err := tx.Exec(
 99		"UPDATE invites SET used_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE code_hash = ? AND used_at IS NULL",
100		codeHash)
101	if err != nil {
102		return "", err
103	}
104	if n, _ := res.RowsAffected(); n == 0 {
105		return "", ErrNotFound
106	}
107	var email string
108	if err := tx.QueryRow("SELECT email FROM invites WHERE code_hash = ?", codeHash).Scan(&email); err != nil {
109		return "", err
110	}
111
112	if taken, err := ownerNameTaken(tx, username); err != nil {
113		return "", err
114	} else if taken {
115		return "", errors.New("that username is taken")
116	}
117	ures, err := tx.Exec("INSERT INTO users (username) VALUES (?)", username)
118	if err != nil {
119		return "", err
120	}
121	uid, err := ures.LastInsertId()
122	if err != nil {
123		return "", err
124	}
125	if _, err := tx.Exec(
126		`INSERT INTO emails (user_id, address, verified_at, verified_by, is_primary)
127		 VALUES (?, ?, strftime('%Y-%m-%dT%H:%M:%fZ','now'), 'smtp', 1)`, uid, email); err != nil {
128		if isUniqueErr(err) {
129			return "", errors.New("the invited address already belongs to an account")
130		}
131		return "", err
132	}
133	if _, err := tx.Exec(
134		"INSERT INTO ssh_keys (user_id, fingerprint, algo, blob, scope) VALUES (?, ?, ?, ?, 'full')",
135		uid, keyFP, keyAlgo, keyBlob); err != nil {
136		if isUniqueErr(err) {
137			return "", ErrDuplicateKey
138		}
139		return "", err
140	}
141	if err := bumpKeyEpoch(tx); err != nil {
142		return "", err
143	}
144	return email, tx.Commit()
145}
146
147// RegisterOpen performs open registration in one transaction: pending user,
148// unverified email, key. Failure leaves nothing behind.
149func (s *Store) RegisterOpen(username, email, keyFP, keyAlgo string, keyBlob []byte) (int64, error) {
150	tx, err := s.DB.Begin()
151	if err != nil {
152		return 0, err
153	}
154	defer tx.Rollback()
155	if taken, err := ownerNameTaken(tx, username); err != nil {
156		return 0, err
157	} else if taken {
158		return 0, errors.New("that username is taken")
159	}
160	ures, err := tx.Exec("INSERT INTO users (username, pending) VALUES (?, 1)", username)
161	if err != nil {
162		return 0, err
163	}
164	uid, err := ures.LastInsertId()
165	if err != nil {
166		return 0, err
167	}
168	if _, err := tx.Exec(
169		"INSERT INTO emails (user_id, address, is_primary) VALUES (?, ?, 1)", uid, email); err != nil {
170		if isUniqueErr(err) {
171			return 0, errors.New("that address already belongs to an account")
172		}
173		return 0, err
174	}
175	if _, err := tx.Exec(
176		"INSERT INTO ssh_keys (user_id, fingerprint, algo, blob, scope) VALUES (?, ?, ?, ?, 'full')",
177		uid, keyFP, keyAlgo, keyBlob); err != nil {
178		if isUniqueErr(err) {
179			return 0, ErrDuplicateKey
180		}
181		return 0, err
182	}
183	if err := bumpKeyEpoch(tx); err != nil {
184		return 0, err
185	}
186	return uid, tx.Commit()
187}