1 00:00:00,000 --> 00:00:06,000 [Code/Racer: Middleware] 2 00:00:06,000 --> 00:00:11,000 In our last video, we saved the information from Facebook to our local database. 3 00:00:11,000 --> 00:00:15,000 Now, let's go ahead and move that logic into a middleware. 4 00:00:15,000 --> 00:00:23,000 Instead of doing if req.session.userid every single time we want to see if a user is logged in, 5 00:00:23,000 --> 00:00:27,000 we can go ahead and create a middleware that will check on that for us. 6 00:00:27,000 --> 00:00:33,000 We do that over here in our Application Definition. 7 00:00:33,000 --> 00:00:36,000 I'm going to change the placement of these commas around very slightly 8 00:00:36,000 --> 00:00:39,000 to make it easier to view. 9 00:00:39,000 --> 00:00:46,000 In order to create a middleware, we do it right here inside of the express stack. 10 00:00:46,000 --> 00:00:52,000 We send in the request, the response, and a callback called "next." 11 00:00:52,000 --> 00:00:55,000 That will get called after the middleware has run. 12 00:00:55,000 --> 00:01:01,000 What we'll do is check to see if there's a user id key inside of the session. 13 00:01:01,000 --> 00:01:05,000 If there is, we'll find the user, 14 00:01:16,000 --> 00:01:21,000 and we'll set a loggedIn variable inside of the request. 15 00:01:21,000 --> 00:01:25,000 Then all we have to do is called req.loggedIn. 16 00:01:30,000 --> 00:01:33,000 Then we call next to go back up the stack. 17 00:01:38,000 --> 00:01:43,000 If there is no user, we set loggedIn to "False." 18 00:01:43,000 --> 00:01:49,000 Finally, we need to do something in the event that there is no user ID in the session at all. 19 00:01:56,000 --> 00:02:05,000 Now what we can do is change this down here in our "me" endpoint 20 00:02:05,000 --> 00:02:11,000 to say if we're logged in. 21 00:02:11,000 --> 00:02:21,000 All we have to do is render the template "me.eco" with our request user. 22 00:02:24,000 --> 00:02:27,000 If not, we just redirect to the homepage. 23 00:02:30,000 --> 00:02:33,000 Now we should see the exact same thing we saw last time 24 00:02:33,000 --> 00:02:40,000 before we extracted it to a middleware, and we do, which is exactly what we want. 25 00:02:40,000 --> 00:02:45,000 Finally, just for fun, let's go ahead and display our profile picture. 26 00:02:45,000 --> 00:02:49,000 We do this inside of the instance methods. 27 00:02:55,000 --> 00:02:58,000 We'll call this method avatar_url, 28 00:03:10,000 --> 00:03:15,000 which is really just a link to Facebook. 29 00:03:15,000 --> 00:03:18,000 Now let's display it inside of our view. 30 00:03:29,000 --> 00:03:31,000 Right now we just have a link to the picture. 31 00:03:31,000 --> 00:03:34,000 Let's go ahead and put it inside of an image tag. 32 00:03:44,000 --> 00:03:46,000 And there we go. 33 00:03:46,000 --> 00:03:51,000 In this video, we learned how to extract logic into a middleware, 34 00:03:51,000 --> 00:03:54,000 thereby cleaning up our methods.