While still working on Path and Form component I decided to write a bit about user authorization and especially about permissions part. So what about it? Very often in smaller projects (that don’t use any framework mechanisms for this purpose) at database level I saw user’s permissions designed like this:


There is an user and a permission table connected in an user_permission relation. To check if user has given permission simple query is required:

It could be wrapped up in some handy function like this (I use Scala and ScalikeJDBC here):

So what’s wrong with it?. Firstly it can slow down other parts of the application. If your logic requires checking permission many times (in loop for example to do something with each order line) delay can be noticeable. Of course it can be cached in some kind of user permission dictionary but that leads to code complexity increasing. Secondly and that’s more important (at least from my point of view) is adding new permission. In the code one could have permission names defined like this:

and use it in a clean and readable way like that (of course it can be simplified more):

But when new permission will be required two steps are needed to take:

  1. Adding new permission in the database
  2. Adding new variable in the Permission object

And the biggest pain here is keeping permission variables in sync with values in the database. If you used serial id (auto generated id) in the permission table and regenerated its data then you cannot be sure about consistency anymore. And developer that wants to add new permission must have database access or he has to bother database administrator.

Is there better solution? I wouldn’t be writing all this if there weren’t :) Instead of having permission and user_permission table let’s just add binary “permission” field in the user table. I usually make it 32 bytes long so it’s capable to store 256 permissions. Each byte keeps permissions – one per bit. In PostgreSql it’s defined as bytea type:

To set a proper bit in the permission array byte slot (n in setFlag function) must be calculated and then bit number of this slot determined (offset in example below). Byte slot is simply a permission value divided by 8 (or shifted right by 3 bits) and offset is 1 moved left by number of bits taken from the rest of permission dividing. To check if permission is set exactly the same operations are needed except the last one where and is used to check if bit is on or off.

packPermissions function converts array of permission numbers into array of permission bits that can be stored in the database. Below is an example of loading user and its permissions (and notifications which are handled in the same way). User class also has simplified version of hasPermission where only permission number is passed.

I hope the code above is clear to you and you’re able to figure everything out. The advantages of this approach are:

  1. Space needed to keep permissions both in the database and the code (only 32 bytes per user instead of 2048 (user_id + permission_id) * 4 bytes).
  2. Speed of loading (it’s a no cost actually).
  3. Speed of access – all permissions are loaded on user authentication, no caching required.
  4. Permissions are defined only on the code side. There is no need to synchronize with database values. If anyone wants to add new permission he simply adds a new variable in Permission object.
  5. Every coder can add new permission. There is no need to have access to the database.

And that’s it. I used this solution in my two last projects and it worked very well.

React is view only library. I really like that it doesn’t try to be a full stack solution. Thanks to that it’s easy to fill the gaps with the library you know and prefer. And routing is one of those gap. In my first react’s app I simply took a look at complementary tools page and chose directorjs for a start. It worked well although very soon I stumbled across few annoying bugs (like not calling route action on init). Workarounds exist but looks like author has no time recently to provide proper fixes. But bugs are not a problem actually. Directorjs simply doesn’t fit conceptually to react. They are two different worlds. So I looked further. The next promising library was react router component. Composable routes in a way one compose react’s comonents was exactly what I was looking for. Unfortunately I have to give up on it because it was a nodejs component and I needed simple and pure javascript solution. And it was too big for my needs. Finally I decided to create my own routing component. Of course it doesn’t have so many features – for example it lacks server side routing (I use scala and spray for that) or server side component rendering but it solves client side routing (for now without supporting html5 history). Sources can be find here: https://github.com/unodgs/react-path-router. Screenshot from github demo:


And the demo source file:

To initialize router PathInit function must be used. First argument is the main react component instance and the second is a dom node to which rendered component will be attached to. Having done that in App component we can now use <Path/>.

url is a constant attribute that must be passed to the Path to allow it properly analyze the url. It contains previous part of an url that was matched in the parent component and the “next url” that will be parsed in the context of current component (component that Path belongs to). I hope React authors allow in the future to define attributes that are automatically transferred from parent component. That would allow to avoid this boilerplate making Path declaration clearer. Anyway for now url is required to be provided by the user. Second attribute name defines part of the url that must be matched to render component pointed by render attribute. Name don’t distinguish between /clients, clients/ and clients. They are all equivalent. Name can also contains many parts: /clients/new, /clients/under/32 and so on. What’s more interesting it can contains parameters like that:

  • /client/:id
  • /group/:groupName/user/:userId

If such an url is matched, every parameter that was found is passed to the rendered component in it’s props. In the case above id would be accessed by this.props.id and the gorupName by this.props.groupName.

Path also passes one more parameter in the props of rendered component. It’s a componentUrl and it contains current component’s url. In the combination with an component it can be used to build links in a safe way (that means you won’t need to change urls everywhere if for example one of the parent component’s name will change). In the example it’s used like this:

Sometimes instead of building separate components and passing them as render attribute in many Paths it’s easier to choose what to render directly in one component.

Paths can be replaced with anything (<div> for example). It’s there only because in react you cannot return tags without common parent.

And pretty much that’s all :). I certainly will keep on working on Path component but I think it’s a good start for everyone that would like to develop something similar adjusted to his requirements. The current code is only 196 lines and should be easy to follow. See you.

When I was creating my first application in spray framework I used spray’s directive to serve static content:

