Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    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
    Published on June 20th, 2013 in devise, Facebook, Login, omniauth, Ruby, Uncategorized

    Did you enjoy this article?

    Continue reading about Force users to add a facebook login with devise omniauth

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

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

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    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 by Swizec with ❤️