metanetsoft / foxlogin
Official PHP SDK for Fox Login: client-side sign-up/sign-in sessions and server-side token verification + management API.
Requires
- php: >=8.1
- ext-json: *
- ext-sodium: *
- firebase/php-jwt: ^7.0
- guzzlehttp/guzzle: ^7.0
Requires (Dev)
- phpunit/phpunit: ^10.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Official PHP SDK for Fox Login: browser/app client (sign-up, sign-in, sessions) and server-side token verification + management API.
Install
composer require metanetsoft/foxlogin
Requires PHP >= 8.1 with the sodium extension (bundled with PHP by default; verify with
php -m | grep sodium).
Client quick start (end users — publishable key)
use FoxLogin\FoxLogin; $fox = new FoxLogin(['publishableKey' => 'pk_live_eu_...']); $fox->signUp(['email' => 'a@b.com', 'password' => 'secret', 'country' => 'DE']); // -> ['status' => 'verification_sent'], sent by email $fox->verifySignUp(['email' => 'a@b.com', 'code' => '123456']); $result = $fox->signIn(['email' => 'a@b.com', 'password' => 'secret']); if ($result['status'] === 'mfa_required') { $user = $fox->verifyMfa(['mfaToken' => $result['mfaToken'], 'code' => readline('Code: ')]); } else { $user = $result['user']; } $token = $fox->getToken(); // refreshes automatically when near expiry; send as Bearer <token> $fox->onChange(function (array $state): void { // $state is ['status' => 'signed_in', 'user' => User] or ['status' => 'signed_out'] }); $fox->signOut();
signIn(), verifySignUp(), signInWithCode() and confirmPasswordReset() all return this
same ['status' => 'signed_in', 'user' => User] or ['status' => 'mfa_required', 'mfaToken' => string] shape — mfa_required means nothing was stored yet, and verifyMfa() finishes it.
Passwordless sign-in and password reset are also available:
$fox->sendSignInCode(['email' => 'a@b.com']); $fox->signInWithCode(['email' => 'a@b.com', 'code' => '123456']); $fox->startPasswordReset(['email' => 'a@b.com']); $fox->confirmPasswordReset(['email' => 'a@b.com', 'code' => '654321', 'password' => 'new-secret']);
Session storage
The session (refresh token, access token, user) is kept via a FoxLogin\SessionStorage.
MemoryStorage (the default) keeps it only for the lifetime of the PHP process — fine for a
single request/response cycle driven purely by a cookie your own backend issues. For a
server-rendered app that should remember the session across requests in the same PHP session, use
PhpSessionStorage (start session_start() first):
use FoxLogin\FoxLogin; use FoxLogin\PhpSessionStorage; session_start(); $fox = new FoxLogin(['publishableKey' => 'pk_live_eu_...', 'storage' => new PhpSessionStorage()]);
Implement FoxLogin\SessionStorage yourself to store it anywhere else (Redis, an encrypted
cookie, ...).
Where users are stored
You never pick a region. Each user is stored in the region of the country they choose at
sign-up (Türkiye → TR, every other country → EU), and the SDK sends every call to the right
place: sign-up to the country's region, sign-in and codes to the region that has the address,
session calls (refresh, sign-out, 2FA, profile) to the user's region. Your code is the same for
every user. $fox->regionForCountry('TR') tells you the region of a country; the
regionHosts option (e.g. ['EU' => 'http://localhost:8081', 'TR' => 'http://localhost:8082'])
overrides region hosts for tests or self-hosting.
Check input before sending
use FoxLogin\Validate; Validate::isValidEmail('ayse@anka.com.tr'); // true Validate::normalizePhone('+90 532 123 45 67'); // '+905321234567' (the country code is required) Validate::isValidPhone('0532 123 45 67'); // false Validate::isValidUsername('ece_k'); // true $fox->checkAvailability(['field' => 'username', 'value' => 'ece']); // ['available' => true, …]
checkAvailability works for usernames and phone numbers (unique in the application across all
regions). Email addresses are never checked this way, so nobody can find out which addresses have
accounts. signUp() rejects a malformed email (invalid_email) or profile phone
(invalid_field) before sending anything.
Sign in with Google
// Sign-in page: redirect the browser (the redirect URI must be listed under Redirect URLs). $_SESSION['fox_state'] = bin2hex(random_bytes(16)); header('Location: ' . $fox->googleSignInUrl([ 'redirectUri' => 'https://your.app/auth/callback', 'state' => $_SESSION['fox_state'], ])); // https://your.app/auth/callback — checks the state, then signs in or asks for more: $r = $fox->handleRedirect($_GET, $_SESSION['fox_state'] ?? null); // null: not a Fox Login return if ($r === null) { // not a Fox Login return } elseif ($r['status'] === 'country_required') { $fox->completeGoogleSignUp(['ticket' => $r['ticket'], 'country' => 'TR']); // ask the user first } elseif ($r['status'] === 'profile_required') { // The application requires fields Google doesn't give ($r['fields'], e.g. ['username']). // Ask for them (and the country when $r['country'] is null); fix errors and send again. $fox->completeGoogleSignUp([ 'ticket' => $r['ticket'], 'country' => $r['country'] ?? 'TR', 'profile' => ['username' => 'ada'], ]); } elseif ($r['status'] === 'mfa_required') { $fox->verifyMfa(['mfaToken' => $r['mfaToken'], 'code' => $code]); } // fox_error (e.g. "access_denied") throws FoxLoginError with that code. // exchangeGoogleCode($_GET['fox_code'], $_GET['fox_region'] ?? null) does the code step alone.
Whether Google shows Fox Login's app or your own Google app is set in the dashboard; the code is the same in both cases.
Sign in with an SMS code
// Dashboard › Login settings › SMS. Users need a phone number in their profile. $fox->sendSmsCode(['phone' => '+905321234567']); // invalid_field before sending when malformed $r = $fox->signInWithSms(['phone' => '+905321234567', 'code' => $code]); // like signIn()
The code is sent by the region of the user with that number (looked up once and cached).
Only some countries (IP check)
// Dashboard › Login settings › General: "Only listed countries" + IP check (sign-up, sign-in). $ip = $fox->checkIp(); // ['country' => 'US', 'signUpAllowed' => false, 'signInAllowed' => true, 'ipCheck' => true] if (!$ip['signUpAllowed']) { echo 'Sign-up is not available in your country.'; } // The server refuses anyway with FoxLoginError code "ip_country_not_allowed" (403).
On a server the IP checked is the one your backend calls Fox Login from.
Two-factor authentication
// The signed-in user turns 2FA on in their settings: $otpauthUrl = $fox->setupTotp()['otpauthUrl']; // show as a QR code $recoveryCodes = $fox->enableTotp(['code' => $code])['recoveryCodes']; // show the codes once $fox->disableTotp(['code' => $code]); // Application policy "required" (dashboard › Login settings › 2FA): a user without 2FA sets it // up during sign-in, before getting a session. $r = $fox->signIn(['email' => $email, 'password' => $password]); if ($r['status'] === 'mfa_setup_required') { $otpauthUrl = $fox->setupTotp(['mfaToken' => $r['mfaToken']])['otpauthUrl']; $done = $fox->enableTotp(['code' => $code, 'mfaToken' => $r['mfaToken']]); // signed in // $done['user'], $done['recoveryCodes'] }
recoveryCodes is empty when the application turned recovery codes off.
Sign-up fields
$app = $fox->getAppConfig(); // sign-in methods, providers and user fields of the application // $app->fieldMode('username') === 'required' -> show a required username input $fox->signUp([ 'email' => $email, 'password' => $password, 'country' => 'TR', 'profile' => ['username' => 'ayse', 'plan' => 'pro'], ]);
A missing or invalid field throws FoxLoginError with code missing_field / invalid_field
(400) or field_taken (409); $e->getDetails()['field'] names the field. A sign-in method that
is off answers method_disabled (403). User::$profile holds the field values.
Users edit their profile
$me = $fox->getProfile(); $fox->updateProfile(['name' => 'Ece', 'profile' => ['username' => 'ece']]); // only "user can edit" fields
Both need a signed-in user (signed_out, 401, otherwise) and update the stored user. Errors:
field_not_editable, missing_field, invalid_field (400) and field_taken (409).
Server quick start (your backend — verify tokens, manage users)
use FoxLogin\TokenVerifier; use FoxLogin\FoxLoginError; try { $claims = TokenVerifier::verifyToken($bearerToken, ['applicationId' => 'app_123']); // $claims->sub is the user id, $claims->rgn the region, $claims->labels custom labels. } catch (FoxLoginError $e) { // $e->getErrorCode(): 'invalid_token' | 'wrong_application', $e->getStatus() === 401 }
use FoxLogin\FoxLoginAdmin; // A secret key (sk_live_...) belongs to one application. Copy it from the application's API keys tab. $admin = new FoxLoginAdmin(['secretKey' => getenv('FOXLOGIN_SECRET_KEY')]); $user = $admin->createUser('app_...', ['email' => 'a@b.com', 'country' => 'DE']);
A secret key works only inside its own application, within the role you gave it (Full access,
Read and write users, Read only). For work across applications, such as creating a new
application, use an organization API key (fk_live_..., page "API keys" in the dashboard).
apiKey and secretKey are the same option.
$org = new FoxLoginAdmin(['apiKey' => getenv('FOXLOGIN_API_KEY')]); $app = $org->createApplication(['name' => 'My App', 'region' => 'EU']);
Keep both keys on your server. Never ship them to a browser or app.
Laravel middleware
<?php // app/Http/Middleware/VerifyFoxLoginToken.php namespace App\Http\Middleware; use Closure; use FoxLogin\FoxLoginError; use FoxLogin\TokenVerifier; use Illuminate\Http\Request; class VerifyFoxLoginToken { public function handle(Request $request, Closure $next) { $token = $request->bearerToken(); if ($token === null) { return response()->json(['error' => ['code' => 'missing_token']], 401); } try { $claims = TokenVerifier::verifyToken($token, [ 'applicationId' => config('services.foxlogin.application_id'), ]); } catch (FoxLoginError $e) { return response()->json(['error' => ['code' => $e->getErrorCode()]], $e->getStatus()); } $request->attributes->set('foxlogin_claims', $claims); return $next($request); } }
Register it in bootstrap/app.php (or app/Http/Kernel.php on Laravel <= 10) and apply it to any
route group that requires a signed-in user:
Route::middleware('foxlogin')->group(function () { Route::get('/me', fn (Request $request) => $request->attributes->get('foxlogin_claims')); });
Errors
Every failed call throws FoxLogin\FoxLoginError with getStatus(), getErrorCode(),
getMessage(), isRetryable(), getRetryAfter() (seconds, from Retry-After), getRegion()
and getDetails() (e.g. ['user_id' => '...'] on email_exists).
Testing your own code against this SDK
Inject a Guzzle client built on GuzzleHttp\Handler\MockHandler via the httpClient option on
both FoxLogin and FoxLoginAdmin — see tests/MockHttp.php in this repository for the helper
used by the SDK's own test suite.
Development
composer install vendor/bin/phpunit
License
MIT — see LICENSE.