rails-authentication-from-scratch icon indicating copy to clipboard operation
rails-authentication-from-scratch copied to clipboard

Why is the ||= removed? current_user method

Open E36lewis opened this issue 2 years ago • 2 comments

I thought the whole point of having this operator was to have the user memoized? With it removed yes the current user is cached into the db, but does that not add to response time? Are there pitfalls in keeping the Current.user ||= instead of the updated: Current.user =.

Looking for clarification, more detail on this. Thanks.

E36lewis avatar Apr 15 '23 21:04 E36lewis

Excellent question! I think the issue was that I was getting failing tests when I introduced af768c2, and just assumed memoization was the culprit. However, that assumption might be incorrect. I think I'll need to investigate if the current_user test helper needs to be updated.

https://github.com/stevepolitodesign/rails-authentication-from-scratch/blob/0416b6f2f65298ec41472d30c2b90ebf7192734d/test/test_helper.rb#L13-L19

stevepolitodesign avatar Apr 19 '23 11:04 stevepolitodesign

I believe the tests are failing because using ||= inside current_user will not re-query the ActiveSession table. It will use the cached value inside Current.user. Therefore if a user deletes their current session current_user still returns a valid user indicating the session is still valid.

https://github.com/stevepolitodesign/rails-authentication-from-scratch/blob/0e9d1de6b214958df37b362786413c9ed5a289b5/app/controllers/active_sessions_controller.rb#L4-L16

passbe avatar Mar 12 '24 06:03 passbe