Added user authentication
This commit is contained in:
parent
d7e7af5a10
commit
cb54057305
40 changed files with 710 additions and 218 deletions
76
services/users/service.go
Normal file
76
services/users/service.go
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
package users
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"lmika.dev/lmika/hugo-cms/models"
|
||||
"lmika.dev/lmika/hugo-cms/providers/db"
|
||||
"log"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
dbp *db.DB
|
||||
}
|
||||
|
||||
func NewService(dbp *db.DB) *Service {
|
||||
return &Service{
|
||||
dbp: dbp,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) AddUser(ctx context.Context, newUser NewUser) (models.User, error) {
|
||||
passwd, err := bcrypt.GenerateFromPassword([]byte(newUser.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return models.User{}, err
|
||||
}
|
||||
|
||||
user := models.User{
|
||||
Email: newUser.Email,
|
||||
PasswordHash: base64.StdEncoding.EncodeToString(passwd),
|
||||
}
|
||||
if err := s.dbp.AddUser(ctx, &user); err != nil {
|
||||
return models.User{}, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetUserByID(ctx context.Context, id int64) (models.User, error) {
|
||||
return s.dbp.GetUserByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Service) VerifyLogin(ctx context.Context, email string, password string) (models.User, error) {
|
||||
user, err := s.dbp.GetUserByEmail(ctx, email)
|
||||
if err != nil {
|
||||
log.Println("User not found")
|
||||
return models.User{}, err
|
||||
}
|
||||
|
||||
pwdHash, err := base64.StdEncoding.DecodeString(user.PasswordHash)
|
||||
if err != nil {
|
||||
return models.User{}, err
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword(pwdHash, []byte(password))
|
||||
if err != nil {
|
||||
log.Println("Password incorrect")
|
||||
return models.User{}, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetUserByEmail(ctx context.Context, email string) (models.User, error) {
|
||||
user, err := s.dbp.GetUserByEmail(ctx, email)
|
||||
if err != nil {
|
||||
return models.User{}, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type NewUser struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue