User Login

User Login

This example shows how you can implement user login on the server side using the DID Token.

The example assumes:

  • You have already configured your client-side app with the Magic Client SDK
  • The example below is assuming you are already using a Ruby Web Framework (Rails, Sinatra, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below
important

It is important to always validate the DID Token before using.

require 'magic-admin'
require 'magic_user_login_service'
# Using
MagicUserLoginService.call(headers, email)
# Definition
class MagicUserLoginService
def self.call(headers, email)
new(headers).login(email)
end
def initialize(headers = {})
@headers = headers
@magic = Magic.new(api_secret_key: '<YOUR_API_SECRET_KEY>')
end
def login(email)
begin
validate_did_token?
rescue MagicAdmin::DIDTokenError => e
e.message
# Your rescue code
end
user_info = load_user(email)
# Handle the user mismatch by raising your application error. ``UnauthorizedError``
# is an example.
raise UnauthorizedError.new('UnAuthorized user login') unless user_info.issuer == issuer
end
def load_user(email)
# Application logics to load user by email from your database.
end
private
attr_reader :headers, :magic
def issuer
magic.token.get_issuer(did_token)
end
def validate_did_token?
magic.token.validate(did_token)
end
def did_token
return nil if headers['Authorization'].nil?
headers['Authorization'].split(' ').last
end
end