0.0.1 • Published 4 months ago

ngx-supabase-auth v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

ngx-supabase-auth

An Angular library for handling authentication with Supabase. This library provides ready-to-use components, services and guards for implementing authentication in Angular applications using Supabase as the backend.

Features

  • 🔑 Authentication components (Login, Password Reset, Profile)
  • 🔒 Authentication guards for route protection
  • 📊 State management using ngrx/signals
  • 🌈 Social login support (Google, Facebook, Twitter, GitHub)
  • 📱 Responsive design with Tailwind CSS
  • 🎨 Customizable components
  • 📝 TypeScript types for all features

Installation

npm install ngx-supabase-auth

Setup

First, configure the library in your app.config.ts:

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideSupabaseAuth } from 'ngx-supabase-auth';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideSupabaseAuth({
      supabaseUrl: 'YOUR_SUPABASE_URL',
      supabaseKey: 'YOUR_SUPABASE_API_KEY',
      // Optional configuration
      redirectAfterLogin: '/dashboard',
      redirectAfterLogout: '/login',
      authRequiredRedirect: '/login',
      authRedirectIfAuthenticated: '/dashboard'
    })
  ]
};

Components

LoginComponent

The login component handles user authentication via email/password or social providers.

Import

import { LoginComponent } from 'ngx-supabase-auth';

@Component({
  // ...
  imports: [LoginComponent],
  // ...
})

Usage

<sup-login
  title="Welcome Back"
  subtitle="Log in to your account"
  [showSocialLogins]="true"
  [enableGoogleLogin]="true"
  [enableFacebookLogin]="true"
  [enableGithubLogin]="true"
  [enableTwitterLogin]="true"
  [showForgotPassword]="true"
  [showSignUpLink]="true"
  (forgotPassword)="onForgotPassword()"
  (signUp)="onSignUp()"
></sup-login>

Parameters

InputTypeDefaultRequiredDescription
titlestring'Login'NoTitle displayed at the top of the login form
subtitlestringundefinedNoOptional subtitle displayed below the title
showSocialLoginsbooleantrueNoWhether to show social login options
enableGoogleLoginbooleantrueNoWhether to enable Google login button
enableFacebookLoginbooleantrueNoWhether to enable Facebook login button
enableGithubLoginbooleantrueNoWhether to enable GitHub login button
enableTwitterLoginbooleantrueNoWhether to enable Twitter login button
showForgotPasswordbooleantrueNoWhether to show the forgot password link
showSignUpLinkbooleantrueNoWhether to show the sign up link
OutputTypeDescription
forgotPasswordEventEmitterEmitted when the user clicks the forgot password link
signUpEventEmitterEmitted when the user clicks the sign up link

ProfileComponent

The profile component allows users to manage their profile information and change their password.

Import

import { ProfileComponent } from 'ngx-supabase-auth';

@Component({
  // ...
  imports: [ProfileComponent],
  // ...
})

Usage

<sup-profile
  title="User Profile"
  subtitle="Manage your account information"
  [showAvatarSection]="true"
  [showPasswordSection]="true"
  [showSignOut]="true"
  [allowEmailChange]="false"
></sup-profile>

Parameters

InputTypeDefaultRequiredDescription
titlestring'User Profile'NoTitle displayed at the top of the profile form
subtitlestringundefinedNoOptional subtitle displayed below the title
showAvatarSectionbooleantrueNoWhether to show the avatar section
showPasswordSectionbooleantrueNoWhether to show the password change section
showSignOutbooleantrueNoWhether to show the sign out button
allowEmailChangebooleanfalseNoWhether to allow the user to change their email

PasswordResetComponent

The password reset component allows users to request a password reset link.

Import

import { PasswordResetComponent } from 'ngx-supabase-auth';

@Component({
  // ...
  imports: [PasswordResetComponent],
  // ...
})

Usage

<sup-password-reset
  title="Reset Password"
  subtitle="Enter your email to get a reset link"
  (backToLogin)="onBackToLogin()"
></sup-password-reset>

Parameters

InputTypeDefaultRequiredDescription
titlestring'Reset Password'NoTitle displayed at the top of the password reset form
subtitlestringundefinedNoOptional subtitle displayed below the title. If not provided, a default message will be shown.
OutputTypeDescription
backToLoginEventEmitterEmitted when the user clicks the back to login link

Authentication Store

The library uses a state management system based on Angular's signals to manage authentication state.

Using the AuthStore

You can inject and use the AuthStore directly in your components:

import { Component, inject } from '@angular/core';
import { AuthStore } from 'ngx-supabase-auth';

@Component({
  selector: 'app-my-component',
  template: `
    <div *ngIf="authStore.user()">
      <p>Welcome, {{ authStore.user()?.email }}</p>
    </div>
  `
})
export class MyComponent {
  authStore = inject(AuthStore);
}

AuthStore API

Properties (Signals)

PropertyTypeDescription
userSignal<User | null>Current authenticated user
loadingSignalWhether an authentication action is in progress
errorSignal<string | null>Current authentication error message, if any
isAuthenticatedSignalWhether the user is authenticated

Methods

