mikker / passwordless

🗝 Authentication for your Rails app without the icky-ness of passwords
MIT License
1.27k stars 88 forks source link

Update README.md to include CreateUsers migration example #191

Closed mzrnsh closed 9 months ago

mzrnsh commented 10 months ago

In the README, we already give a code sample that creates User model and CreateUsers migration:

$ bin/rails generate model User email

And then we display the code for User model, showing how to mark the passwordless email field:

class User < ApplicationRecord
  validates :email,
            presence: true,
            uniqueness: { case_sensitive: false },
            format: { with: URI::MailTo::EMAIL_REGEXP }

  passwordless_with :email # <-- here!
end

Since this snippet already shows the example of how to validate an email field, I believe it's useful to also feature a snippet that adds similar db-level constraint. The idea is to ensure data integrity in case records are modified outside Rails (or within Rails when validations are skipped).

Here's how I do it:

class CreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      t.string :email, null: false

      t.index 'LOWER(email)', unique: true, name: 'index_users_on_lowercase_email'

      t.timestamps
    end
  end
end

It is not exactly the same as the model validation - this doesn't validate email format. But personally, I don't care because this is only to ensure email uniqueness. If an invalid email is saved forcibly, the worst that's going to happen is that that one user won't be able to log in.

djfpaagman commented 9 months ago

Rails 7.1 added normalizing the ActiveRecord, that could also be a useful approach for this problem.

mzrnsh commented 9 months ago

That's a cool new feature. But would it not affect the only model, meaning uniqueness should still be enforced at database level?

mikker commented 9 months ago

I feel like we should maybe instead move all the user setup to a separate file, maybe a wiki page. I don't want to add too much to the README as it quickly becomes tl;dr.

On the other hand this is good information and definitely something lesser experienced devs will find helpful and appreciate.

Something like a page called "Creating a proper User class". What do you think?

mzrnsh commented 9 months ago

Good idea! Added the wiki page, and updated the README to point to it.

https://github.com/mikker/passwordless/wiki/Creating-the-user-model

mikker commented 9 months ago

I like this. Thanks!