As you can see the main actor combines routes from apiRoute (handles all rest requests) and staticRoute (handles static content that is located in src/main/resources/web). Static route returns index.html if no path is provided in the url and any other resource from web directory otherwise). That works pretty well but has three disadvantages:

  • If any file from web directory will change hitting F5 in the browser will return previous content until spray server is restarted. That is very annoying during developing app’s frontend when one wants to see changes immediately.
  • Restarting spray server takes time. Sure it’s relatively not that long (on my machine around 3-4 sec) but still too slow for convenient development process.
  • Returning file content to the user requires JVM involving. Whatever they told you it’s not the best way to do it. And it’s better to save CPU cycles for more important tasks.

I decided to use nginx for that task (it’s small and fast with low memory footprint http server). Here’s my configuration (it’s based on one of the gists but unfortunately I don’t remember the author):

To run nginx I created following script start_nginx.sh:

Notice the -p parameter. Without it nginx looks for provided configuration file (in my example called nginx.conf) in its default configuration directory. What’s interesting on Windows this parameter is not required. I was really surprised with this platform inconsistency.

To stop nginx you must run following command (nginx process it’s not “killable” (at least on windows)):

If everything is ok nginx will start listening on localhost:9000 and from now on it will be responsible for serving files from the web directory. I forgot to mention that I moved web folder outside resources folder to avoid including it in the final jar file.

Spray application is listening on localhost:8080 and all requests coming from localhost:9000/api/* are forwarded there. In my case I use ssl on port 9000 so I had to add following line:

This line transforms https prefix into http one. Of course you can use ssl on spray side as well but it’s unnecessary protection doubling.

And that’s all. Hope that will help someone :)

I’ve been working on my form component and here it is: https://github.com/unodgs/react-semanticui-forms. Of course this is still work in progress and it’s missing few essential parts like select tag or better form definition errors handling but I’m already using it in my apps so why not you ;). Below screenshot from example app (from github repo):


Since the last time I made following changes:

  • ref is no longer needed in Submit declaration
  • data property was changed to dataFn. Now it points to this.dataFn (that comes from FormMixin). Unfortunately there is no (known to me) way of making it unnecessary (provided implicitly by Form component). But I can live with that – I hope future versions of react will make it possible.
  • dataFn must be provided in every component (including Form)

This is the code of the form from the screenshot:

For now my form component is strictly connected with semantic ui css framework but I’m working on make it css independent. I hope you’ll find it useful. I’m aware of others similar components but none of them fits my needs. What I was missing the most was inability to freely mix form inputs with form layout. See you soon.

As you probably already know React is quite a new gamer in SPA world. In contrast to AngularJS it prefers functional approach to deal with complex and interactive UI. After creating two projects with Angular I decided to try it out with my new application. I will describe overall impression later, here I want to share my problems with form component.

My application consists of many forms like settings, user profile, registration panel etc. Each of them:

  • has input elements and submit button
  • loads initial data via ajax
  • stores entered data via ajax
  • blocks form during ajax calls
  • has nice progress indicator

I could create each of those form in classical way described in react documentation but that would be cumbersome and generated too much code. This is what I wanted to achieve:

Every kind of html input is wrapped in a react component that stores input type, its value and other necessary parameters as well as internal state if component is a little bit complex. Then Form component iterates over its children, creates validation rules for validation plugin (which in my case comes from http://semantic-ui.com) and responds to submit button. Form component is also responsible for loading and saving form data from url passed through url attribute.

I was really surprised that such a functionality is impossible to achieve in react (at least in current version). Of course that might be my fault and I would be thankful if someone shared a similar component that is working. So what is the problem? The problem is parent – children communication. Let’s take a look at a Form component (simplified version):

The most interesting part is {this.props.children}. In this property all the tags between <Form></Form> declared in PersonalDataForm are passed. One can iterate over them using React built in functions. Here’s my iteration helper (react’s foreach looks for children only one level deep in dom hierarchy):

Unfortunately (in this case) Form component is not the owner of those children. The PeronalDataForm is. That has consequences. I can’t in Form update the children properties or transfer properties passed to Form (it’s a problem because this is the preferred way of communicating with children in react). Also if I would like to modify state of children I’m forced to use undocumented internals of react (that can change in feature versions) like __realComponentInstance (if that only worked :) , the render method of child component still used previous state). What worked in the code above was validation as reading data from this.props.children was perfectly fine. What didn’t work was modifying props or state of children. I wasn’t able to load data from server and distribute it among children from within Form component.

I hope in future version communicating between children and parent will be addressed in some way or another. In the meantime I used mixins. Now PersonalDataForm looks like this:

I simply inlined all the methods that previously were placed in the Form component into the PersonalDataForm. Now PersonalDataForm is the owner of all inputs and is able to manipulate them. I also gave up on iterating over children through this.props.children. Now I iterate over this.refs. That simplifies the code but requires providing ref attribute at every input wrapper. Another disadvantage is forcing user to mix in FormMixin in every form component and unnecessary code duplication because of that. User also has to pass this.state.data (which contains ajax data) everywhere, but the final effect is very similar to what I really wanted. I will post sources of my components soon.

Hi! I’m Daniel Kos. I’m 34 years old software developer from Poland that finally decided to share his opinions with others. This blog is not going to be be only about software development but also about things like politics, hobbies and life. I hope you’ll find it interesting :)