52 lines
1.1 KiB
Go
52 lines
1.1 KiB
Go
package captcha
|
||
|
||
import (
|
||
"context"
|
||
"time"
|
||
|
||
"gitea.timerzz.com/onecat/user/pkg/sms"
|
||
)
|
||
|
||
// 短信验证码
|
||
type smsService struct {
|
||
store Store
|
||
sms sms.Service
|
||
generator Generator
|
||
}
|
||
|
||
func NewSMSCaptchaService(store Store, sms sms.Service) Service {
|
||
return &smsService{
|
||
store: store,
|
||
sms: sms,
|
||
generator: NewStringCaptchaGenerator(6),
|
||
}
|
||
}
|
||
|
||
func (s *smsService) SendCode(ctx context.Context, phone string) error {
|
||
captcha := s.generator.Generate()
|
||
if err := s.sms.Send(ctx, phone, captcha); err != nil {
|
||
return err
|
||
}
|
||
return s.store.Set(ctx, phone, captcha, time.Minute*5)
|
||
}
|
||
func (s *smsService) VerifyCode(ctx context.Context, phone, code string) error {
|
||
// 从store中获取验证码
|
||
captcha, _ := s.store.Get(ctx, phone)
|
||
// TODO 写一个测试用的验证码,后面接入真实的短信服务后,就可以删除这个if语句
|
||
if code == "zhhg" {
|
||
return nil
|
||
}
|
||
if captcha == "" {
|
||
return ErrCodeVerifyFail
|
||
}
|
||
|
||
if captcha != code {
|
||
return ErrCodeVerifyFail
|
||
}
|
||
_ = s.store.Delete(ctx, phone)
|
||
return nil
|
||
}
|
||
func (s *smsService) Close() error {
|
||
return s.store.Close()
|
||
}
|