Now that we’re in the latter half of the semester, we’re dealing less with the boilerplate CRUD of web applications and more on the logic that powers the interesting parts of the app: the models. To get us to think about this, Jeff had us do an exercise called domain modeling. Creating a domain model involves sketching out on paper or a whiteboard how the different models in your app connect to one another. It’s actually incredibly helpful to draw out a visual representation of how models are related without wading into the code. It allows for a high level perspective of the app that can make you realize the fundamental flaws in it’s design.
In order to add certain features to an app, like user authentication, you should first understand the concept of cookies. The purpose of authenticating a user is to allow access to information that’s from the information that non-users see. So, you need some way of seeing if a user is currently logged in. To check attributes in an app, you would normally use something like the
params</code> hash, but we can’t use it in this case. This is because the
params hash only lasts for one request-response cycle, or as long as the current controller action is being called. Going from
/users/7 empties and changes the params hash depending on the logic in your controller action. With this in mind, you need to find a way to make the notion of being “logged in” more persistent than the
params hash. Databases are suppposed to have persistent storage, are they not? Couldn’t you just have an attribute in the
User model that keeps track of whether a user is logged in or not? It may be techically possible, but you actually want something less permanent. This is where cookies come in. Cookies act as a sort of database, but only exist on the client-side. This means that they only exist in the browser. Cookies only last as long as you do not delete them from your browser cache or until they expire, which is usually two weeks. This is why you can stay signed in to certain websites for extended periods of time without re-rentering your password.
To store cookies in Rails, you can use the
cookies hash, but in the case of user authentication, you would want to use something called the
session hash behaves exactly like the
cookies hash, except sessions are hidden in the web inspector.
In class next week, we’re going more in depth with user authentication and how to make your app secure.