### Python Server-Side Token Validation with Magic Admin SDK Source: https://context7.com/context7/magic_link/llms.txt Validates Magic authentication tokens in Python applications using the Magic Admin SDK. This example demonstrates a function to validate the token and retrieve user metadata, with integration into a Flask application. Requires the Magic Admin SDK for Python (`pip install magic-admin`). ```python from magic_admin import Magic from magic_admin.error import DIDTokenError, RequestError # Initialize with secret key magic = Magic(api_secret_key='sk_live_YOUR_SECRET_KEY') def validate_magic_token(did_token): """Validate DID token and return user metadata""" try: # Validate the token magic.Token.validate(did_token) # Get user metadata issuer = magic.Token.get_issuer(did_token) user_metadata = magic.User.get_metadata_by_issuer(issuer) return { 'issuer': user_metadata.issuer, 'email': user_metadata.email, 'public_address': user_metadata.public_address, } except DIDTokenError as e: print(f'Token validation failed: {e}') raise ValueError('Invalid token') except RequestError as e: print(f'Request failed: {e}') raise # Flask example from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/api/auth/login', methods=['POST']) def login(): auth_header = request.headers.get('Authorization') if not auth_header or not auth_header.startswith('Bearer '): return jsonify({'error': 'No token provided'}), 401 did_token = auth_header.replace('Bearer ', '') try: user_data = validate_magic_token(did_token) # Create session or JWT session_token = create_session_token(user_data) return jsonify({ 'success': True, 'user': user_data, 'session_token': session_token, }) except ValueError as e: return jsonify({'error': str(e)}), 401 ``` -------------------------------- ### Get User Metadata in JavaScript Source: https://context7.com/context7/magic_link/llms.txt Retrieves authenticated user information, including their issuer (DID), email, and blockchain public address. This function first checks if the user is logged in. ```javascript import { Magic } from 'magic-sdk'; const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY'); async function getUserProfile() { try { const isLoggedIn = await magic.user.isLoggedIn(); if (!isLoggedIn) { throw new Error('User not logged in'); } const metadata = await magic.user.getMetadata(); return { issuer: metadata.issuer, // DID of the user email: metadata.email, publicAddress: metadata.publicAddress, // Blockchain wallet address phoneNumber: metadata.phoneNumber, // If SMS auth is used }; } catch (error) { console.error('Failed to get user metadata:', error); throw error; } } // Usage getUserProfile().then(profile => { console.log('User profile:', profile); }); ``` -------------------------------- ### Node.js Server-Side Token Validation with Magic Admin SDK Source: https://context7.com/context7/magic_link/llms.txt Validates DID tokens on the server using the Magic Admin SDK for Node.js. It includes middleware for Express.js to extract and validate tokens from the Authorization header and attach user metadata to the request. Assumes the Magic Admin SDK is installed (`npm install @magic-sdk/admin`). ```javascript import { Magic } from '@magic-sdk/admin'; // Initialize with secret key (keep this secure!) const magic = new Magic('sk_live_YOUR_SECRET_KEY'); // Express.js middleware example async function validateMagicToken(req, res, next) { try { // Extract DID token from Authorization header const didToken = req.headers.authorization?.replace('Bearer ', ''); if (!didToken) { return res.status(401).json({ error: 'No token provided' }); } // Validate the token magic.token.validate(didToken); // Get user metadata from the token const metadata = await magic.users.getMetadataByToken(didToken); // Attach user info to request req.user = { issuer: metadata.issuer, email: metadata.email, publicAddress: metadata.publicAddress, }; next(); } catch (error) { console.error('Token validation failed:', error); return res.status(401).json({ error: 'Invalid token' }); } } // Protected route example app.post('/api/auth/login', validateMagicToken, async (req, res) => { // Create session or JWT const sessionToken = createSessionToken(req.user); res.json({ success: true, user: req.user, sessionToken: sessionToken, }); }); ``` -------------------------------- ### Get User Metadata Source: https://context7.com/context7/magic_link/llms.txt Retrieves metadata for the currently authenticated user, including their issuer (DID), email, public blockchain address, and potentially phone number if SMS authentication was used. ```APIDOC ## Get User Metadata ### Description Retrieves authenticated user information. This includes the user's Decentralized Identifier (DID), email address, public blockchain wallet address, and optionally, their phone number if SMS authentication was utilized. ### Method `magic.user.getMetadata()` ### Endpoint Not Applicable (Method call within SDK) ### Parameters None ### Request Example ```javascript import { Magic } from 'magic-sdk'; const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY'); async function getUserProfile() { try { const isLoggedIn = await magic.user.isLoggedIn(); if (!isLoggedIn) { throw new Error('User not logged in'); } const metadata = await magic.user.getMetadata(); return { issuer: metadata.issuer, // DID of the user email: metadata.email, publicAddress: metadata.publicAddress, // Blockchain wallet address phoneNumber: metadata.phoneNumber, // If SMS auth is used }; } catch (error) { console.error('Failed to get user metadata:', error); throw error; } } // Usage getUserProfile().then(profile => { console.log('User profile:', profile); }); ``` ### Response #### Success Response (200) - **issuer** (string) - The Decentralized Identifier (DID) of the user. - **email** (string) - The email address of the user. Null if not available. - **publicAddress** (string) - The user's blockchain wallet address. Null if not available. - **phoneNumber** (string) - The user's phone number, if authenticated via SMS. Null otherwise. #### Response Example ```json { "issuer": "did:eth:12345abc...", "email": "user@example.com", "publicAddress": "0xAbCdEf1234567890aBcDeF1234567890aBcDeF12", "phoneNumber": null } ``` #### Error Response - **Error** - Thrown if the user is not logged in or if there's an issue retrieving metadata. #### Error Example ``` Error: Failed to get user metadata: User not logged in ``` ``` -------------------------------- ### Initialize Magic SDK in JavaScript Source: https://context7.com/context7/magic_link/llms.txt Initializes the Magic SDK with a publishable API key for use in a web application. It also demonstrates how to check if a user is already logged in and retrieve their metadata. ```javascript import { Magic } from 'magic-sdk'; // Initialize Magic with your publishable API key const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY', { network: 'mainnet', // or 'goerli', 'polygon', etc. }); // Check if user is already logged in const isLoggedIn = await magic.user.isLoggedIn(); if (isLoggedIn) { // Get user metadata const metadata = await magic.user.getMetadata(); console.log('User email:', metadata.email); console.log('User public address:', metadata.publicAddress); } ``` -------------------------------- ### JavaScript SDK Initialization Source: https://context7.com/context7/magic_link/llms.txt Initializes the Magic SDK in a web application to enable passwordless authentication flows. Requires your publishable API key. ```APIDOC ## JavaScript SDK Initialization ### Description Initialize the Magic SDK in a web application to enable passwordless authentication flows. ### Method Not Applicable (Initialization) ### Endpoint Not Applicable (Initialization) ### Parameters None ### Request Example ```javascript import { Magic } from 'magic-sdk'; // Initialize Magic with your publishable API key const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY', { network: 'mainnet', // or 'goerli', 'polygon', etc. }); // Check if user is already logged in const isLoggedIn = await magic.user.isLoggedIn(); if (isLoggedIn) { // Get user metadata const metadata = await magic.user.getMetadata(); console.log('User email:', metadata.email); console.log('User public address:', metadata.publicAddress); } ``` ### Response #### Success Response (Initialization) Initialization does not return a direct response, but the `magic` object is made available for subsequent API calls. #### Response Example None ``` -------------------------------- ### Connect Web3 Wallet with Magic Link Source: https://context7.com/context7/magic_link/llms.txt Establishes a connection to a user's Web3 wallet using Magic Link, retrieves the Ethereum address and balance, and enables transaction sending. It requires Magic SDK and the Ethereum extension. Inputs include user's email for login and recipient address/amount for transactions. Outputs are wallet address, balance, and transaction hash. ```javascript import { Magic } from 'magic-sdk'; import { EthereumExtension } from '@magic-ext/ethereum'; // Initialize Magic with Ethereum extension const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY', { extensions: [ new EthereumExtension({ rpcUrl: 'https://mainnet.infura.io/v3/YOUR_INFURA_KEY', }), ], }); async function connectWallet() { try { // Login with magic link await magic.auth.loginWithMagicLink({ email: 'user@example.com', }); // Get user's Ethereum address const accounts = await magic.ethereum.request({ method: 'eth_accounts', }); const address = accounts[0]; console.log('Wallet address:', address); // Get balance const balance = await magic.ethereum.request({ method: 'eth_getBalance', params: [address, 'latest'], }); console.log('Balance (wei):', balance); return { address, balance }; } catch (error) { console.error('Wallet connection failed:', error); throw error; } } // Send transaction async function sendTransaction(toAddress, amount) { try { const accounts = await magic.ethereum.request({ method: 'eth_accounts', }); const txParams = { from: accounts[0], to: toAddress, value: amount, // Amount in wei gas: '0x5208', // 21000 gas }; const txHash = await magic.ethereum.request({ method: 'eth_sendTransaction', params: [txParams], }); console.log('Transaction hash:', txHash); return txHash; } catch (error) { console.error('Transaction failed:', error); throw error; } } ``` -------------------------------- ### Implement OAuth Social Login with Magic Link Source: https://context7.com/context7/magic_link/llms.txt Integrates social login providers (Google, Facebook, GitHub, Twitter) using Magic Link's OAuth extension. It allows users to log in via their social accounts and retrieves user metadata and OAuth tokens. The callback handler processes the redirect result. Dependencies include Magic SDK and the OAuth extension. Inputs are provider name and redirect URI. Outputs include user metadata and OAuth details. ```javascript import { Magic } from 'magic-sdk'; import { OAuthExtension } from '@magic-ext/oauth'; const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY', { extensions: [new OAuthExtension()] }); async function loginWithGoogle() { try { await magic.oauth.loginWithRedirect({ provider: 'google', redirectURI: `${window.location.origin}/callback`, }); } catch (error) { console.error('OAuth login failed:', error); throw error; } } // Handle OAuth callback async function handleOAuthCallback() { try { // Get OAuth result from redirect const result = await magic.oauth.getRedirectResult(); console.log('OAuth provider:', result.oauth.provider); console.log('OAuth access token:', result.oauth.accessToken); // Get user metadata const metadata = await magic.user.getMetadata(); return { user: metadata, oauth: result.oauth, }; } catch (error) { console.error('OAuth callback failed:', error); throw error; } } // Complete example with multiple providers function SocialLoginButtons() { const providers = ['google', 'facebook', 'github', 'twitter']; async function handleSocialLogin(provider) { try { await magic.oauth.loginWithRedirect({ provider: provider, redirectURI: `${window.location.origin}/callback`, }); } catch (error) { console.error(`${provider} login failed:`, error); } } return (
{providers.map(provider => ( ))}
); } ``` -------------------------------- ### Custom UI Authentication with Magic Link SDK in JavaScript Source: https://context7.com/context7/magic_link/llms.txt Implements passwordless login using Magic Link with a custom user interface. It disables Magic's default UI and handles loading, success, and error states through custom functions. Dependencies include the 'magic-sdk' library. It takes an email address as input and returns a DID token upon successful authentication and server verification. ```javascript import { Magic } from 'magic-sdk'; const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY'); async function customUILogin(email) { try { // Show custom loading UI showCustomLoadingSpinner(); // Login without Magic's UI const didToken = await magic.auth.loginWithMagicLink({ email: email, showUI: false, // Disable Magic's UI }); // Show custom success message hideCustomLoadingSpinner(); showCustomSuccessMessage('Check your email for the magic link!'); // Wait for email confirmation // The promise resolves when user clicks the magic link console.log('DID Token:', didToken); // Verify on server const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${didToken}`, }, }); const data = await response.json(); if (data.success) { showCustomWelcomeScreen(data.user); } return data; } catch (error) { hideCustomLoadingSpinner(); showCustomErrorMessage(error.message); throw error; } } // Helper functions for custom UI function showCustomLoadingSpinner() { document.getElementById('custom-spinner').style.display = 'block'; } function hideCustomLoadingSpinner() { document.getElementById('custom-spinner').style.display = 'none'; } function showCustomSuccessMessage(message) { document.getElementById('custom-message').textContent = message; document.getElementById('custom-message').className = 'success'; } function showCustomErrorMessage(message) { document.getElementById('custom-message').textContent = message; document.getElementById('custom-message').className = 'error'; } function showCustomWelcomeScreen(user) { document.getElementById('welcome-screen').innerHTML = $( '

Welcome, ${user.email}!

\n

Your wallet address: ${user.publicAddress}

' ); } ``` -------------------------------- ### React Magic Link Authentication with Hooks Source: https://context7.com/context7/magic_link/llms.txt Integrates Magic authentication into a React web application using custom hooks. It handles user login, logout, and checks the authentication status. Requires the 'magic-sdk' library. ```javascript import React, { createContext, useContext, useState, useEffect } from 'react'; import { Magic } from 'magic-sdk'; const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY'); const AuthContext = createContext(); export function AuthProvider({ children }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { checkUserLoggedIn(); }, []); async function checkUserLoggedIn() { try { const isLoggedIn = await magic.user.isLoggedIn(); if (isLoggedIn) { const metadata = await magic.user.getMetadata(); setUser(metadata); } } catch (error) { console.error('Error checking login status:', error); } finally { setLoading(false); } } async function login(email) { try { setLoading(true); await magic.auth.loginWithMagicLink({ email }); const metadata = await magic.user.getMetadata(); setUser(metadata); return metadata; } catch (error) { console.error('Login failed:', error); throw error; } finally { setLoading(false); } } async function logout() { try { setLoading(true); await magic.user.logout(); setUser(null); } catch (error) { console.error('Logout failed:', error); throw error; } finally { setLoading(false); } } return ( {children} ); } export function useAuth() { return useContext(AuthContext); } // Component usage function LoginForm() { const { login, user, logout } = useAuth(); const [email, setEmail] = useState(''); if (user) { return (

