Skip to content

Commit

Permalink
tidy components #1
Browse files Browse the repository at this point in the history
  • Loading branch information
nelsonic committed Jul 13, 2024
1 parent 8f692df commit 8271442
Show file tree
Hide file tree
Showing 6 changed files with 214 additions and 151 deletions.
22 changes: 19 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one
- [Run the Tests!](#run-the-tests)
- [Build It!](#build-it)
- [_Please_ star the repo! ⭐️](#please-star-the-repo-️)
- [Troubleshooting](#troubleshooting)


# Why? 🤷‍♀️
Expand Down Expand Up @@ -127,10 +128,17 @@ npm i

### 3. Create Environment Variables

Copy the `.env.local-example` file and create your `.env` file:
Copy the `.env.local-example` file and create your `.env.local` file:

```sh
cp .env.local-example .env
cp .env.local-example .env.local
```

Add the necessary environment variables to your `.env.local` file,
e.g:

```sh

```


Expand Down Expand Up @@ -162,4 +170,12 @@ See:
If you find this repo/tutorial useful,
please star it on GitHub, so that we know! ⭐

Thank you! 🙏
Thank you! 🙏


## Troubleshooting

```sh
[auth][error] MissingSecret: Please define a `secret`..
Read more at https://errors.authjs.dev#missingsecret
```
2 changes: 1 addition & 1 deletion src/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
import { handlers } from "@/src/auth" // Referring to the auth.ts we just created
import { handlers } from "@/src/auth" // Referring to the auth.ts just created
export const { GET, POST } = handlers
4 changes: 3 additions & 1 deletion src/components/LoginOrUserInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export default function LoginOrUserInfo({ session } : Readonly<{session: Default
</div>
);
} else {
return <button onClick={() => signIn()}>SIGN IN</button>;
return <button onClick={() => signIn()}
className="nx-bg-blue-500 hover:nx-bg-blue-700 nx-text-white py-2 px-4 nx-rounded">
SIGN IN</button>;
}
}
33 changes: 21 additions & 12 deletions src/generatePrivateRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ import { PrivateRoutes, MetaJson } from './types';


/**
* This function looks at the file system under a path and goes through each `_meta.json` looking for private routes recursively.
* It is expecting the `_meta.json` values of keys to have a property called "private" to consider the route as private for specific roles.
* If a parent is private, all the children are private as well. The children inherit the roles of their direct parent.
* This function looks at the file system under a path
* and goes through each `_meta.json` looking for private routes recursively.
* It is expecting the `_meta.json` values of keys to have a property
* called "private" to consider the route as private for specific roles.
* If a parent is private, all the children are private as well.
* The children inherit the roles of their direct parent.
* @param pagesDir path to recursively look for.
* @returns map of private routes as key and array of roles that are permitted to access the route.
* @returns map of private routes as key and array of roles that
* are permitted to access the route.
*/
export function getPrivateRoutes(pagesDir: string): PrivateRoutes {
let privateRoutes: PrivateRoutes = {};
Expand All @@ -19,7 +23,9 @@ export function getPrivateRoutes(pagesDir: string): PrivateRoutes {
const metaFiles = globSync(path.join(pagesDir, "**/_meta.json"));

// Variable to keep track if parent is private on nested routes and its role
const rootPrivateSettings: { [key: string]: { private: boolean; roles: string[] } } = {};
const rootPrivateSettings: {
[key: string]: { private: boolean; roles: string[] }
} = {};

// Iterate over the found meta files
for (const file of metaFiles) {
Expand Down Expand Up @@ -48,20 +54,21 @@ export function getPrivateRoutes(pagesDir: string): PrivateRoutes {
} else {
// Check if the parent folder is private and inherit roles
const parentDir = path.resolve(dir, "..");
if (rootPrivateSettings[parentDir] && rootPrivateSettings[parentDir].private) {
if (rootPrivateSettings[parentDir] &&
rootPrivateSettings[parentDir].private) {
const parentRoles = rootPrivateSettings[parentDir].roles;
privateRoutes[route] = parentRoles;
}
}
}
}

// Now let's just do a second pass to clean-up possible unwanted/invalid routes
// Second pass to clean-up possible unwanted/invalid routes
for (const route of Object.keys(privateRoutes)) {
const fullPath = path.join(pagesDir, route);
const lastSegment = route.split("/").pop();

// Remove separators or any route that doesn't correspond to an existing file/directory
// Remove separators or any route that doesn't match existing file/directory
if (lastSegment === "---") {
delete privateRoutes[route];
continue;
Expand All @@ -80,8 +87,8 @@ export function getPrivateRoutes(pagesDir: string): PrivateRoutes {
// - - - - - - - - - - - - - - - - - - - - - - -
// `middleware.ts` is changed by executing the code below.

const CONST_VARIABLE_NAME = "privateRoutesMap"; // Name of the constant inside `middleware.ts` to be manipulated
const DIRECTORY = "pages"; // Directory to look for the routes (should be `pages`, according to Nextra's file system)
const CONST_VARIABLE_NAME = "privateRoutesMap"; // const inside `middleware.ts`
const DIRECTORY = "pages"; // Dir to look for the routes (should be `pages`, according to Nextra's file system)

export function changeMiddleware() {

Expand All @@ -91,15 +98,17 @@ export function changeMiddleware() {

// Initialize the project and source file
const project = new Project();
const sourceFile = project.addSourceFileAtPath(path.resolve(__dirname, "middleware.ts"));
const sourceFile = project.addSourceFileAtPath(
path.resolve(__dirname, "middleware.ts")
);

// Find the variable to replace and change it's declaration
const variable = sourceFile.getVariableDeclaration(CONST_VARIABLE_NAME);
if (variable) {
variable.setInitializer(JSON.stringify(privateRoutes));
sourceFile.saveSync();
} else {
console.error("Variable not found in `middleware.ts`. File wasn't changed.");
console.error("Variable not found in `middleware.ts`. File not changed.");
}
}

Expand Down
8 changes: 1 addition & 7 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,7 @@ import { NextResponse } from "next/server";
// It is manipulated before the project is compiled so it knows all the routes that are private
// according to what is defined in "_meta.json" files.
// See `package.json` and the `private-route-gen` script for context.
const privateRoutesMap: any = {
"/reference_api":["user"],
"/reference_api/about":["user"],
"/reference_api/person":["user"],
"/reference_api/mega_private":["cant_enter"],
"/reference_api/mega_private/hello":["cant_enter"]
};
const privateRoutesMap: any = {"/reference_api":["user"],"/reference_api/about":["user"],"/reference_api/person":["user"],"/reference_api/mega_private":["cant_enter"],"/reference_api/mega_private/hello":["cant_enter"]};

export default auth(async (req, ctx) => {
const currentPath = req.nextUrl.pathname;
Expand Down
Loading

0 comments on commit 8271442

Please sign in to comment.