feat: login and logout
This commit is contained in:
@@ -4,4 +4,5 @@ type User struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Username string `gorm:"unique" json:"username"`
|
||||
Password string `json:"-"`
|
||||
Token string `json:"-"`
|
||||
}
|
||||
|
||||
@@ -48,3 +48,17 @@ func (ur *UserRepository) FindByUsername(username string) (*User, error) {
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (ur *UserRepository) Login(id uint, token string) error {
|
||||
if err := ur.db.Model(&User{}).Where("id = ?", id).Update("token", token).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ur *UserRepository) Logout(id uint, token string) error {
|
||||
if err := ur.db.Model(&User{}).Where("id = ?", id).Update("token", "").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
package account
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
import (
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/auth"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
userRepository *UserRepository
|
||||
@@ -62,3 +67,34 @@ func (us *UserService) FindByUsername(username string) (*User, error) {
|
||||
return user, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (us *UserService) Login(username, password string) (string, error) {
|
||||
user, err := us.FindByUsername(username)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// generate token
|
||||
token, err := auth.GenerateToken(user.ID, user.Username)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := us.userRepository.Login(user.ID, token); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (us *UserService) Logout(userID uint) error {
|
||||
user, err := us.FindByID(userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if user.Token == "" {
|
||||
return errors.New("user already logged out")
|
||||
}
|
||||
return us.userRepository.Logout(user.ID, user.Token)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user