Heads up! To view this whole video, sign in with your Courses Plus account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
We can clean up our application a bit by extracting our sign in logic in to an Express middleware. This video shows how to both create a middleware and add some helper methods to our User class.
[Code/Racer: Middleware]
0:00
In our last video, we saved the information from Facebook to our local database.
0:06
Now, let's go ahead and move that logic into a middleware.
0:11
Instead of doing if req.session.userid every single time we want to see if a user is logged in,
0:15
we can go ahead and create a middleware that will check on that for us.
0:23
We do that over here in our Application Definition.
0:27
I'm going to change the placement of these commas around very slightly
0:33
to make it easier to view.
0:36
In order to create a middleware, we do it right here inside of the express stack.
0:39
We send in the request, the response, and a callback called "next."
0:46
That will get called after the middleware has run.
0:52
What we'll do is check to see if there's a user id key inside of the session.
0:55
If there is, we'll find the user,
1:01
and we'll set a loggedIn variable inside of the request.
1:16
Then all we have to do is called req.loggedIn.
1:21
Then we call next to go back up the stack.
1:30
If there is no user, we set loggedIn to "False."
1:38
Finally, we need to do something in the event that there is no user ID in the session at all.
1:43
Now what we can do is change this down here in our "me" endpoint
1:56
to say if we're logged in.
2:05
All we have to do is render the template "me.eco" with our request user.
2:11
If not, we just redirect to the homepage.
2:24
Now we should see the exact same thing we saw last time
2:30
before we extracted it to a middleware, and we do, which is exactly what we want.
2:33
Finally, just for fun, let's go ahead and display our profile picture.
2:40
We do this inside of the instance methods.
2:45
We'll call this method avatar_url,
2:55
which is really just a link to Facebook.
3:10
Now let's display it inside of our view.
3:15
Right now we just have a link to the picture.
3:29
Let's go ahead and put it inside of an image tag.
3:31
And there we go.
3:44
In this video, we learned how to extract logic into a middleware,
3:46
thereby cleaning up our methods.
3:51
You need to sign up for Treehouse in order to download course files.
Sign up