MethodParametersReturn TypeDescription
signInWithEmailemail: string, password: stringPromiseSign in with email and password
signInWithSocialProviderprovider: SocialAuthProviderPromiseSign in with a social provider
signOut-PromiseSign out the current user
resetPasswordemail: stringPromiseRequest a password reset email
updateProfiledata: UserProfileUpdatePromiseUpdate user profile data
updatePasswordpassword: stringPromiseUpdate user's password

Extending the AuthStore

You can extend the AuthStore by creating your own store that inherits from it:

import { Injectable, inject } from '@angular/core';
import { AuthStore } from 'ngx-supabase-auth';
import { computed } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyExtendedAuthStore extends AuthStore {
  // Add your own properties and methods
  
  // Example: computed signal for user's display name
  readonly displayName = computed(() => {
    const user = this.user();
    return user?.user_metadata?.full_name || user?.email || 'User';
  });
  
  // Example: custom method
  async signInAndLoadUserData(email: string, password: string) {
    await this.signInWithEmail(email, password);
    if (this.isAuthenticated()) {
      // Load additional user data
      await this.loadUserData();
    }
  }
  
  private async loadUserData() {
    // Your custom implementation
  }
}

Then use your extended store instead of the original:

import { Component, inject } from '@angular/core';
import { MyExtendedAuthStore } from './my-extended-auth.store';

@Component({
  selector: 'app-my-component',
  template: `
    <div *ngIf="authStore.isAuthenticated()">
      <p>Welcome, {{ authStore.displayName() }}</p>
    </div>
  `
})
export class MyComponent {
  authStore = inject(MyExtendedAuthStore);
}

Guards

Los guards permiten proteger rutas basándose en el estado de autenticación del usuario.

Auth Guard

Protects routes that require authentication:

import { Routes } from '@angular/router';
import { authGuard } from 'ngx-supabase-auth';

export const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [authGuard],
    // Optional: custom redirect path using data property
    data: {
      authRequiredRedirect: '/custom-login-page'
    }
  }
];

The authGuard can be configured with the following options through the data property:

PropertyTypeDescription
authRequiredRedirectstringCustom URL where users will be redirected if not authenticated. Overrides the global config.

Unauth Guard

Prevents authenticated users from accessing certain routes:

import { Routes } from '@angular/router';
import { unauthGuard } from 'ngx-supabase-auth';

export const routes: Routes = [
  {
    path: 'login',
    component: LoginPageComponent,
    canActivate: [unauthGuard],
    // Optional: custom redirect path using data property
    data: {
      authRedirectIfAuthenticated: '/custom-dashboard'
    }
  }
];

The unauthGuard can be configured with the following options through the data property:

PropertyTypeDescription
authRedirectIfAuthenticatedstringCustom URL where authenticated users will be redirected. Overrides the global config.

Complete Example

Here's a complete example showcasing all components together:

// app.routes.ts
import { Routes } from '@angular/router';
import { LoginPageComponent } from './pages/login-page.component';
import { PasswordResetPageComponent } from './pages/password-reset-page.component';
import { ProfilePageComponent } from './pages/profile-page.component';
import { authGuard, unauthGuard } from 'ngx-supabase-auth';

export const routes: Routes = [
  { 
    path: 'login', 
    component: LoginPageComponent,
    canActivate: [unauthGuard]
  },
  { 
    path: 'forgot-password', 
    component: PasswordResetPageComponent,
    canActivate: [unauthGuard]
  },
  { 
    path: 'profile', 
    component: ProfilePageComponent,
    canActivate: [authGuard]
  },
  { path: '', redirectTo: '/login', pathMatch: 'full' }
];

// login-page.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LoginComponent } from 'ngx-supabase-auth';

@Component({
  selector: 'app-login-page',
  standalone: true,
  imports: [LoginComponent],
  template: `
    <div class="max-w-7xl mx-auto px-4 py-8">
      <sup-login
        title="Welcome Back"
        subtitle="Log in to your account"
        (forgotPassword)="onForgotPassword()"
        (signUp)="onSignUp()"
      ></sup-login>
    </div>
  `
})
export class LoginPageComponent {
  constructor(private router: Router) {}

  onForgotPassword() {
    this.router.navigate(['/forgot-password']);
  }
  
  onSignUp() {
    // Navigate to sign up page or open a signup dialog
    console.log('Sign up clicked');
  }
}

// password-reset-page.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PasswordResetComponent } from 'ngx-supabase-auth';

@Component({
  selector: 'app-password-reset-page',
  standalone: true,
  imports: [PasswordResetComponent],
  template: `
    <div class="max-w-7xl mx-auto px-4 py-8">
      <sup-password-reset
        (backToLogin)="onBackToLogin()"
      ></sup-password-reset>
    </div>
  `
})
export class PasswordResetPageComponent {
  constructor(private router: Router) {}

  onBackToLogin() {
    this.router.navigate(['/login']);
  }
}

// profile-page.component.ts
import { Component } from '@angular/core';
import { ProfileComponent } from 'ngx-supabase-auth';

@Component({
  selector: 'app-profile-page',
  standalone: true,
  imports: [ProfileComponent],
  template: `
    <div class="max-w-7xl mx-auto px-4 py-8">
      <sup-profile
        title="Your Profile"
        subtitle="Manage your account information"
      ></sup-profile>
    </div>
  `
})
export class ProfilePageComponent {}

License

MIT