owl-blogs/app/author_service.go

104 lines
2.4 KiB
Go
Raw Permalink Normal View History

2023-07-08 11:28:06 +00:00
package app
import (
"crypto/sha256"
"fmt"
"owl-blogs/app/repository"
"owl-blogs/config"
2023-07-08 11:28:06 +00:00
"owl-blogs/domain/model"
"strings"
"golang.org/x/crypto/bcrypt"
)
type AuthorService struct {
2023-07-16 19:48:39 +00:00
repo repository.AuthorRepository
siteConfigRepo repository.ConfigRepository
2023-07-08 11:28:06 +00:00
}
func NewAuthorService(repo repository.AuthorRepository, siteConfigRepo repository.ConfigRepository) *AuthorService {
2023-07-16 19:48:39 +00:00
return &AuthorService{repo: repo, siteConfigRepo: siteConfigRepo}
2023-07-08 11:28:06 +00:00
}
func hashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
return "", err
}
return string(bytes), nil
}
func (s *AuthorService) Create(name string, password string) (*model.Author, error) {
hash, err := hashPassword(password)
if err != nil {
return nil, err
}
return s.repo.Create(name, hash)
}
2023-08-12 18:39:07 +00:00
func (s *AuthorService) SetPassword(name string, password string) error {
hash, err := hashPassword(password)
if err != nil {
return err
}
author, err := s.repo.FindByName(name)
if err != nil {
return err
}
author.PasswordHash = hash
err = s.repo.Update(author)
return err
}
2023-07-08 11:28:06 +00:00
func (s *AuthorService) FindByName(name string) (*model.Author, error) {
return s.repo.FindByName(name)
}
func (s *AuthorService) Authenticate(name string, password string) bool {
author, err := s.repo.FindByName(name)
if err != nil {
return false
}
err = bcrypt.CompareHashAndPassword([]byte(author.PasswordHash), []byte(password))
return err == nil
}
func (s *AuthorService) getSecretKey() string {
siteConfig := model.SiteConfig{}
err := s.siteConfigRepo.Get(config.SITE_CONFIG, &siteConfig)
2023-07-16 19:48:39 +00:00
if err != nil {
panic(err)
}
if siteConfig.Secret == "" {
siteConfig.Secret = RandStringRunes(64)
err = s.siteConfigRepo.Update(config.SITE_CONFIG, siteConfig)
2023-07-16 19:48:39 +00:00
if err != nil {
panic(err)
}
}
return siteConfig.Secret
2023-07-08 11:28:06 +00:00
}
func (s *AuthorService) CreateToken(name string) (string, error) {
hash := sha256.New()
_, err := hash.Write([]byte(name + s.getSecretKey()))
if err != nil {
return "", err
}
return fmt.Sprintf("%s.%x", name, hash.Sum(nil)), nil
}
2023-07-13 19:55:08 +00:00
func (s *AuthorService) ValidateToken(token string) (bool, string) {
2023-07-08 11:28:06 +00:00
parts := strings.Split(token, ".")
witness := parts[len(parts)-1]
name := strings.Join(parts[:len(parts)-1], ".")
hash := sha256.New()
_, err := hash.Write([]byte(name + s.getSecretKey()))
if err != nil {
2023-07-13 19:55:08 +00:00
return false, ""
2023-07-08 11:28:06 +00:00
}
2023-07-13 19:55:08 +00:00
return fmt.Sprintf("%x", hash.Sum(nil)) == witness, name
2023-07-08 11:28:06 +00:00
}