Swizec Teller - a geek with a hatswizec.com

    Force users to add a facebook login with devise omniauth

    You've set up rails with devise and omniauth. Users are signing up with facebook or twitter or email&password or something completely different. Everything is going great.

    Now you want to force some users to add a facebook login to their account. Maybe you just want to see if their name and avatar match what they've set up in your service to make sure they really are who they say they are. Whatever.

    It seems like you might need to add a custom Devise strategy. You start googling. Doesn't seem like a lot of work, you just extend Authorizable and override the authorize! function and then ... do something. Seems you'll have to mostly override how authorization works. Will that play well with omniauthable?

    But that only solves the problem of forcing Facebook on authorization. Who's going to check the conditions on every page load and sign the user out?

    You set up a filter. Put it in application_controller and it's just a big mess. You're still not sure how to tie everything together and the clusterfuck of code is growing and growing.

    https://twitter.com/Swizec/statuses/347024137086173185

    Force FB with just 19 sloc

    There's a better way!

    I stumbled on this solution almost by accident after ending up on an obscure API doc page on my gazillionth google search. Turns out you can force a user to sign up with facebook in just under 19 lines of code.

    We have to extend how models behave, not create a new Devise strategy. The function we're looking to override is active_for_authentication?.

    This function is called on every page load when a user is signed in and checks that they're still active. If it returns false the user will be signed out and asked to login before continuing. They won't be let through until the function returns true.

    Elegant!

    All you have to do is put something like this in your app/classes directory.

    module Facebookable
    extend ActiveSupport::Concern
    def needs_facebook?
    needs_facebook && services.where("provider = 'Facebook'").count < 1
    end
    def should_flag?
    condition # get a score somehow
    if condition
    self.needs_facebook = true
    self.save!
    end
    end
    def active_for_authentication?
    super && !needs_facebook? && !should_flag?()
    end
    def inactive_message
    needs_facebook? ? "Please sign in with Facebook." : super
    end
    end

    And that's essentially it. Add a boolean needs_facebook field to your user model and add :facebookable to the strategies list and you're done. Everything works.

    Facebookable will automatically take care of checking whether a user has facebook connected and kick them out if they don't but should. On every page load it will also check whatever condition you've set and flag the user.

    It took me four days to come up with those 19 lines of code because nobody's written a blogpost about how to do this properly. Now someone has.

    PS: testing this works the same as testing any other model methods.

    Enhanced by Zemanta

    Did you enjoy this article?

    Published on June 20th, 2013 in devise, Facebook, Login, omniauth, Ruby, Uncategorized

    Learned something new?
    Want to become a high value JavaScript expert?

    Here's how it works 👇

    Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Start with an interactive cheatsheet 📖

    Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

    "Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

    ~ Ashish Kumar

    Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created bySwizecwith ❤️