~evanj/cms

ref: 9d7fbcbdf7e7332ea56493092efe5cffbadccdd6 cms/internal/s/db/invite.go -rw-r--r-- 5.0 KiB
9d7fbcbdEvan M Jones Fix(go.mod/vendor): Attempting to fix vendoring for deploys. 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package db

import (
	"database/sql"
	"fmt"
	"strconv"
	"time"

	"git.sr.ht/~evanj/cms/internal/m/invite"
	"git.sr.ht/~evanj/cms/internal/m/org"
	"git.sr.ht/~evanj/cms/internal/m/user"
	"git.sr.ht/~evanj/security"
)

type Invite struct {
	// From DB.
	id, createdStr, expiresStr string
	used                       bool
	InviteOrg                  Org
	// Set on get.
	created, expires time.Time
	tok              string
}

var (
	queryCreate = `
		INSERT INTO cms_invite (EXPIRES, ORG_ID, USED) VALUES (?, ?, FALSE)
	`

	queryGet = `
		SELECT cms_invite.ID, CREATED, EXPIRES, USED, cms_org.ID, cms_billing.TIER_NAME, cms_billing.PAYMENT_CUSTOMER 
		FROM cms_invite 
		JOIN cms_org ON cms_org.ID=cms_invite.ORG_ID
		LEFT JOIN cms_billing ON cms_billing.ORG_ID=cms_org.ID
		WHERE cms_invite.ID=?
	`

	queryList = `
		SELECT ID FROM cms_invite WHERE ORG_ID=? AND EXPIRES < ? AND EXPIRES > ? AND USED=FALSE ORDER BY ID DESC
	`

	queryUse = `
		UPDATE cms_invite SET USED=TRUE WHERE ID=?
	`

	mysqlTimeLayout = "2006-01-02 15:04:05"
)

func (db *DB) InviteNew(u user.User, o org.Org) (invite.Invite, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	i, err := db.inviteNew(t, o)
	if err != nil {
		return nil, err
	}

	return i, t.Commit()
}

func (db *DB) inviteNew(t *sql.Tx, o org.Org) (invite.Invite, error) {
	res, err := t.Exec(queryCreate, time.Now().UTC().Add(1*time.Hour), o.ID())
	if err != nil {
		return nil, err
	}

	id, err := res.LastInsertId()
	if err != nil {
		return nil, err
	}

	return db.inviteGet(t, strconv.FormatInt(id, 10))
}

func (db *DB) InviteGet(u user.User, id string) (invite.Invite, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	i, err := db.inviteGet(t, id)
	if err != nil {
		return nil, err
	}

	return i, t.Commit()
}

func (db *DB) inviteGet(t *sql.Tx, id string) (invite.Invite, error) {
	var i Invite
	if err := t.QueryRow(queryGet, id).Scan(
		&i.id, &i.createdStr, &i.expiresStr, &i.used,
		&i.InviteOrg.OrgID, &i.InviteOrg.OrgBillingTierName, &i.InviteOrg.OrgPaymentCustomer,
	); err != nil {
		return nil, err
	}

	created, err := time.Parse(mysqlTimeLayout, i.createdStr)
	if err != nil {
		return nil, err
	}

	expires, err := time.Parse(mysqlTimeLayout, i.expiresStr)
	if err != nil {
		return nil, err
	}

	tok, err := db.sec.TokenCreate(security.TokenMap{"ID": i.id})
	if err != nil {
		return nil, err
	}

	i.created = created
	i.expires = expires
	i.tok = tok

	return i, i.Validate()
}

func (db *DB) InviteAccept(i invite.Invite, u, p, v string) (user.User, invite.Invite, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, nil, err
	}
	defer t.Rollback()

	user, invite, err := db.inviteAccept(t, i, u, p, v)
	if err != nil {
		return nil, nil, err
	}

	return user, invite, t.Commit()
}

func (db *DB) inviteAccept(t *sql.Tx, i invite.Invite, u, p, v string) (user.User, invite.Invite, error) {
	if _, err := t.Exec(queryUse, i.ID()); err != nil {
		return nil, nil, err
	}

	// Create user.
	hash, err := db.userNewGeneratePassword(u, p, v)
	if err != nil {
		return nil, nil, err
	}

	if _, err := t.Exec(queryCreateNewUser, u, hash, i.Org().ID()); err != nil {
		return nil, nil, fmt.Errorf("user '%s' already exists", u)
	}

	user, err := db.userGet(t, u, p)
	if err != nil {
		return nil, nil, err
	}

	return user, i, nil
}

func (db *DB) InviteList(u user.User, o org.Org) (r []invite.Invite, err error) {
	var (
		now  = time.Now().UTC()
		from = now.Format(mysqlTimeLayout)
		// Add a second here. Offset it slightly so user receives expected results.
		to = now.Add(1 * time.Hour).Add(1 * time.Second).Format(mysqlTimeLayout)
	)

	rows, err := db.Query(queryList, o.ID(), to, from)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		var id string
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}

		i, err := db.InviteGet(u, id)
		if err != nil {
			return nil, err
		}

		r = append(r, i)
	}

	return r, nil
}

func (db *DB) inviteGetByToken(t *sql.Tx, tok string) (invite.Invite, error) {
	tmap, err := db.sec.TokenFrom(tok)
	if err != nil {
		return nil, fmt.Errorf("failed to decode invite token")
	}

	id, ok := tmap["ID"]
	if !ok {
		return nil, fmt.Errorf("corrupted invite token")
	}

	str, ok := id.(string)
	if !ok {
		return nil, fmt.Errorf("corrupted invite token")
	}

	i, err := db.inviteGet(t, str)
	if err != nil {
		return nil, err
	}

	if err := i.Validate(); err != nil {
		return nil, err
	}

	return i, nil
}

func (db *DB) InviteGetByToken(tok string) (invite.Invite, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	i, err := db.inviteGetByToken(t, tok)
	if err != nil {
		return nil, err
	}

	return i, t.Commit()
}

func (i Invite) ID() string    { return i.id }
func (i Invite) Token() string { return i.tok }
func (i Invite) Org() org.Org  { return i.InviteOrg }

func (i Invite) Validate() error {
	if i.used {
		return invite.ErrUsed
	}

	if time.Now().UTC().After(i.expires) {
		return invite.ErrExpired
	}

	return nil
}