-
Notifications
You must be signed in to change notification settings - Fork 2
/
verifier.go
452 lines (385 loc) · 12.3 KB
/
verifier.go
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Package verifier is used for validation & verification of email, sms etc.
package verifier
import (
"errors"
"time"
)
const (
// CommTypeMobile communication type mobile
CommTypeMobile = CommType("mobile")
// CommTypeEmail communication type email
CommTypeEmail = CommType("email")
// VerStatusPending verification status pending
VerStatusPending = verificationStatus("pending")
// VerStatusExpired verification status expired
VerStatusExpired = verificationStatus("expired")
// VerStatusVerified verification status verified
VerStatusVerified = verificationStatus("verified")
// VerStatusRejected verification status rejected
VerStatusRejected = verificationStatus("rejected")
// VerStatusExceededAttempts verification status when attempts are exceeded
VerStatusExceededAttempts = verificationStatus("exceeded-attempts")
)
var (
// ErrMaximumAttemptsExceeded is the error returned when maximum verification attempts have exceeded
ErrMaximumAttemptsExceeded = errors.New("maximum attempts exceeded")
// ErrSecretExpired is the error returned when the verification secret has expired
ErrSecretExpired = errors.New("verification secret expired")
// ErrInvalidSecret is the error returned upon receiving invalid secret
ErrInvalidSecret = errors.New("invalid verification secret")
// ErrInvalidMobileNumber is the error returned upon receiving invalid mobile number
ErrInvalidMobileNumber = errors.New("invalid mobile number provided")
// ErrInvalidEmail is the error returned upon receiving invalid email address
ErrInvalidEmail = errors.New("invalid email address provided")
// ErrEmptyEmailBody is the error returned when using custom email body and it's empty
ErrEmptyEmailBody = errors.New("empty email body")
// ErrEmptyMobileMessageBody is the error returned when using custom mobile message body and it's empty
ErrEmptyMobileMessageBody = errors.New("empty mobile message body")
)
// CommType defines the communication type (mobile, Email)
type CommType string
// verificationStatus defines the status of a verification request (e.g. pending, verified, rejected)
type verificationStatus string
type emailService interface {
// the interface returned is expected to be a reference ID for the communication sent
// This might be a single ref ID or more info based on the service we're using
Send(sender, recipient, subject, body string) (interface{}, error)
}
type mobileService interface {
// the interface returned is expected to be a reference ID for the communication sent
// This might be a single ref ID or more info based on the service we're using
Send(recipient, body string) (interface{}, error)
}
type store interface {
Create(ver *Request) (*Request, error)
ReadLastPending(ctype CommType, recipient string) (*Request, error)
Update(verID string, ver *Request) (*Request, error)
}
func newID() string {
return randomString(32)
}
// Config has all the configurations required for verifier package to function
type Config struct {
// MaxVerifyAttempts is used to set the maximum number of times verification attempts can be made
MaxVerifyAttempts int `json:"maxVerifyAttempts,omitempty"`
// EmailOTPExpiry is used to define the expiry of a secret generated to verify email
EmailOTPExpiry time.Duration `json:"emailOTPExpiry,omitempty"`
// MobileOTPExpiry is used to define the expiry of a secret generated to verify mobile phone number
MobileOTPExpiry time.Duration `json:"mobileOTPExpiry,omitempty"`
// EmailCallbackURL is used to generate the callback link which is sent in the verification email
/*
Two query string attributes are added to the callback URL while sending the verification link.
1) 'email' - The email address to which verification mail was sent
2) 'secret' - The secret generated for the email, this is required while verification
*/
EmailCallbackURL string `json:"emailCallbackURL,omitempty"`
// DefaultFromEmail is used to set the "from" email while sending verification emails
DefaultFromEmail string `json:"defaultFromEmail,omitempty"`
// DefaultEmailSub is the email subject set while sending verification emails
/*
If not set, a hardcoded string "Email verification request" is set as the subject.
The default subject is used if no subject is sent while calling the Send function
*/
DefaultEmailSub string `json:"defaultEmailSub,omitempty"`
}
func (cfg *Config) init() {
if cfg.MaxVerifyAttempts < 1 {
cfg.MaxVerifyAttempts = 3
}
}
// CommStatus stores the status of the communication sent
type CommStatus struct {
Status string `json:"status,omitempty"`
Data map[string]interface{} `json:"data,omitempty"`
}
// Request struct holds all data related to a single verification request
type Request struct {
ID string `json:"id,omitempty"`
Type CommType `json:"type,omitempty"`
Sender string `json:"sender,omitempty"`
Recipient string `json:"recipient,omitempty"`
Data map[string]string `json:"data,omitempty"`
Secret string `json:"secret,omitempty"`
SecretExpiry *time.Time `json:"secretExpiry,omitempty"`
// Attempts has the number of times verification has been attempted
Attempts int `json:"attempts,omitempty"`
// CommStatus is the communication status, and is maintained as a list to later store
// statuses of retries
CommStatus []CommStatus `json:"commStatus,omitempty"`
Status verificationStatus `json:"status,omitempty"`
CreatedAt *time.Time `json:"createdAt,omitempty"`
UpdatedAt *time.Time `json:"updatedAt,omitempty"`
}
func (v *Request) setStatus(status interface{}, err error) {
if status != nil {
if len(v.CommStatus) == 0 {
v.CommStatus = make([]CommStatus, 0, 1)
}
v.CommStatus = append(
v.CommStatus,
CommStatus{
Status: "queued",
Data: map[string]interface{}{
"status": status,
},
},
)
return
}
if err != nil {
if len(v.CommStatus) == 0 {
v.CommStatus = make([]CommStatus, 0, 1)
}
v.CommStatus = append(
v.CommStatus,
CommStatus{
Status: "failed",
Data: map[string]interface{}{
"error": err.Error(),
},
},
)
return
}
}
// Verifier struct exposes all services provided by verify package
type Verifier struct {
cfg *Config
emailHandler emailService
mobileHandler mobileService
store store
}
// NewRequest is used to create a new verification request
func (ver *Verifier) NewRequest(ctype CommType, recipient string) (*Request, error) {
now := time.Now()
secExpiry := now.Add(ver.cfg.EmailOTPExpiry)
secret := randomString(256)
switch ctype {
case CommTypeMobile:
{
secExpiry = now.Add(ver.cfg.MobileOTPExpiry)
secret = randomNumericString(6)
}
}
verReq := &Request{
ID: newID(),
Type: ctype,
Recipient: recipient,
Data: nil,
Secret: secret,
SecretExpiry: &secExpiry,
Status: VerStatusPending,
CreatedAt: &now,
UpdatedAt: &now,
}
verReq, err := ver.store.Create(verReq)
if err != nil {
return nil, err
}
return verReq, nil
}
func (ver *Verifier) verifySecret(ctype CommType, recipient, secret string) error {
verreq, err := ver.store.ReadLastPending(ctype, recipient)
if err != nil {
return err
}
return ver.verifyAndUpdate(secret, verreq)
}
func (ver *Verifier) validate(secret string, verreq *Request) error {
if verreq.Attempts > ver.cfg.MaxVerifyAttempts {
return ErrMaximumAttemptsExceeded
}
now := time.Now()
if verreq.SecretExpiry.Before(now) {
return ErrSecretExpired
}
if secret != verreq.Secret {
return ErrInvalidSecret
}
return nil
}
// verifyAndUpdate verifies all conditions required to verify a secret. And then update
// the status of verification in the store
func (ver *Verifier) verifyAndUpdate(secret string, verreq *Request) error {
var err error
now := time.Now()
verreq.UpdatedAt = &now
verreq.Attempts++
validationErr := ver.validate(secret, verreq)
switch validationErr {
case ErrMaximumAttemptsExceeded:
{
verreq.Status = VerStatusExceededAttempts
verreq, err = ver.store.Update(verreq.ID, verreq)
if err != nil {
return err
}
}
case ErrSecretExpired:
{
verreq.Status = VerStatusExpired
verreq, err = ver.store.Update(verreq.ID, verreq)
if err != nil {
return err
}
}
case ErrInvalidSecret:
{
verreq.Status = VerStatusRejected
verreq, err = ver.store.Update(verreq.ID, verreq)
if err != nil {
return err
}
}
}
if validationErr != nil {
return validationErr
}
verreq.Status = VerStatusVerified
verreq, err = ver.store.Update(verreq.ID, verreq)
if err != nil {
return err
}
return nil
}
// VerifyEmailSecret validates an email and its verification secret
func (ver *Verifier) VerifyEmailSecret(recipient, secret string) error {
return ver.verifySecret(CommTypeEmail, recipient, secret)
}
// NewEmailWithReq is used to send a mail with a custom verification request
func (ver *Verifier) NewEmailWithReq(verreq *Request, subject, body string) error {
err := validateEmailAddress(verreq.Recipient)
if err != nil {
return err
}
if body == "" {
return ErrEmptyEmailBody
}
if subject == "" {
subject = ver.cfg.DefaultEmailSub
if subject == "" {
subject = "Email verification request"
}
}
status, sendErr := ver.emailHandler.Send(
ver.cfg.DefaultFromEmail,
verreq.Recipient,
subject,
body,
)
verreq.setStatus(status, sendErr)
verreq, err = ver.store.Update(verreq.ID, verreq)
if err != nil {
return err
}
if sendErr != nil {
return sendErr
}
return nil
}
// NewEmail creates a new request for email verification
func (ver *Verifier) NewEmail(recipient, subject string) error {
err := validateEmailAddress(recipient)
if err != nil {
return err
}
verreq, err := ver.NewRequest(CommTypeEmail, recipient)
if err != nil {
return err
}
callbackURL, err := EmailCallbackURL(ver.cfg.EmailCallbackURL, verreq.Recipient, verreq.Secret)
if err != nil {
return err
}
if subject == "" {
subject = ver.cfg.DefaultEmailSub
if subject == "" {
subject = "Email verification request"
}
}
return ver.NewEmailWithReq(
verreq,
subject,
emailBody(callbackURL, ver.cfg.EmailOTPExpiry.String()),
)
}
// NewMobileWithReq creates a new request for mobile number verification
func (ver *Verifier) NewMobileWithReq(verreq *Request, body string) error {
err := validateMobile(verreq.Recipient)
if err != nil {
return err
}
if body == "" {
return ErrEmptyMobileMessageBody
}
status, sendErr := ver.mobileHandler.Send(
verreq.Recipient,
body,
)
verreq.setStatus(status, sendErr)
verreq, err = ver.store.Update(verreq.ID, verreq)
if err != nil {
return nil
}
if sendErr != nil {
return sendErr
}
return nil
}
// NewMobile creates a new request for mobile number verification with default setting
func (ver *Verifier) NewMobile(recipient string) error {
err := validateMobile(recipient)
if err != nil {
return err
}
verreq, err := ver.NewRequest(CommTypeMobile, recipient)
if err != nil {
return err
}
return ver.NewMobileWithReq(
verreq,
smsBody(verreq.Secret, ver.cfg.MobileOTPExpiry.String()),
)
}
// VerifyMobileSecret validates a mobile number and its verification secret (OTP)
func (ver *Verifier) VerifyMobileSecret(recipient, secret string) error {
return ver.verifySecret(CommTypeMobile, recipient, secret)
}
// CustomEmailHandler is used to set a custom email sending service
func (ver *Verifier) CustomEmailHandler(email emailService) error {
ver.emailHandler = email
// TODO: implement a validation method later, by implementing Ping
return nil
}
// CustomStore is used to set a custom persistent store
func (ver *Verifier) CustomStore(verStore store) error {
ver.store = verStore
// TODO: implement a validation method later, by implementing Ping
return nil
}
// CustomMobileHandler is used to set a custom mobile message sending service
func (ver *Verifier) CustomMobileHandler(mobile mobileService) error {
ver.mobileHandler = mobile
// TODO: implement a validation method later, by implementing Ping
return nil
}
// New lets you customize various components
func New(cfg *Config, verStore store, email emailService, mobile mobileService) (*Verifier, error) {
cfg.init()
v := &Verifier{
cfg: cfg,
}
err := v.CustomEmailHandler(email)
if err != nil {
return nil, err
}
err = v.CustomMobileHandler(mobile)
if err != nil {
return nil, err
}
err = v.CustomStore(verStore)
if err != nil {
return nil, err
}
return v, nil
}