47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/go-chi/jwtauth/v5"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func (s *Service) VerifyUser(ctx context.Context, input VerifyUserInput) (VerifyUserResult, error) {
|
|
u, err := s.queries.GetUserByUsername(ctx, input.Username)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return VerifyUserResult{}, notFound("user does not exist or password is wrong")
|
|
}
|
|
return VerifyUserResult{}, internalError("auth error", nil)
|
|
}
|
|
|
|
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(input.Password)); err != nil {
|
|
return VerifyUserResult{}, notFound("user does not exist or password is wrong")
|
|
}
|
|
|
|
// jwt
|
|
claims := make(map[string]any)
|
|
claims["userid"] = u.ID.String()
|
|
claims["username"] = u.Username
|
|
claims["role"] = u.Role
|
|
claims["display_name"] = u.DisplayName
|
|
claims["account_status"] = u.AccountStatus
|
|
jwtauth.SetExpiryIn(claims, 24*time.Hour)
|
|
jwtauth.SetIssuedNow(claims)
|
|
|
|
_, token, _ := s.config.JWTAuth.Encode(claims)
|
|
|
|
return VerifyUserResult{
|
|
Token: token,
|
|
UserId: u.ID.String(),
|
|
UserName: u.Username,
|
|
DisplayName: u.DisplayName,
|
|
Role: u.Role,
|
|
AccountStatus: u.AccountStatus,
|
|
}, nil
|
|
}
|