vue-auth-controller
v0.2.0
Published
Universal Vue.js authentication controller with OAuth support and code-based callback handling
Maintainers
Readme
vue-auth-controller
Universal Vue.js authentication controller with OAuth support and code-based callback handling for Vue 3 and Pinia.
🚀 Features
- Universal Authentication Flow - Single entry point for all auth operations
- OAuth Support - Telegram, Google, Yandex integration
- Code-based OAuth Callbacks - Support for Google and Yandex OAuth with
codeparameter - Queue System - Prevents concurrent authentication requests
- Smart Redirects - Automatic navigation based on user verification status
- TypeScript Support - Full type safety
- Configurable Logging - Beautiful colored console output with emojis
- Pinia Integration - Designed specifically for Pinia store
- Vue 3 Support - Composition API and Options API support
📦 Installation
npm install vue-auth-controller🔧 Quick Start
1. Install Plugin
import { createApp } from "vue";
import { createPinia } from "pinia";
import AuthController from "vue-auth-controller";
import { useUserStore } from "./stores/user";
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.use(AuthController, {
userStore: useUserStore(),
config: {
routes: {
emailVerify: "/auth/email-verify",
telegramVerify: "/auth/telegram-verify",
kyc: "/account/kyc",
profile: "/account/profile",
home: "/",
},
logging: {
enabled: true,
colors: true,
level: "info",
},
},
});
app.mount("#app");2. Use in Components
<script setup lang="ts">
import { useAuthController } from "vue-auth-controller";
const { handleManualLogin, handleOAuthCallback, isProcessing, getUserInfo } =
useAuthController();
const handleLogin = async () => {
await handleManualLogin({
email: "[email protected]",
password: "password",
});
};
const handleGoogleCallback = async (queryData: any) => {
// AuthController will automatically detect code-based OAuth
await handleOAuthCallback("google", queryData, {
redirectAfterSuccess: "/account/profile",
});
};
</script>⚠️ Important: Vue 3 Initialization
Due to Vue 3's composition API rules, the AuthController cannot be initialized directly in main.ts because it requires access to Pinia stores and Vue Router, which are only available after the app is fully set up.
Method 1: Initialize in App.vue (Recommended)
// main.ts
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount("#app");<!-- App.vue -->
<script setup lang="ts">
import { onMounted } from "vue";
import { useUserStore } from "./stores/user";
import { AuthController } from "vue-auth-controller";
const userStore = useUserStore();
onMounted(() => {
// Initialize AuthController after Vue is fully set up
AuthController.install(app, {
userStore,
config: {
routes: {
emailVerify: "/auth/email-verify",
telegramVerify: "/auth/telegram-verify",
kyc: "/account/kyc",
profile: "/account/profile",
home: "/",
},
logging: {
enabled: true,
colors: true,
level: "info",
},
},
});
});
</script>🔄 OAuth Callback Handling
Code-based OAuth (Google/Yandex)
The AuthController now supports code-based OAuth callbacks for Google and Yandex:
// In your OAuth callback handler
const { handleOAuthCallback } = useAuthController();
// For Google OAuth callback with code parameter
await handleOAuthCallback(
"google",
{
code: "authorization_code_from_google",
state: "optional_state_parameter",
},
{
redirectAfterSuccess: "/account/profile",
}
);
// For Yandex OAuth callback with code parameter
await handleOAuthCallback(
"yandex",
{
code: "authorization_code_from_yandex",
state: "optional_state_parameter",
},
{
redirectAfterSuccess: "/account/profile",
}
);Token-based OAuth (Telegram)
For Telegram OAuth, continue using the existing approach:
// For Telegram OAuth with token data
await handleOAuthCallback(
"telegram",
{
id: "123456789",
first_name: "John",
last_name: "Doe",
username: "johndoe",
photo_url: "https://example.com/photo.jpg",
auth_date: 1234567890,
hash: "telegram_hash",
},
{
redirectAfterSuccess: "/account/profile",
}
);📚 API Reference
Plugin Options
interface AuthControllerPluginOptions {
userStore: IUserStore;
appStore?: IAppStore;
config?: Partial<IAuthControllerConfig>;
logger?: ILogger;
}User Store Interface (IUserStore)
Your Pinia user store must implement this interface:
interface IUserStore {
user: User | null;
isUserLoggedIn: boolean;
isOauthRedirected: boolean;
registrationUsingTelegram: (data: any) => Promise<void>;
registrationUsingSocial: (provider: string, data: any) => Promise<void>;
registration: (data: any) => Promise<void>;
login: (credentials: any) => Promise<void>;
getOauthUrl: (provider: string) => Promise<string>;
logout?: () => Promise<void>;
refreshToken?: () => Promise<void>;
updateUser?: (data: Partial<User>) => Promise<void>;
}OAuth Data Types
// For code-based OAuth callbacks
interface GoogleOAuthCallbackData {
code: string;
state?: string;
[key: string]: any;
}
interface YandexOAuthCallbackData {
code: string;
state?: string;
[key: string]: any;
}
// For token-based OAuth
interface TelegramAuthData {
id: string;
first_name: string;
last_name?: string;
username?: string;
photo_url?: string;
auth_date: number;
hash: string;
}🔧 Configuration
import { createConfig } from "vue-auth-controller";
const config = createConfig({
routes: {
emailVerify: "/auth/email-verify",
telegramVerify: "/auth/telegram-verify",
kyc: "/account/kyc",
profile: "/account/profile",
home: "/",
},
logging: {
enabled: true,
colors: true,
level: "info",
},
oauth: {
providers: ["telegram", "google", "yandex"],
redirectStrategy: "window.location",
},
});📝 Logging
import { Logger } from "vue-auth-controller";
const customLogger = new Logger({
enabled: true,
colors: true,
level: "debug",
prefix: "MyAuth",
});🏭 Factory Methods
import { AuthControllerFactory } from "vue-auth-controller";
const controller = AuthControllerFactory.createWithVueRouter(
router,
userStore,
appStore,
config
);🧪 Testing
import { useAuthController } from "vue-auth-controller";
// Mock the controller for testing
vi.mock("vue-auth-controller", () => ({
useAuthController: vi.fn(() => ({
handleManualLogin: vi.fn(),
handleOAuthCallback: vi.fn(),
handleOAuthInitiation: vi.fn(),
handleEmailVerification: vi.fn(),
canAccessAuthPage: vi.fn(),
getAuthRedirectPath: vi.fn(),
isAuthProcessing: ref(false),
getUserInfo: vi.fn(() => ({
id: 1,
email: "[email protected]",
name: "Test User",
email_verified_at: null,
telegram_verified_at: null,
kyc_verified_at: null,
status: "UserStatus.NEW",
})),
})),
}));📖 Documentation
For detailed documentation, interactive examples, and API reference, visit:
The documentation includes:
- 📚 Installation Guide - Step-by-step setup instructions
- 💡 Interactive Examples - Live demos and code samples
- 📝 API Reference - Complete API documentation
- 🔧 Logging Examples - Console output examples
- 🎨 Theme Support - Dark/light theme toggle
🔄 Migration from v0.1.0
The main changes in v0.2.0:
- Added support for code-based OAuth callbacks for Google and Yandex
- New OAuth data types
GoogleOAuthCallbackDataandYandexOAuthCallbackData - Enhanced
handleOAuthCallbackto automatically detect callback type - Improved error handling for OAuth flows
- Better TypeScript support with stricter type checking
No breaking changes for existing implementations using token-based OAuth.
🌐 Website
https://vue-auth-controller.125368ap-b06.workers.dev/installation
