File size: 6,022 Bytes
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6e89e6
 
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
c6e89e6
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
c6e89e6
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a28cd8
edcf070
 
 
 
 
 
 
 
 
 
 
c6e89e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b43786e
 
 
 
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package middleware

import (
	"errors"
	"fmt"
	"net/http"
	"strings"
	"time"

	"service-warungpos-go/config"
	"service-warungpos-go/models"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"golang.org/x/crypto/bcrypt"
)

type JWTClaims struct {
	Sub          uint   `json:"sub"`
	Role         string `json:"role"`
	CompanyID    *uint  `json:"company_id"`
	SessionToken string `json:"session_token,omitempty"`
	jwt.RegisteredClaims
}

// Security Helpers
func HashPassword(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(bytes), err
}

func VerifyPassword(password, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}

func CreateAccessToken(userID uint, role string, companyID *uint, sessionToken ...string) (string, error) {
	expiryHours := config.GlobalConfig.JWTExpiryHours
	if expiryHours == 0 {
		expiryHours = 24
	}

	claims := JWTClaims{
		Sub:       userID,
		Role:      role,
		CompanyID: companyID,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expiryHours) * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}
	if len(sessionToken) > 0 && sessionToken[0] != "" {
		claims.SessionToken = sessionToken[0]
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(config.GlobalConfig.JWTSecretKey))
}

func ParseToken(tokenString string) (*JWTClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(config.GlobalConfig.JWTSecretKey), nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
		return claims, nil
	}

	return nil, errors.New("invalid token claims")
}

// Gin Middlewares
func GetCurrentUser() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"detail": "Token otorisasi diperlukan"})
			c.Abort()
			return
		}

		parts := strings.Split(authHeader, " ")
		if len(parts) != 2 || parts[0] != "Bearer" {
			c.JSON(http.StatusUnauthorized, gin.H{"detail": "Format token otorisasi salah"})
			c.Abort()
			return
		}

		tokenString := parts[1]
		claims, err := ParseToken(tokenString)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"detail": fmt.Sprintf("Token error: %v", err)})
			c.Abort()
			return
		}

		var user models.User
		if err := config.DB.Select("id, name, email, phone, role, company_id, branch_id, is_active, created_at").First(&user, claims.Sub).Error; err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"detail": "User tidak ditemukan"})
			c.Abort()
			return
		}

		if !user.IsActive {
			c.JSON(http.StatusForbidden, gin.H{"detail": "Akun Anda dinonaktifkan. Hubungi Administrator."})
			c.Abort()
			return
		}

		// Cek single session enforcement untuk kasir
		if user.Role == "kasir" && user.CompanyID != nil {
			var company models.Company
			if err := config.DB.Select("enforce_single_session").First(&company, *user.CompanyID).Error; err == nil {
				if company.EnforceSingleSession {
					// Harus ada session_token di JWT
					if claims.SessionToken == "" {
						c.JSON(http.StatusUnauthorized, gin.H{"detail": "Sesi tidak valid, silakan login ulang.", "code": "SESSION_EXPIRED"})
						c.Abort()
						return
					}
					// Validasi session_token ke DB
					var session models.UserSession
					err := config.DB.Where(
						"user_id = ? AND session_token = ? AND expires_at > ?",
						user.ID, claims.SessionToken, time.Now(),
					).First(&session).Error
					if err != nil {
						c.JSON(http.StatusUnauthorized, gin.H{"detail": "Sesi Anda sudah tidak aktif. Perangkat lain telah login dengan akun ini.", "code": "SESSION_EXPIRED"})
						c.Abort()
						return
					}
				}
			}
		}

		// Simpan user ke context Gin
		c.Set("user", &user)
		c.Next()
	}
}

func RequireSuperAdmin() gin.HandlerFunc {
	return func(c *gin.Context) {
		userVal, exists := c.Get("user")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"detail": "Hubungan otorisasi gagal"})
			c.Abort()
			return
		}

		user := userVal.(*models.User)
		if user.Role != "super_admin" {
			c.JSON(http.StatusForbidden, gin.H{"detail": "Akses ditolak: Hanya super_admin yang memiliki izin."})
			c.Abort()
			return
		}

		c.Next()
	}
}

func RequireOwner() gin.HandlerFunc {
	return func(c *gin.Context) {
		userVal, exists := c.Get("user")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"detail": "Hubungan otorisasi gagal"})
			c.Abort()
			return
		}

		user := userVal.(*models.User)
		if user.Role != "owner" && user.Role != "super_admin" { // Super admin biasakan lolos untuk CRUD company
			c.JSON(http.StatusForbidden, gin.H{"detail": "Akses ditolak: Hanya owner yang memiliki izin."})
			c.Abort()
			return
		}

		if user.CompanyID == nil {
			c.JSON(http.StatusForbidden, gin.H{"detail": "Akses ditolak: Akun Anda tidak terikat ke perusahaan/toko manapun."})
			c.Abort()
			return
		}

		c.Next()
	}
}

func RequireTenantContext() gin.HandlerFunc {
	return func(c *gin.Context) {
		userVal, exists := c.Get("user")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"detail": "Hubungan otorisasi gagal"})
			c.Abort()
			return
		}

		user := userVal.(*models.User)
		if user.CompanyID == nil {
			c.JSON(http.StatusForbidden, gin.H{"detail": "Akses ditolak: User tidak terikat ke perusahaan/toko manapun."})
			c.Abort()
			return
		}

		c.Next()
	}
}

func RequireAuthenticated() gin.HandlerFunc {
	return func(c *gin.Context) {
		_, exists := c.Get("user")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"detail": "Hubungan otorisasi gagal"})
			c.Abort()
			return
		}
		c.Next()
	}
}