Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

ITB2019 10 in 50: Ten Coldbox Modules You Should be Using in Every App - Jon Clausen


Published on

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!

Published in: Technology
  • Be the first to comment

  • Be the first to like this

ITB2019 10 in 50: Ten Coldbox Modules You Should be Using in Every App - Jon Clausen

  1. 1. T E N I N F I F T Y T E N C O L D B O X M O D U L E S 
 Y O U S H O U L D B E U S I N G 
  2. 2. Me: Jon Clausen Senior Software Developer,
 Ortus Solutions Grand Rapids, Michigan
  3. 3. C F M I G R AT I O N S
  4. 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. 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. 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" ); } ); } }
  7. 7. C B A U T H
  8. 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. 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 erServiceClass • Implement three methods in your user service class and one method in your user object/entity
  10. 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( 
 ); } 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( ); }
  11. 11. C B G U A R D
  12. 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. 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. 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. 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”{…} ...
  16. 16. C B VA L I D AT I O N
  17. 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. 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. 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 }, } } };
  20. 20. C B S T O R A G E S
  21. 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. 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. 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. 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" ); } }
  25. 25. B C RY P T
  26. 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. 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. 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;     } }
  29. 29. C B M A I L S E R V I C E S
  30. 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. 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. 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 ),, subject=rc.subject ); contactMail.setBody( renderView( view=“email/contacts/index" ) ); mailService.send( contactMail );
  33. 33. M E M E N T I F I E R
  34. 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. 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. 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. 37. M E M E N T I F I E R /api/v1/products?,skus.inventory
  38. 38. C F F R A C TA L
  39. 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. 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. 41. C F F R A C TA L fractal .builder() .collection( users ) .withTransformer( "UserTransformer" ) .withIncludes( "roles" ) .convert();
  42. 42. C F F R A C TA L event.paramValue( “format”, “json” );
 switch( rc.format ){
 case “xml”:
 var serializer = “XMLSerializer@cffractal”;
 var serializer = “ResultsMapSerializer@cffractal”;
  43. 43. C B S T R E A M S
  44. 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. 45. C B S T R E A M S : Q U I C K S TA R T box install cbstreams
  46. 46. C B S T R E A M S return streamBuilder .new( users )
 .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; } );
  47. 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
  48. 48. Q & A