Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sign_in custom method: how? #711

Closed
kelset opened this issue Aug 26, 2016 · 1 comment
Closed

Sign_in custom method: how? #711

kelset opened this issue Aug 26, 2016 · 1 comment

Comments

@kelset
Copy link

kelset commented Aug 26, 2016

Hi all.
I'm having trouble implementing a custom method in a controller to login an user.

In the User model I have, as requested in the doc, added include DeviseTokenAuth::Concerns::User, which should allow me to use methods like create_new_auth_token.

But, in my custom login method - which handles user which logged in via Facebook SDK in a mobile client, passing me back the access_token - :

def login_user_facebook
    @graph = Koala::Facebook::API.new(facebook_params[:access_token])
    @user_profile = @graph.get_object("me?fields=id,email")
    if @user = User.where(provider: "facebook", uid: @user_profile["id"])
        sign_in(:user, @user)
        new_auth_headers = @user.create_new_auth_token
        //posting the answer there
    else
        //posting the error there
    end
end

I get the following error: undefined method 'create_new_auth_token' for #<User::ActiveRecord_Relation:0x00000005451f50>.

Is it a bug causing this? Am I implementing the sign_in wrongly?

@kelset
Copy link
Author

kelset commented Sep 8, 2016

Ok I think I figured it out.
@lynndylanhurley feel free to close this issue, or leave it open, as it may help some people using your gem is a scoped route.

Basically, I was making two mistakes here:

  1. by using User.where I was not getting back an user, so that's why create_new_auth_token wasn't working. Needed to use User.find

  2. Since my user resource is scoped into API::V1:: in the routes, I needed to call sign_in by scoping it too.

So the working code is:

   @user = User.find_by(provider: "facebook", uid: @user_profile["id"])
    if @user != nil
        sign_in(:api_v1_user, @user)

        new_auth_header = @user.create_new_auth_token()

        # update response with the header that will be required by the next request
        response.headers.merge!(new_auth_header)

        render json: {
            user: @user,
        }, status: 200
    else
        render json: {
            error: "There is no user via facebook with this name"
        }, status: 400
    end

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants