Files

51 lines
1.1 KiB
Go

package services
import (
"fmt"
"time"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"golang.org/x/crypto/bcrypt"
)
type AuthService struct {
issuer string
}
func NewAuthService(issuer string) *AuthService {
return &AuthService{issuer: issuer}
}
func (a *AuthService) HashPassword(password string) (string, error) {
hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hashed), nil
}
func (a *AuthService) ComparePassword(hash, password string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}
func (a *AuthService) NewOTP(email string) (*otp.Key, error) {
return totp.Generate(totp.GenerateOpts{
Issuer: a.issuer,
AccountName: email,
})
}
func (a *AuthService) VerifyOTP(secret, code string) bool {
return totp.Validate(code, secret)
}
func (a *AuthService) BuildOTPURI(email, secret string) string {
return fmt.Sprintf("otpauth://totp/%s:%s?secret=%s&issuer=%s", a.issuer, email, secret, a.issuer)
}
func (a *AuthService) OTPCode(secret string, at time.Time) (string, error) {
return totp.GenerateCode(secret, at)
}