New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@bricco/auth

Package Overview
Dependencies
Maintainers
0
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bricco/auth

  • 0.2.16-alpha.9
  • npm
  • Socket score

Version published
Weekly downloads
35
decreased by-50%
Maintainers
0
Weekly downloads
 
Created
Source

How to implement

  • In next.config.ts, add @bricco/auth as transpiled package.
const transpilePackages = [
  '@bricco/auth',
  ...
];
  • Create a middleware.ts file (or extend the current file)
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/services/auth';

export async function middleware(request: NextRequest ): Promise<NextResponse | void> {
  const url = request.nextUrl.clone();

  // Only validate the user if the request is not for a static asset
  // Add more paths here which should ignore auth
  if (!url.pathname.startsWith('/_next/static')) {
    const user = await auth();
    if (!user && url.pathname !== '/admin/login' && !url.pathname.startsWith('/api/auth')) {
      console.info(`No user found, redirecting from ${url.pathname} to /admin/login`);
      url.pathname = '/admin/login';
      return NextResponse.redirect(url);
    }
  }
  return NextResponse.next();
}
  • Create a @/services/auth file
import { createAuth, type Credentials, encodePassword, VercelKVAdapter } from '@bricco/auth';
import { z } from 'zod';

// Optional to extend credentials
export type CredentialsWith2FA = Credentials & {
  twoFactorAuth?: string;
};

// The user model for the JWT cookie
type UserModel = {
  _id: string;
  email: string;
  company: string;
};

// Parsing schema for login data
export const signInSchema = z.object({
  email: z.string().email(),
  password: z
    .string()
    .min(1)
    .transform(value => encodePassword(value)),
  twoFactorAuth: z.string().optional(),
});

// Authorize function
const authorize = async (credentials: Partial<CredentialsWith2FA>): Promise<Partial<UserModel> | null> => {
  const loginUser = await signInSchema.parseAsync(credentials);
  if (!loginUser) {
    throw new Error('User not found.');
  }

  // Do your auth here
  const user = { _id: '123', email: loginUser.email, company: 'Bricco', twoVerified: false };

  // Return the user
  return { _id: user._id, email: user.email, company: user.company };
};

export const { signIn, auth, handlers } = createAuth<CredentialsWith2FA, UserModel>({
  authorize,
  cookieName: 'nameofcookie',
  adapter: VercelKVAdapter({
    cookieName: 'nameofcookie',
  }),
});
  • Create optional actions (@services/action.ts)
'use server';

import { signIn } from './auth';

/**
 * Login via server action
 * @param data FormData with email and password
 */
export const login = async (data: FormData): Promise<void> => {
  await signIn('credentials', {
    email: data.get('email') as string,
    password: data.get('password') as string,
    redirectTo: '/admin',
  });
};
  • Create optinal login form (/admin/login/page.tsx)
'use client';

import { login } from '@/services/action';

export default function Login(): JSX.Element {
  return (
    <div>
      <h1>Login</h1>
      <form action={login}>
        <input name="email" defaultValue="test@email.com" />
        <input name="password" type="password" defaultValue="randompassword" />
        <input type="submit" value="Login" />
      </form>
    </div>
  );
}
  • The package includes a AuthProvider is you want to access the session in client components (/admin/layout.tsx)
  <AuthProvider session={(await auth()) as any} cookieName="nameofcookie">{children}</AuthProvider>

FAQs

Package last updated on 13 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc