### 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 (
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 (Logged in as: {user.email}