mv logic into userService

allows reusing it in the views more easy
This commit is contained in:
2025-01-05 22:38:48 +01:00
parent 4e48e87f6c
commit 273918f542
2 changed files with 73 additions and 51 deletions

68
services/userService.go Normal file
View File

@@ -0,0 +1,68 @@
package services
import(
"os"
"time"
"golang.org/x/crypto/bcrypt"
"github.com/golang-jwt/jwt/v5"
"example.com/gin/test/models"
"example.com/gin/test/repositories"
)
var(
Users UserService = UserService{}
)
type UserService struct {}
func (u *UserService) Register(name string, email string, password string) (models.User, error) {
//hash pw
hash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
return models.User{}, err
}
user := models.User{Name: name, Email: email, Password: string(hash)}
_, err = repositories.Users.Create(user)
if err != nil {
return models.User{}, err
}
return user, nil
}
//return jwt tokenstring on success
func (u *UserService) Login(email string, password string) (string, error) {
//lookup requested user
user, err := repositories.Users.GetByEmail(email)
if err != nil {
return "", err
}
// compare sent with saved pass
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err != nil {
return "", err
}
//generate jwt token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": user.ID,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(os.Getenv("SECRET")))
if err != nil {
return "", err
}
return tokenString, nil
}