41 lines
946 B
Go
41 lines
946 B
Go
package captcha
|
|
|
|
import (
|
|
"bytes"
|
|
|
|
"cloudnest/internal/infrastructure/database"
|
|
"github.com/dchest/captcha"
|
|
)
|
|
|
|
type CaptchaService struct {
|
|
redis *database.RedisClient
|
|
}
|
|
|
|
func NewCaptchaService(redis *database.RedisClient) *CaptchaService {
|
|
captcha.SetCustomStore(captcha.NewMemoryStore(100, 5*60*1e9))
|
|
return &CaptchaService{redis: redis}
|
|
}
|
|
|
|
func (s *CaptchaService) Generate() (captchaID string, imageBytes []byte, err error) {
|
|
captchaID = captcha.New()
|
|
|
|
var buf bytes.Buffer
|
|
if err = captcha.WriteImage(&buf, captchaID, 240, 80); err != nil {
|
|
return "", nil, err
|
|
}
|
|
|
|
return captchaID, buf.Bytes(), nil
|
|
}
|
|
|
|
func (s *CaptchaService) GetImage(captchaID string) ([]byte, error) {
|
|
var buf bytes.Buffer
|
|
if err := captcha.WriteImage(&buf, captchaID, 240, 80); err != nil {
|
|
return nil, err
|
|
}
|
|
return buf.Bytes(), nil
|
|
}
|
|
|
|
func (s *CaptchaService) Verify(captchaID, answer string) bool {
|
|
return captcha.VerifyString(captchaID, answer)
|
|
}
|