devise_invitable icon indicating copy to clipboard operation
devise_invitable copied to clipboard

Issue related to find_by_invitation_token

Open avinash-khushu opened this issue 7 years ago • 4 comments

I am having an issue related to find_by_invitation_token. When using find_by_invitation_token with 1st param as token and second param as true, it is generating new token. so the invitation is failing.

What is the solution for this now ? Note - I cannot change the versions as it is driven by client.

gem 'devise', '~> 3.2.4' gem 'devise_invitable', '~> 1.3.5'

avinash-khushu avatar Nov 02 '17 11:11 avinash-khushu

find_by_invitation_token never generates new token it looks for resource with invitation token provided in first argument. if second argument is false, and resource is not found, it returns a new record, with invitation token set, and error in invitation token column. if second argument is true, only return record if is found, so you should get record with no error (errors.empty?)

However, invitation token in link is the raw token generated by devise invitable, and invitation token in database is the encrypted token (a hash generated from raw token).

scambra avatar Nov 02 '17 14:11 scambra

This confused me too at first. I thought I encountered the same problem as @avinash-khushu until I realized that Devise::Models::Invitable#generate_invitation_token creates a token which is sent in the email link (@raw_invitation_token) and a hash digest of that token which gets assigned to invitation_token and stored in the database. Once @raw_invitation_token is sent out in the email it gets discarded (or so I think) and when the invited user clicks the link the raw token submitted is rehashed for lookup against the invitation_token column. I guess that makes it harder to impersonate an invited user, like why we encrypt passwords.

@avinash-khushu I'm not sure what is causing your invitation to fail, but it could be that you are applying the find_by_invitation_token method incorrectly.

wakproductions avatar Dec 07 '17 03:12 wakproductions

I have a similar issue. When I call find_by_invitation_token() with the token from the email, it queries my database for the hash digest of that token, but the result is nil. When I manually look up the invitation_token for the resource is in fact different. How can the database value differ ?

JeremyLopez avatar Nov 06 '18 20:11 JeremyLopez

It could differ if new token is generated after email is sent, because only hash for last token is saved in database

scambra avatar Nov 07 '18 12:11 scambra