Skip to content

Commit a068895

Browse files
committed
Add a secureSameUser method to throw when passed a different user
Just as `sameUser` returns `false` when the passed in user is different than the logged in user, `secureSameUser` will throw when the passed in user is different than the logged in user.
1 parent b0c9c80 commit a068895

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

models/CBSecurity.cfc

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,9 +258,33 @@ component singleton accessors="true" {
258258
}
259259
if ( results ) {
260260
throw( type = "NotAuthorized", message = arguments.message );
261+
}
262+
return this;
263+
}
264+
265+
/**
266+
* Verifies that the passed in user object must be the same as the authenticated user.
267+
* Equality is done by evaluating the `getid()` method on both objects.
268+
* If the equality check fails, a `NotAuthorized` exception is thrown.
269+
*
270+
* @throws NoUserLoggedIn
271+
* @throws NotAuthorized
272+
*
273+
* @user The user to test for equality
274+
* @message The error message to throw in the exception
275+
*/
276+
CBSecurity function secureSameUser(
277+
required user,
278+
message = variables.DEFAULT_ERROR_MESSAGE
279+
){
280+
if ( !sameUser( arguments.user ) ) {
281+
throw(
282+
type = "NotAuthorized",
283+
message = arguments.message
284+
);
261285
}
262286
return this;
263-
}
287+
}
264288

265289
/**
266290
* Alias proxy if somebody is coming from cbguard, proxies to the secure() method

test-harness/tests/specs/unit/CBSecurityTest.cfc

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,22 @@ component extends="coldbox.system.testing.BaseModelTest" model="cbsecurity.model
301301
cbsecurity.secureWhen( function( user ){ return false; } );
302302
});
303303
});
304+
describe( "secureSameUser() method", function(){
305+
it( "can secure if the logged in user is not the user passed", function(){
306+
mockUser.$( "getId", 1 );
307+
var testUser = createStub().$( "getId", 2 );
308+
309+
expect( function(){
310+
cbsecurity.secureSameUser( testUser );
311+
}).toThrow( "NotAuthorized" );
312+
});
313+
314+
it( "can allow if the logged in user is the user passed", function(){
315+
mockUser.$( "getId", 1 );
316+
var testUser = createStub().$( "getId", 1 );
317+
cbsecurity.secureSameUser( testUser );
318+
});
319+
});
304320
});
305321

306322
});

0 commit comments

Comments
 (0)