@propelauth/nextjs 0.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,215 @@
1
+ # PropelAuth Next.js (v13 / AppRouter) Library
2
+
3
+ [PropelAuth](https://www.propelauth.com?utm_source=github&utm_medium=library&utm_campaign=nextjs) is a user management and authentication service for your B2B/multi-tenant applications.
4
+
5
+ This library provides a simple way to integrate your Next.js application with PropelAuth.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @propelauth/nextjs
11
+ ```
12
+
13
+ ## Setup
14
+
15
+ Before you start, make sure you have a PropelAuth account. You can sign up for free at [here](https://auth.propelauth.com).
16
+
17
+ Create a file called `propelauth.ts` in the `src` directory (or your project's root if you prefer) with the following content:
18
+
19
+ ```typescript
20
+ import {initializeAuth} from "@propelauth/nextjs/server";
21
+
22
+ const auth = initializeAuth({
23
+ authUrl: process.env.NEXT_PUBLIC_AUTH_URL,
24
+ redirectUri: process.env.REDIRECT_URI,
25
+ integrationApiKey: process.env.INTEGRATION_API_KEY,
26
+ verifierKey: process.env.VERIFIER_KEY,
27
+ })
28
+
29
+ export const {
30
+ getRouteHandler,
31
+ postRouteHandler,
32
+ getUser,
33
+ getUserOrRedirect,
34
+ validateAccessToken,
35
+ validateAccessTokenOrUndefined,
36
+ authMiddleware,
37
+ } = auth
38
+ ```
39
+
40
+ This file exports all of our server-side functions that you will need to use in your application.
41
+ You can find all the env variables for your application in the PropelAuth Dashboard under **Backend Integration**.
42
+
43
+ ### 1. Set up middleware
44
+
45
+ In your `src/middleware.ts` file, add the following:
46
+
47
+ ```typescript
48
+ import {authMiddleware} from "@/auth";
49
+
50
+ export const middleware = authMiddleware
51
+
52
+ // The middleware is responsible for keeping the user session up to date.
53
+ // It should be called on every request that requires authentication AND /api/auth/.* routes.
54
+ export const config = {
55
+ matcher: [
56
+ // REQUIRED: Match all request paths that start with /api/auth/
57
+ '/api/auth/(.*)',
58
+ // OPTIONAL: Don't match any static assets
59
+ '/((?!_next/static|_next/image|favicon.ico).*)',
60
+ ],
61
+ }
62
+ ```
63
+
64
+ ### 2. Set up routes (AppRouter)
65
+
66
+ In your `src/app/api/auth/[slug]` directory, create a file called `route.ts` with the following content:
67
+
68
+ ```typescript
69
+ import {getRouteHandler, postRouteHandler} from "@/auth";
70
+
71
+ export const GET = getRouteHandler
72
+ export const POST = postRouteHandler
73
+ ```
74
+
75
+ ### 3. Set up AuthProvider (AppRouter)
76
+
77
+ In your root layout, `src/app/layout.tsx`, add the `AuthProvider`:
78
+
79
+ ```typescript jsx
80
+ export default async function RootLayout({children}: {children: React.ReactNode}) {
81
+ return (
82
+ <html lang="en">
83
+ <AuthProvider authUrl={process.env.NEXT_PUBLIC_AUTH_URL}>
84
+ <body className={inter.className}>{children}</body>
85
+ </AuthProvider>
86
+ </html>
87
+ )
88
+ }
89
+ ```
90
+
91
+ ## Usage
92
+
93
+ ### Get the user in Server Components
94
+
95
+ ```tsx
96
+ import {getUser} from "@/auth";
97
+
98
+ const WelcomeMessage = () => {
99
+ const user = getUser()
100
+
101
+ if (user) {
102
+ return <div>Hello {user.firstName}!</div>
103
+ } else {
104
+ return <div>Please log in to be welcomed</div>
105
+ }
106
+ }
107
+ ```
108
+
109
+ ```tsx
110
+ import {getUserOrRedirect} from "@/auth";
111
+
112
+ const WelcomeMessage = () => {
113
+ // If the user is not logged in, they will be redirected to the login page
114
+ const user = getUserOrRedirect()
115
+
116
+ return <div>Hello {user.firstName}!</div>
117
+ }
118
+ ```
119
+
120
+ ### Get the user in Client Components
121
+
122
+ ```tsx
123
+ "use client";
124
+
125
+ import {useUser} from "@propelauth/nextjs/client";
126
+
127
+ const WelcomeMessage = () => {
128
+ const {loading, user} = useUser()
129
+
130
+ if (loading) {
131
+ return <div>Loading...</div>
132
+ } else if (user) {
133
+ return <div>Hello {user.firstName}!</div>
134
+ } else {
135
+ return <div>Please log in to be welcomed</div>
136
+ }
137
+ }
138
+ ```
139
+
140
+ ### Checking organization membership / RBAC
141
+
142
+ Note that this works on both the client and server's `User` object, but the below example is on the server.
143
+
144
+ If you are curious where the organization information comes from, check out our documentation on [organizations](https://docs.propelauth.com/overview/organizations?utm_source=github&utm_medium=library&utm_campaign=nextjs).
145
+ The quick answer is:
146
+ - PropelAuth provides UI for users to create organizations and invite other users to join them.
147
+ - Your users can also create Enterprise SSO/SAML connections to their own Identity Providers (IdPs) so their organization members can log in with their existing work credentials.
148
+ - You can create organizations and add users to them via our APIs or our Dashboard.
149
+
150
+ ```tsx
151
+ // src/app/org/[slug]/page.tsx
152
+ import {getUserOrRedirect} from "@/auth";
153
+
154
+ export default async function AdminOnlyPage({ params }: { params: { slug: string } }) {
155
+ const user = await getUserOrRedirect()
156
+ const org = user.getOrgByName(params.slug);
157
+ const isAdmin = org?.isRole("Admin")
158
+
159
+ if (!isAdmin) {
160
+ return <div>Not found</div>
161
+ } else {
162
+ return <div>Welcome {user.firstName}, Admin of {org?.orgName}</div>
163
+ }
164
+ }
165
+ ```
166
+
167
+ ### Logging out
168
+
169
+ ```tsx
170
+ "use client"
171
+
172
+ import {useLogoutFunction} from "@propelauth/nextjs/client";
173
+
174
+ export default function LogoutButton() {
175
+ const logoutFn = useLogoutFunction()
176
+ return <button onClick={logoutFn}>Logout</button>
177
+ }
178
+ ```
179
+
180
+ ### Logging in / Signing up
181
+
182
+ If you don't want to use redirect functions, you can also use `useHostedPageUrls` which will return the URLs instead of redirecting.
183
+
184
+ ```tsx
185
+ "use client"
186
+
187
+ import {useRedirectFunctions} from "@propelauth/nextjs/client";
188
+
189
+ export default function SignupAndLoginButtons() {
190
+ const {redirectToSignupPage, redirectToLoginPage} = useRedirectFunctions()
191
+ return <>
192
+ <button onClick={redirectToSignupPage}>Sign up</button>
193
+ <button onClick={redirectToLoginPage}>Log in</button>
194
+ </>
195
+ }
196
+ ```
197
+
198
+ ### Redirecting to Account / Org pages
199
+
200
+ PropelAuth also provides you with pre-built account and organization management UIs.
201
+ You can redirect your users to these pages by using the following functions:
202
+
203
+ ```tsx
204
+ "use client"
205
+
206
+ import {useRedirectFunctions} from "@propelauth/nextjs/client";
207
+
208
+ export default function AccountAndOrgButtons() {
209
+ const {redirectToAccountPage, redirectToOrgPage} = useRedirectFunctions()
210
+ return <>
211
+ <button onClick={redirectToAccountPage}>Account</button>
212
+ <button onClick={redirectToOrgPage}>Organization</button>
213
+ </>
214
+ }
215
+ ```
@@ -0,0 +1,95 @@
1
+ import React from 'react';
2
+
3
+ declare class User {
4
+ userId: string;
5
+ orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo;
6
+ email: string;
7
+ firstName?: string;
8
+ lastName?: string;
9
+ username?: string;
10
+ legacyUserId?: string;
11
+ impersonatorUserId?: string;
12
+ constructor(userId: string, email: string, orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo, firstName?: string, lastName?: string, username?: string, legacyUserId?: string, impersonatorUserId?: string);
13
+ getOrg(orgId: string): OrgMemberInfo | undefined;
14
+ getOrgByName(orgName: string): OrgMemberInfo | undefined;
15
+ getOrgs(): OrgMemberInfo[];
16
+ isImpersonating(): boolean;
17
+ static fromJSON(json: string): User;
18
+ }
19
+ type OrgIdToOrgMemberInfo = {
20
+ [orgId: string]: OrgMemberInfo;
21
+ };
22
+ declare class OrgMemberInfo {
23
+ orgId: string;
24
+ orgName: string;
25
+ orgMetadata: {
26
+ [key: string]: any;
27
+ };
28
+ urlSafeOrgName: string;
29
+ private userAssignedRole;
30
+ private userInheritedRolesPlusCurrentRole;
31
+ private userPermissions;
32
+ constructor(orgId: string, orgName: string, orgMetadata: {
33
+ [key: string]: any;
34
+ }, urlSafeOrgName: string, userAssignedRole: string, userInheritedRolesPlusCurrentRole: string[], userPermissions: string[]);
35
+ isRole(role: string): boolean;
36
+ isAtLeastRole(role: string): boolean;
37
+ hasPermission(permission: string): boolean;
38
+ hasAllPermissions(permissions: string[]): boolean;
39
+ static fromJSON(json: string): OrgMemberInfo;
40
+ get assignedRole(): string;
41
+ get inheritedRolesPlusCurrentRole(): string[];
42
+ get permissions(): string[];
43
+ }
44
+
45
+ type AuthProviderProps = {
46
+ authUrl: string;
47
+ children?: React.ReactNode;
48
+ };
49
+ declare const AuthProvider: (props: AuthProviderProps) => React.JSX.Element;
50
+
51
+ type UseUserLoading = {
52
+ loading: true;
53
+ isLoggedIn: never;
54
+ user: never;
55
+ };
56
+ type UseUserLoggedIn = {
57
+ loading: false;
58
+ isLoggedIn: true;
59
+ user: User;
60
+ };
61
+ type UseUserNotLoggedIn = {
62
+ loading: false;
63
+ isLoggedIn: false;
64
+ user: undefined;
65
+ };
66
+ type UseUser = UseUserLoading | UseUserLoggedIn | UseUserNotLoggedIn;
67
+ declare function useUser(): UseUser;
68
+
69
+ declare function useHostedPageUrls(): {
70
+ getLoginPageUrl: () => string;
71
+ getSignupPageUrl: () => string;
72
+ getAccountPageUrl: () => string;
73
+ getOrgPageUrl: (orgId?: string | undefined) => string;
74
+ getCreateOrgPageUrl: () => string;
75
+ getSetupSAMLPageUrl: (orgId: string) => string;
76
+ };
77
+
78
+ declare function useLogoutFunction(): () => Promise<void>;
79
+
80
+ declare function useRedirectFunctions(): {
81
+ redirectToSignupPage: () => void;
82
+ redirectToLoginPage: () => void;
83
+ redirectToAccountPage: () => void;
84
+ redirectToOrgPage: (orgId?: string | undefined) => void;
85
+ redirectToCreateOrgPage: () => void;
86
+ };
87
+ interface RedirectProps {
88
+ children?: React.ReactNode;
89
+ }
90
+ declare function RedirectToSignup({ children }: RedirectProps): React.JSX.Element;
91
+ declare function RedirectToLogin({ children }: RedirectProps): React.JSX.Element;
92
+
93
+ declare function useRefreshAuth(): () => Promise<User | undefined>;
94
+
95
+ export { AuthProvider, AuthProviderProps, OrgIdToOrgMemberInfo, OrgMemberInfo, RedirectProps, RedirectToLogin, RedirectToSignup, UseUser, UseUserLoading, UseUserLoggedIn, UseUserNotLoggedIn, User, useHostedPageUrls, useLogoutFunction, useRedirectFunctions, useRefreshAuth, useUser };