In this 50-minute session, we'll take a fast-paced look at 10 Coldbox modules you owe it to yourself to be using in every application you develop. These modules run the gamut from security and authenticatiom to data serialization, but they all have one thing in common: they will save you hours of repetitive coding and make your life easier!
4. C F M I G R AT I O N S
• Version control for your application's database
• Changes to database schema are kept in timestamped
files that run in order
• Two methods: up and down
• Built on the QB ( Query Builder ) module, which is
database-agnostic
• Excellent for deployments across multiple tiers
5. C F M I G R AT I O N S : Q U I C K S TA R T
box install cfmigrations
box install commandbox-migrations
box migrate create AddResetTokenToUsersTable
6. C F M I G R AT I O N S
component {
function up( schema ) {
schema.alter( "users", function( table ){
table.addColumn(
table.string( "resetToken", 75 ).nullable()
);
} );
}
function down( schema ) {
schema.alter( "users", function( table ){
table.dropColumn( "resetToken" );
} );
}
}
8. C B A U T H
• Authentication wrapper for Coldbox
• Interception points and standardized conventions
• Supertype global methods to allow easy access to
authentication info in your handlers, views, and
interceptors
• Simplifies the task of rewriting the auth mechanisms
with every new application
9. C B A U T H : Q U I C K S TA R T
box install cbauth
• Specify a userServiceClass in your config/
ColdBox.cfc inside moduleSettings.cbauth.us
erServiceClass
• Implement three methods in your user service class
and one method in your user object/entity
10. C B A U T H
// Tests the credentials
public boolean function isValidCredentials(
required string username,
required string password
){
var user = retrieveUserByUsername( arguments.username );
if( !isNull( user ) ){
return encryptionService.bcryptMatches(
arguments.password,
user.getPassword()
);
} else {
return false;
}
}
// retrieves the user to test the credentials
public function retrieveUserByUsername( required string username ){
return newEntity().where( 'email', arguments.username ).first();
}
// retrieves the user by identifier
public function retrieveUserById( required string id ){
return newEntity().find( arguments.id );
}
12. C B G U A R D
• Secure routes and events to logged in users and users with
specific permissions with component and function annotations
• A simple “secured” annotation on a handler prevents
execution from all but authenticated users, while additional
annotations will check permissions
• Handlers/actions may use combinations of actions to provide
granular lockdown control
• Authentication failures may be re-routed by module and by
type of request ( e.g. AJAX vs UI )
13. C B G U A R D : Q U I C K S TA R T
box install cbguard
• Implement two methods in your existing authentication
service: hasPermission and isLoggedIn
• Configure your Coldbox.cfc with the authentication
service and any desired override events
• Add additional configuration overrides to any application
modules
14. C B G U A R D
moduleSettings = {
cbguard = {
authenticationService : “SecurityService”,
authenticationOverrideEvent : “Main.onAuthenticationFailure”,
authenticationAjaxOverrideEvent : “BaseAPIHandler.onAuthorizationFailure”,
authorizationOverrideEvent : “Main.onAuthorizationFailure”,
authorizationAjaxOverrideEvent : “BaseAPIHandler.onAuthorizationFailure”,
}
};
15. C B G U A R D
component secured{
function index( event, rc, prc ){...}
function create( event, rc, prc ) secured=“User:Create”{...}
function update( event, rc, prc ) secured=“User:Edit”{…}
...
}
17. C B VA L I D AT I O N
• An oldie but goodie.
• Works with a variety of different entities, models,
DAOs, etc
• Supertype methods to simplify validation in handlers
• Global or model-specific constraints may be specified
18. C B VA L I D AT I O N : Q U I C K S TA R T
box install cbvalidation
• Add constraints to your config, models or objects
• Add validation routines in your handler CRUD
methods
19. C B VA L I D AT I O N
this.constraints = {
firstName : { required : true },
lastName : { required : true },
password : { required : true },
email : { required : true, validator : "UniqueValidator@cborm" }
};
moduleSettings = {
cbvalidation = {
sharedConstraints = {
modifiedTime = { required: true },
modifiedBy = { required: true },
}
}
};
21. C B S T O R A G E S
• Another oldie but goodie.
• Provides you with a collection of *smart* interfaces for dealing
with common scopes and storage mechanisms ( i.e. - cookies,
cache )
• Consistent methods for dealing with all scopes - you can change
from SessionStorage to CookieStorage without refactoring code
• Cookie Storage handles automatic encryption/decryption
• Cache Storage simplifies distributed caching of authentication
and “session” persistence
22. C B S T O R A G E S : Q U I C K S TA R T
box install cbstorages
• Begin implementing usage in your auth services and
other places where storage scopes are used
23. C B S T O R A G E S
component{
property name=“cookieStorage” inject=“CookieStorage@cbstorages”;
property name=“sessionStorage” inject=“CacheStorage@cbstorages”;
}
24. C B S T O R A G E S
function setAuthorizedUser( required User user ){
//set our session storage var
sessionStorage.setVar(
name="AuthorizedUser",
value=arguments.user.getId()
);
// set a cookie which we can use for timeout evaluation
cookieStorage.setVar(
name="AuthorizedUser",
value=arguments.user.getId(),
expires = dateDiff( 'd', now(), dateAdd( 'n', now(), 20 ) )
);
return this;
}
function logout(){
if( isSessionAuthenticated() ){
sessionStorage.deleteVar( "AuthorizedUser" );
cookieStorage.deleteVar(“AuthorizedUser" );
}
}
26. B C RY P T
• Creates cryptographically strong (and slow) hashes
• Implements one-way encryption - can never be
decrypted
• Usages: Paswords, Pins, API Tokens, etc
• Given many recent, very public user/password data
thefts, you owe it to yourself to use this one…
27. B C RY P T : Q U I C K S TA R T
box install BCrypt
• Add additional configuration options and begin using
to secure your passwords
28. B C RY P T
/**
* BCrypt a string
*/
function bCrypt( string value ){
return variables.bCrypt.hashPassword( ARGUMENTS.value );
}
/**
* Verify if a string matches
*/
function bCryptMatches( string provided, string stored ){
try{
return variables.bCrypt.checkPassword( provided,stored );
} catch( "java.lang.IllegalArgumentException" e ){
return false;
}
}
30. C B M A I L S E R V I C E S
• Object-Oriented email with a consistent interface
• Data tokens in views to support dynamic data
• Built-in protocols ( CFMail, File-based, Postmark )
• Other protocols available through forge box
• Allows for global configuration of sender information
• Additional protocols are easily developed
31. C B M A I L S E R V I C E S : Q U I C K S TA R T
box install cbmailservices
• Add additional configuration options to your Coldbox
configuration
32. C B M A I L S E R V I C E S
var contactMail = mailService.newMail(
to=event.getValue( "recipient", getSetting( "mailSettings" ).to ),
from=rc.email,
subject=rc.subject
);
contactMail.setBody( renderView( view=“email/contacts/index" ) );
mailService.send( contactMail );
34. M E M E N T I F I E R
• Transforms objects into data structures
• Injects itself in to model objects and can be
configured and extended
• Exceptionally fast transformations as native functions
( no passing around of objects or collections during
transformation)
35. M E M E N T I F I E R : Q U I C K S TA R T
box install mementifier
• Add additional memento configuration to your
modules
36. M E M E N T I F I E R
this.memento = {
// An array of the properties/relationships to include by default
defaultIncludes = [
"id",
"username",
"firstName",
"lastName",
"email",
"avatar"
],
defaultExcludes = [],
neverInclude = [
"password",
"PIN"
],
defaults = {
"roles" : [],
"explicitPermissions" : []
},
mappers = {}
};
37. M E M E N T I F I E R
/api/v1/products?includes=skus.media.mediaItem,skus.inventory
39. C F F R A C TA L
• Another tool for rich transformations of data objects
• Include and exclude items
• Custom serialization, filtering and sanitization of data
( e.g. XML, JSON, Arrays, Maps, etc )
• Prevents repetitive code in your handlers
40. C F F R A C TA L : Q U I C K S TA R T
box install cffractal
• Add transformers and serialization handling in your
handlers
41. C F F R A C TA L
fractal
.builder()
.collection( users )
.withTransformer( "UserTransformer" )
.withIncludes( "roles" )
.convert();
42. C F F R A C TA L
event.paramValue( “format”, “json” );
switch( rc.format ){
case “xml”:
var serializer = “XMLSerializer@cffractal”;
break;
default:
var serializer = “ResultsMapSerializer@cffractal”;
}
44. C B S T R E A M S
• Enable functional-style operations on streams of elements ( e.g. -
collections )
• Elements in a stream are processed and passed across the
processing pipeline ( e.g. parallel transformations, while
maintaining synchronicity )
• Unlike traditional CFML functions like map(), reduce() and filter(),
which duplicate, streams maintain the integrity of the original
collection
• Chainable syntax which mimics native collection member
functions
45. C B S T R E A M S : Q U I C K S TA R T
box install cbstreams
46. C B S T R E A M S
return streamBuilder
.new( users )
.parallel()
.map( function( user ){
return {
“firstName” : user.firstName,
“lastName” : user.lastName
}
} )
.sorted( function( item1, item2 ){
return item1.lastName.compareNoCase( item2.lastName );
} )
.forEach( function( item ){
item[ “fullName” ]=item.firstName & “ “ & item.lastName;
} );
https://forgebox.io/view/cbstreams
47. T E N I N F I F T Y
• C F M I G R AT I O N S
• C B A U T H
• C B G U A R D
• C B VA L I D AT I O N
• C B S T O R A G E S
• B C RY P T
• C B M A I L S E R V I C E S
• M E M E N T I F I E R
• C F F R A C TA L
• C B S T R E A M S