@@ -109,32 +109,29 @@ package main
109109
110110import (
111111 " context"
112- " database/sql"
113112 " fmt"
114113 " log"
115114
116115 " github.com/casbin/casbin/v3"
117- _ " github.com/lib/pq"
118116)
119117
120118type UserService struct {
121- db *sql.DB
122119 enforcer *casbin.TransactionalEnforcer
123120}
124121
125122// UpdateUserRole atomically updates user role in database and Casbin
126123func (s *UserService ) UpdateUserRole (ctx context .Context , userId , oldRole , newRole string ) error {
127124 return s.enforcer .WithTransaction (ctx, func (tx *casbin.Transaction ) error {
128- // Get database transaction from adapter
129- // (This requires your adapter to provide access to the DB transaction)
125+ // Note: In a real application, you would access the database transaction
126+ // from your adapter to ensure both database and Casbin operations
127+ // happen in the same transaction. See the GORM example below.
130128
131- // Update user role in business database
132- _ , err := s.db .ExecContext (ctx,
133- " UPDATE users SET role = $1 WHERE id = $2" ,
134- newRole, userId)
135- if err != nil {
136- return fmt.Errorf (" failed to update user role: % w" , err)
137- }
129+ // Example (pseudo-code):
130+ // dbTx := tx.GetDatabaseTransaction() // Adapter-specific
131+ // _, err := dbTx.Exec("UPDATE users SET role = $1 WHERE id = $2", newRole, userId)
132+ // if err != nil {
133+ // return fmt.Errorf("failed to update user role: %w", err)
134+ // }
138135
139136 // Remove old role mapping in Casbin
140137 if oldRole != " " {
@@ -155,13 +152,13 @@ func (s *UserService) UpdateUserRole(ctx context.Context, userId, oldRole, newRo
155152// CreateUser atomically creates a user with initial permissions
156153func (s *UserService ) CreateUser (ctx context .Context , userId , role string , permissions [][]string ) error {
157154 return s.enforcer .WithTransaction (ctx, func (tx *casbin.Transaction ) error {
158- // Insert user into database
159- _ , err := s. db . ExecContext (ctx,
160- " INSERT INTO users (id, role) VALUES ($1, $2) " ,
161- userId, role)
162- if err != nil {
163- return fmt.Errorf (" failed to create user: % w" , err)
164- }
155+ // Note: In a real application, you would insert into your database here
156+ // Example (pseudo-code):
157+ // dbTx := tx.GetDatabaseTransaction() // Adapter-specific
158+ // _, err := dbTx.Exec("INSERT INTO users (id, role) VALUES ($1, $2)", userId, role)
159+ // if err != nil {
160+ // return fmt.Errorf("failed to create user: %w", err)
161+ // }
165162
166163 // Assign role in Casbin
167164 if _ , err := tx.AddGroupingPolicy (userId, role); err != nil {
0 commit comments