Spaces:
Runtime error
Runtime error
Delete services
Browse filesFiles changed (5)
- services/authentication_service.goDeleted-71
- services/jwt_service.goDeleted-80
- services/register_service.goDeleted-46
- services/service.goDeleted-42
- services/user_profile_service.goDeleted-97
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071package services
import (
"errors"
"pweb-api.abdanhafidz.com/models"
"pweb-api.abdanhafidz.com/repositories"
)
type AuthenticationService struct {
Service[models.Account, models.AuthenticatedUser]
}
func (s *AuthenticationService) Authenticate() {
accountData := repositories.GetAccountbyEmail(s.Constructor.Email)
if accountData.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "there is no account with given credentials!"
return
}
if VerifyPassword(accountData.Result.Password, s.Constructor.Password) != nil {
s.Exception.Unauthorized = true
s.Exception.Message = "incorrect password!"
return
}
token, err_tok := GenerateToken(&accountData.Result)
if err_tok != nil {
s.Error = errors.Join(s.Error, err_tok)
return
}
accountData.Result.Password = "SECRET"
s.Result = models.AuthenticatedUser{
Account: accountData.Result,
Token: token,
}
s.Error = accountData.RowsError
}
func (s *AuthenticationService) Update(oldPassword string, newPassword string) {
if len(newPassword) < 8 {
s.Exception.InvalidPasswordLength = true
s.Exception.Message = "Password must have at least 8 characters!"
return
}
accountData := repositories.GetAccountById(s.Constructor.Id)
if accountData.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "there is no account with given credentials!"
return
}
if VerifyPassword(accountData.Result.Password, oldPassword) != nil {
s.Exception.Unauthorized = true
s.Exception.Message = "incorrect old password!"
return
}
hashed_password, _ := HashPassword(newPassword)
accountData.Result.Password = hashed_password
changePassword := repositories.UpdateAccount(accountData.Result)
changePassword.Result.Password = "SECRET"
s.Result = models.AuthenticatedUser{
Account: changePassword.Result,
}
s.Error = changePassword.RowsError
}
// LoginHandler handles user login1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980package services
import (
"errors"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"pweb-api.abdanhafidz.com/config"
"pweb-api.abdanhafidz.com/models"
)
var salt = config.Salt
var secretKey = []byte(salt)
func GenerateToken(user *models.Account) (string, error) {
claims := models.CustomClaims{
UserID: user.Id,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)), // Token berlaku 24 jam
IssuedAt: jwt.NewNumericDate(time.Now()),
Issuer: "apabdanhafidz.com",
},
}
// Buat token dengan metode signing
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(secretKey)
}
func ExtractBearerToken(authHeader string) (string, error) {
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
return "", errors.New("invalid authorization header format")
}
return parts[1], nil
}
func VerifyToken(bearerToken string) (uint, string, error) {
// fmt.Println("bearerToken :", bearerToken)
tokenData, err := ExtractBearerToken(bearerToken)
if err != nil {
return 0, "invalid-token", err
} else {
// fmt.Println("Extracted Token:", tokenData)
}
token, err := jwt.ParseWithClaims(tokenData, &models.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return secretKey, nil
})
if err != nil {
return 0, "invalid-token", err
}
// Extract the claims
claims, ok := token.Claims.(*models.CustomClaims)
if !ok || !token.Valid {
return 0, "invalid-token", err
}
if claims.ExpiresAt != nil && claims.ExpiresAt.Time.Before(time.Now()) {
return 0, "expired", err
}
return claims.UserID, "valid", err
}
func VerifyPassword(hashedPassword, password string) error {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
if err != nil {
return errors.New("invalid password")
}
return nil
}
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546package services
import (
"errors"
uuid "github.com/satori/go.uuid"
"gorm.io/gorm"
"pweb-api.abdanhafidz.com/models"
"pweb-api.abdanhafidz.com/repositories"
)
type RegisterService struct {
Service[models.Account, models.Account]
}
func (s *RegisterService) Create() {
if len(s.Constructor.Password) < 8 {
s.Exception.InvalidPasswordLength = true
s.Exception.Message = "Password must have at least 8 characters!"
return
}
hashed_password, err_hash := HashPassword(s.Constructor.Password)
s.Error = err_hash
s.Constructor.Password = hashed_password
s.Constructor.UUID = uuid.NewV4()
accountCreated := repositories.CreateAccount(s.Constructor)
if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {
s.Exception.DataDuplicate = true
s.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!"
return
} else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) {
s.Exception.BadRequest = true
s.Exception.Message = "Bad request!"
return
}
userProfile := UserProfileService{}
userProfile.Constructor.AccountId = accountCreated.Result.Id
userProfile.Create()
if userProfile.Error != nil {
s.Error = userProfile.Error
return
}
s.Error = accountCreated.RowsError
s.Result = accountCreated.Result
s.Result.Password = "SECRET"
}123456789101112131415161718192021222324252627282930313233343536373839404142package services
import (
"time"
"pweb-api.abdanhafidz.com/models"
)
type (
Services interface {
Retrieve()
Update()
Create()
Delete()
Validate()
Authenticate()
Authorize()
}
IService interface {
Implements()
}
Service[TConstructor any, TResult any] struct {
Constructor TConstructor
Result TResult
Exception models.Exception
Error error
}
)
func Construct[TConstructor any, TResult any](constructor ...TConstructor) *Service[TConstructor, TResult] {
if len(constructor) == 1 {
return &Service[TConstructor, TResult]{}
}
return &Service[TConstructor, TResult]{
Constructor: constructor[0],
}
}
func CalculateDueTime(duration time.Duration) time.Time {
return time.Now().Add(duration)
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697package services
import (
"regexp"
"strings"
"pweb-api.abdanhafidz.com/models"
"pweb-api.abdanhafidz.com/repositories"
)
type UserProfileService struct {
Service[models.AccountDetails, models.UserProfileResponse]
}
// SanitizePhoneNumber membersihkan dan menormalkan nomor telepon ke format +62
func SanitizePhoneNumber(input string) string {
// Hilangkan semua spasi dan strip
input = strings.ReplaceAll(input, " ", "")
input = strings.ReplaceAll(input, "-", "")
input = strings.ReplaceAll(input, "(", "")
input = strings.ReplaceAll(input, ")", "")
// Hilangkan semua karakter non-digit kecuali +
re := regexp.MustCompile(`[^0-9\+]`)
input = re.ReplaceAllString(input, "")
// Handle nomor diawali 0 (contoh: 0812...) menjadi +62812...
if strings.HasPrefix(input, "0") {
input = "+62" + input[1:]
}
// Handle jika diawali dengan 62 tanpa + (contoh: 62812...)
if strings.HasPrefix(input, "62") && !strings.HasPrefix(input, "+62") {
input = "+" + input
}
// Handle jika tidak ada awalan +62 sama sekali (contoh: 8123456789)
if !strings.HasPrefix(input, "+62") {
if strings.HasPrefix(input, "8") {
input = "+62" + input
}
}
return input
}
func (s *UserProfileService) Create() {
userProfile := repositories.CreateAccountDetails(s.Constructor)
s.Error = userProfile.RowsError
if userProfile.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "There is no account with given credentials!"
return
}
s.Result = models.UserProfileResponse{
Account: repositories.GetAccountById(s.Constructor.AccountId).Result,
Details: userProfile.Result,
}
}
func (s *UserProfileService) Retrieve() {
userProfile := repositories.GetDetailAccountById(s.Constructor.AccountId)
s.Error = userProfile.RowsError
if userProfile.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "There is no account with given credentials!"
return
}
s.Result = models.UserProfileResponse{
Account: repositories.GetAccountById(s.Constructor.AccountId).Result,
Details: userProfile.Result,
}
s.Result.Account.Password = "SECRET"
}
func (s *UserProfileService) Update() {
if s.Constructor.PhoneNumber != nil {
phoneNumber := *s.Constructor.PhoneNumber
*s.Constructor.PhoneNumber = SanitizePhoneNumber(phoneNumber)
}
userProfile := repositories.UpdateAccountDetails(s.Constructor)
s.Error = userProfile.RowsError
if userProfile.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "There is no account with given credentials!"
return
}
account := repositories.GetAccountById(s.Constructor.AccountId)
account.Result.IsDetailCompleted = (userProfile.Result.InitialName != "" &&
userProfile.Result.FullName != nil &&
userProfile.Result.PhoneNumber != nil &&
userProfile.Result.University != nil)
repositories.UpdateAccount(account.Result)
s.Result = models.UserProfileResponse{
Account: account.Result,
Details: userProfile.Result,
}
s.Result.Account.Password = "SECRET"
}services/authentication_service.goDeleted-71
services/jwt_service.goDeleted-80
services/register_service.goDeleted-46
services/service.goDeleted-42
services/user_profile_service.goDeleted-97