Logged in as: {user.email}

); } return (
{ e.preventDefault(); login(email); }}> setEmail(e.target.value)} placeholder="Enter your email" required />
); } ``` -------------------------------- ### Email Magic Link Authentication Source: https://context7.com/context7/magic_link/llms.txt Sends a magic link to a user's email address for passwordless login. Optionally displays Magic's UI and returns a DID token upon successful authentication. ```APIDOC ## Email Magic Link Authentication ### Description Send a magic link to a user's email address for passwordless login. This method can trigger Magic's built-in UI for a seamless user experience and returns a Decentralized Identifier (DID) token upon successful authentication, which should be sent to your server for validation. ### Method POST (implicitly via `magic.auth.loginWithMagicLink`) ### Endpoint `magic.auth.loginWithMagicLink({ email: string, showUI?: boolean })` ### Parameters #### Request Body (within the SDK method call) - **email** (string) - Required - The email address of the user to authenticate. - **showUI** (boolean) - Optional - If `true`, displays Magic's built-in UI for the authentication flow. Defaults to `false` if not provided. ### Request Example ```javascript import { Magic } from 'magic-sdk'; const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY'); async function loginWithEmail(email) { try { // Trigger magic link email const didToken = await magic.auth.loginWithMagicLink({ email: email, showUI: true, // Show Magic's built-in UI }); // Send DID token to your server for validation const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${didToken}`, }, }); const data = await response.json(); console.log('Login successful:', data.user); return data; } catch (error) { console.error('Login failed:', error); throw error; } } // Usage loginWithEmail('user@example.com'); ``` ### Response #### Success Response (200) - **didToken** (string) - The Decentralized Identifier token for the authenticated user. This token should be sent to your backend for validation. #### Response Example ```json { "didToken": "did:eth:12345abc..." } ``` #### Error Response - **Error** - Thrown if the login process fails (e.g., invalid email, network issues). #### Error Example ``` Error: Login failed: MagicSDKError: Invalid email format ``` ``` -------------------------------- ### Implement SMS Passwordless Authentication with Magic Link Source: https://context7.com/context7/magic_link/llms.txt Enables passwordless authentication using a user's phone number via Magic Link. Users receive a magic link via SMS to log in. The system validates the DID token on the server and retrieves user metadata. Requires Magic SDK. Input is a phone number in E.164 format. Outputs include user metadata and a DID token. ```javascript import { Magic } from 'magic-sdk'; const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY'); async function loginWithSMS(phoneNumber) { try { // Send SMS with magic link const didToken = await magic.auth.loginWithSMS({ phoneNumber: phoneNumber, // Format: +1234567890 }); // Validate token on server const response = await fetch('/api/auth/verify', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${didToken}`, }, }); const data = await response.json(); console.log('SMS login successful:', data.user); return data; } catch (error) { console.error('SMS login failed:', error); throw error; } } // Usage with international phone numbers async function loginUser() { try { const phoneNumber = '+14155551234'; // E.164 format required const result = await loginWithSMS(phoneNumber); // Get user metadata const metadata = await magic.user.getMetadata(); console.log('Phone number:', metadata.phoneNumber); console.log('Issuer:', metadata.issuer); return metadata; } catch (error) { if (error.code === 'INVALID_PHONE_NUMBER') { console.error('Please provide a valid phone number'); } throw error; } } ``` -------------------------------- ### Authenticate with Email Magic Link in JavaScript Source: https://context7.com/context7/magic_link/llms.txt Sends a magic link to a user's email address to initiate a passwordless login flow. The function handles sending the DID token to a backend API for validation. ```javascript import { Magic } from 'magic-sdk'; const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY'); async function loginWithEmail(email) { try { // Trigger magic link email const didToken = await magic.auth.loginWithMagicLink({ email: email, showUI: true, // Show Magic's built-in UI }); // Send DID token to your server for validation const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${didToken}`, }, }); const data = await response.json(); console.log('Login successful:', data.user); return data; } catch (error) { console.error('Login failed:', error); throw error; } } // Usage loginWithEmail('user@example.com'); ``` -------------------------------- ### React Native Magic Link Authentication Source: https://context7.com/context7/magic_link/llms.txt Implements Magic authentication for React Native mobile applications using '@magic-sdk/react-native'. Provides functionality for user login, logout, and checking login status. ```javascript import { Magic } from '@magic-sdk/react-native'; import React, { useState, useEffect } from 'react'; import { View, TextInput, Button, Text } from 'react-native'; // Initialize Magic const magic = new Magic('pk_live_YOUR_PUBLISHABLE_KEY'); function LoginScreen() { const [email, setEmail] = useState(''); const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { checkLogin(); }, []); async function checkLogin() { try { const isLoggedIn = await magic.user.isLoggedIn(); if (isLoggedIn) { const metadata = await magic.user.getMetadata(); setUser(metadata); } } catch (error) { console.error('Error checking login:', error); } finally { setLoading(false); } } async function handleLogin() { try { setLoading(true); await magic.auth.loginWithMagicLink({ email }); const metadata = await magic.user.getMetadata(); setUser(metadata); } catch (error) { console.error('Login failed:', error); alert('Login failed'); } finally { setLoading(false); } } async function handleLogout() { try { setLoading(true); await magic.user.logout(); setUser(null); } catch (error) { console.error('Logout failed:', error); } finally { setLoading(false); } } if (loading) { return Loading...; } if (user) { return ( Welcome, {user.email} Address: {user.publicAddress}