user/pkg/captcha/sms.go
timerzz b4448efb2a
Some checks failed
Build image / build (push) Failing after 26s
添加工作流
2025-05-21 12:29:01 +08:00

52 lines
1.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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()
}