Loading
Current section: Authenticated Integration 5 exercises
solution

Verifying Session Creation and User Authentication

Loading solution

Transcript

00:00 So, the first thing we want to do is get the cookie out of the response. So, our setCookieHeader from response.headers.getCookie, or setCookie. So, this is a response from the server to the client.

00:15 They're going to send setCookieHeaders for setting the session cookie. Okay, so then let's make sure that that cookie exists because this could return null. So, we'll just make sure that the setCookieHeader has been set. I'm using invariant here because invariant will throw an error if that isn't the case,

00:34 just like a regular assertion, but it also makes TypeScript happy, and so that makes it easier for the rest of our code. The truth is that the setCookieHeader, like, should absolutely be set anyway, and the error message will be just fine with using invariant.

00:51 But normally, you want to use expect because you have a little bit nicer utilities here. So, we're actually going to do something similar to this, where we're going to get the parsed cookie. Let's grab that piece, too. And we're going to make sure that the en session is set. So, that's in our session.server.

01:10 That's what we call this cookie, is en underscore session. And so, we make sure that that session has been set. So, so far, this actually works just fine. All these things are parsing properly. If I console.log the parsed cookie,

01:27 then we'll get a couple of those logs that include our en session, and here we have a redirect to. We also have en toast, and then we have one with an en session and a redirect to. So, this is working well so far, but we can go a step further,

01:43 and we can also verify that a session was created for the user in the database. So, let's await session. Oh, excuse me, that's going to be const session. Await prisma session dot find first,

02:00 and we're going to look or select the ID and where the user ID is set. Okay? So, this should be the only user ID, because we just barely made this user, so there should only be one session in the database anyway.

02:16 And we can expect this session to be truthy. And there we go. Now, we've verified that session. Not only is there a session cookie set, but also there's a session created in the database for us.

02:32 So, that is how we assert that a session was created in our authenticated requests that we're making. Well, they're actually not authenticated. They're authenticated after we come back from actually logging in with GitHub.

02:47 And so, now we can feel confident that users who are going through this process of authentication will actually be able to log in.