Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: MongoDB edition
Lecture: Fixing the login
0:00 Now, let's go try to log in.
0:02 Actually, before we even try that
0:03 let me do a quick cleanup here.
0:05 Remember we put those users in
0:07 and they don't have things like
0:10 hashed passwords and so on
0:11 and that's going to cause some trouble.
0:13 So let me just go over here
0:14 and we can just say remove all documents.
0:17 The only way we really want users
0:18 in here is they go and register.
0:20 So let's try that.
0:21 Let's go over here and try to register.
0:25 We'll put our name, our email, our password
0:28 and then I guess we still have this around here.
0:29 I'm not really 57, but whatever.
0:32 Oh, that's a problem. What's going on here?
0:35 So, apparently zero is not a valid ObjectId.
0:38 Where is this error happening?
0:40 Way, way down here
0:45 on this query right there.
0:47 So when we're trying to find the user
0:48 we're passing in an integer
0:50 and it's expecting an ObjectId.
0:52 Well, why is that? What is happening here?
0:56 It turns out, it has to do
0:57 with the fact that we're using a cookie
0:59 for the user_id, remember that?
1:01 What we're putting in here is an integer
1:03 and what it needs to be is an ObjectId.
1:05 So I'll say bson comes from a Mongo
1:07 PyMongo, technically.
1:09 We want an ObjectId like that.
1:11 This is what we want this to return
1:13 and it doesn't yet, but it's going to in a moment.
1:18 One of these, I'm going to come down here
1:20 and the part that's problematic is this.
1:23 So let's just say try to do this else.
1:31 Return. And then we have it.
1:32 That should actually do it.
1:34 So we should be able to come over here
1:36 rerun our app.
1:38 Here notice the login actually worked
1:40 and it tried to redirect us to our account
1:42 and now, guess what, our account works.
1:45 We logged in, this is great.
1:47 Let's log out and just show that we can login again.
1:49 We went through the register before.
1:53 But look; login, logout. Works beautifully.
1:56 So we had to make that little tiny change
1:58 because we're now using a bson.ObjectId
2:01 as the primary key. We want to store that
2:04 instead of just using an integer before.
2:07 Okay, so this little minor change
2:09 was just all we needed to do to
2:11 sort of sync up with the data types
2:13 and I guess we could have gotten around it
2:15 but it's really better to leverage MongoDB's
2:17 ObjectId for the ObjectId's if you don't care.
2:23 But if they're auto generated, go with this.
2:25 This is nice.