Hey there, fellow Ruby developer! Ready to add some rock-solid authentication to your app? Look no further than Firebase Auth. It's like having a security guard for your application, but way cooler and doesn't need coffee breaks. In this guide, we'll walk through integrating Firebase Auth into your Ruby project. Trust me, your future self will thank you for this added layer of security.
Before we dive in, make sure you've got:
Oh, and don't forget to install these gems:
gem 'firebase_admin' gem 'jwt'
First things first, let's get that Firebase Admin SDK up and running:
require 'firebase_admin' Firebase::Admin.configure do |config| config.credentials = 'path/to/your/service-account-key.json' end
Pro tip: Keep that service account key safe. It's like the keys to your castle!
Let's get those users on board:
def sign_up(email, password) Firebase::Auth.create_user( email: email, password: password ) end
Welcome back, user:
def sign_in(email, password) Firebase::Auth.sign_in_with_email_and_password(email, password) end
Because we all forget sometimes:
def reset_password(email) Firebase::Auth.send_password_reset_email(email) end
For those special snowflake sessions:
def create_custom_token(uid) Firebase::Auth.create_custom_token(uid) end
Trust, but verify:
def verify_id_token(token) Firebase::Auth.verify_id_token(token) end
Get to know your users:
def get_user(uid) Firebase::Auth.get_user(uid) end
People change, and so do their profiles:
def update_user(uid, attributes) Firebase::Auth.update_user(uid, attributes) end
Sometimes, it's time to say goodbye:
def delete_user(uid) Firebase::Auth.delete_user(uid) end
Give your users some extra flair:
def set_custom_claims(uid, claims) Firebase::Auth.set_custom_user_claims(uid, claims) end
With great power comes great responsibility:
def verify_admin(token) claims = verify_id_token(token) claims['admin'] == true end
Keep those endpoints locked down:
class AuthMiddleware def initialize(app) @app = app end def call(env) begin token = extract_token(env) Firebase::Auth.verify_id_token(token) @app.call(env) rescue => e [401, {'Content-Type' => 'application/json'}, [{error: 'Unauthorized'}.to_json]] end end private def extract_token(env) # Extract token from Authorization header end end
Don't forget to test! Here's a quick example using RSpec:
RSpec.describe AuthService do describe '#sign_up' do it 'creates a new user' do result = AuthService.sign_up('[email protected]', 'password123') expect(result).to have_key('localId') end end end
And there you have it! You've just leveled up your Ruby app with Firebase Auth. Remember, authentication is just the beginning. Keep exploring Firebase's other features to make your app even more awesome.
Now go forth and code securely, my friend! 🚀