Base64 encoded id or crude int?

I’m working on a project that uses some urls that contains int refering to the primary key of an item.

As I’m looking into user authentication, I’ve noticed that PasswordResetView from django.contrib.auth uses a base64 encoding of the user id:

Email template context:

  • email: An alias for user.email
  • user: The current User, according to the email form field. Only active users are able to reset their passwords (User.is_active is True).
  • site_name: An alias for site.name. If you don’t have the site framework installed, this will be set to the value of request.META['SERVER_NAME']. For more on sites, see The “sites” framework.
  • domain: An alias for site.domain. If you don’t have the site framework installed, this will be set to the value of request.get_host().
  • protocol: http or https
  • uid: The user’s primary key encoded in base 64.
  • token: Token to check that the reset link is valid.

I’ve done some research on the potential benefit of using base64 encoding in a url and all I could find is that it’s sometimes preferable to use text rather than binary data.

This argument seems a bit weak however, since Django can handle int in a path (e.g. path('edit-item/<str:class_name>/<int:pk>/', edit_item, name='edit-item').

So my question is: what is the point of using base64 encoding in a url?

Does it have to do with large numbers by any chance?

Any help appreciated!

Welcome @jagaudin !

There’s no requirement that the primary key of the User model be an integer. You could create a User model where the username is the primary key. In that case, you could end up with non-url-safe characters in that primary key, which would make the constructed url invalid.

By base64 encoding that primary key, you know that what you’re using will create a valid url.

1 Like

@KenWhitesell Thank you so much, that makes perfect sense now. I’ll stop scratching my head and start typing now!