Skip to content

Commit

Permalink
add next auth addon
Browse files Browse the repository at this point in the history
  • Loading branch information
OrJDev committed Dec 17, 2022
1 parent 9fd3662 commit 0f990d7
Show file tree
Hide file tree
Showing 19 changed files with 311 additions and 101 deletions.
3 changes: 3 additions & 0 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@ npm create jd-app@latest

## Addons

All addons are optional, you may select some, you may select all and you may select none.

- [Prisma](https://github.com/prisma/prisma)
- [tRPC](https://github.com/trpc/trpc)
- [TailwindCSS](https://github.com/tailwindlabs/tailwindcss)
- [UnoCSS](https://github.com/unocss/unocss)
- [SolidAuth](https://github.com/orjdev/solid-auth)
- [Next Auth](https://github.com/orjdev/auth-solid)
- [Upstash Ratelimit](https://github.com/upstash/ratelimit)

#### Preview
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-jd-app",
"version": "1.0.98",
"version": "1.0.99",
"main": "dist/index.js",
"scripts": {
"test": "ts-node -r tsconfig-paths/register src",
Expand Down
20 changes: 15 additions & 5 deletions src/helpers/installer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,15 @@ export async function getCtxWithInstallers(
let optInstallers = installers.filter(
(pkg) => !validInstallers.includes(pkg)
);
const opts = ["TailwindCSS", "UnoCSS"];
const opts = [
["TailwindCSS", "UnoCSS"],
["SolidAuth", "NextAuth"],
];
for (const opt of opts) {
if (validInstallers.includes(opt)) {
optInstallers = optInstallers.filter((pkg) => !opts.includes(pkg));
for (const op of opt) {
if (validInstallers.includes(op)) {
optInstallers = optInstallers.filter((pkg) => !opt.includes(pkg));
}
}
}
const newPkgs = (
Expand All @@ -126,8 +131,12 @@ export async function getCtxWithInstallers(
message: "What should we use for this app?",
choices: optInstallers,
validate: (ans: string[]) => {
if (ans.includes("TailwindCSS") && ans.includes("UnoCSS")) {
return "You can't use both TailwindCSS and UnoCSS at the same time";
for (const opt of opts) {
if (opt.every((o) => ans.includes(o))) {
return `You can't use both ${opt
.map((o) => chalk.blue(o))
.join(" and ")} at the same time`;
}
}
return true;
},
Expand All @@ -148,5 +157,6 @@ export async function getCtxWithInstallers(
return {
...ctx,
installers: pkgs,
ssr: !pkgs.includes("tRPC"), // currently sq doesn't support ssr
};
}
4 changes: 4 additions & 0 deletions src/helpers/packages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ const packages = {
// solid auth
"@solid-auth/core": "^0.0.1",
"@solid-auth/socials": "^0.0.2",
// next auth
"@solid-auth/next": "^0.0.17",
"@auth/core": "^0.1.4",
"@next-auth/prisma-adapter": "^1.0.5", // currently not supported
// upstash ratelimit
"@upstash/ratelimit": "^0.1.5",
"@upstash/redis": "^1.18.0",
Expand Down
110 changes: 67 additions & 43 deletions src/helpers/utils/getIndexPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ const getIndexPage: IUtil = (ctx) => {
const uswTW = ctx.installers.includes("TailwindCSS");
const useStyles = useUno || uswTW;
const useTRPC = ctx.installers.includes("tRPC");
const useAuth = ctx.installers.includes("SolidAuth");
const useNextAuth = ctx.installers.includes("NextAuth");
const useSolidAuth = ctx.installers.includes("SolidAuth");
const useAuth = useNextAuth || useSolidAuth;
const shouldUsePrisma =
ctx.installers.includes("Prisma") && !useTRPC && !useAuth;
const withStyles = getStyle(
Expand All @@ -20,38 +22,49 @@ const getIndexPage: IUtil = (ctx) => {
} mx-3 my-3 rounded-lg w-56 p-2.5 text-white font-bold flex items-center justify-center`
);

const innerRes = getRes(useAuth, shouldUsePrisma, useTRPC);
const loginKey = useSolidAuth ? "discord" : "github";
const innerRes = getRes(useNextAuth, useSolidAuth, shouldUsePrisma, useTRPC);
const innerContent = getContent(
withStyles,
useAuth,
useSolidAuth,
useNextAuth,
shouldUsePrisma,
loginKey,
useTRPC,
withButtonStyles
);
return `import { type ParentComponent${
return `import { type VoidComponent${
useTRPC || shouldUsePrisma || useAuth ? ", Switch, Match" : ""
}${shouldUsePrisma ? ", createResource" : ""} } from "solid-js";
import { Title${useAuth ? ", useRouteData" : ""} } from "solid-start";${
useTRPC ? '\nimport { trpc } from "~/utils/trpc";' : ""
}${
useAuth
? `\nimport { createServerData$ } from "solid-start/server";
import { authenticator } from "~/server/auth";
useAuth ? `\nimport { createServerData$ } from "solid-start/server";` : ""
}${
useSolidAuth
? `\nimport { authenticator } from "~/server/auth";
import { authClient } from "~/utils/auth";`
: ""
}${
useNextAuth
? `\nimport { getSession } from "@solid-auth/next/session";\nimport { authOpts } from "./api/auth/[...solidauth]";\nimport { signIn, signOut } from "@solid-auth/next/utils";`
: ""
}
${
useAuth
? `\nexport const routeData = () => {
return createServerData$(async (_, { request }) => {
const user = await authenticator.isAuthenticated(request);
return user;
return await ${
useSolidAuth
? "authenticator.isAuthenticated(request)"
: "getSession(request, authOpts)"
};
});
};
`
: ""
}
const Home: ParentComponent = () => {${innerRes}
const Home: VoidComponent = () => {${innerRes}
return (
<>
<Title>Home</Title>
Expand All @@ -69,20 +82,23 @@ export default Home;
export default getIndexPage;

const getRes = (
useAuth: boolean,
useNextAuth: boolean,
useSolidAuth: boolean,
shouldUsePrisma: boolean,
useTRPC: boolean
) => {
if (useAuth && useTRPC) {
return `\n const user = useRouteData<typeof routeData>();
if ((useNextAuth || useSolidAuth) && useTRPC) {
return `\n const ${
useSolidAuth ? "user" : "session"
} = useRouteData<typeof routeData>();
const res = trpc.secret.useQuery(undefined, {
get enabled() {
return !!user();
return ${useSolidAuth ? "!!user()" : "!!session()?.user"};
},
});
`;
}
if (useAuth) {
if (useNextAuth || useSolidAuth) {
return `\n const res = useRouteData<typeof routeData>();\n`;
}
return shouldUsePrisma
Expand All @@ -96,11 +112,15 @@ const getRes = (

const getContent = (
withStyles: string,
useAuth: boolean,
useSolidAuth: boolean,
useNextAuth: boolean,
shouldUsePrisma: boolean,
loginKey: string,
useTRPC: boolean,
withButtonStyles: string
) => {
const useAuth = useNextAuth || useSolidAuth;
const key = useSolidAuth ? "user" : "session";
if (useAuth && !useTRPC) {
return ` <Switch
fallback={
Expand All @@ -116,32 +136,32 @@ const getContent = (
<Switch
fallback={
<button
onClick={() =>
authClient.login("discord", {
onClick={() => ${
useSolidAuth
? `authClient.login("${loginKey}", {
successRedirect: "/",
failureRedirect: "/",
})
}${
withButtonStyles.length
? `\n ${withButtonStyles}`
: ""
}
})`
: `signIn("${loginKey}")`
}}${
withButtonStyles.length ? `\n ${withButtonStyles}` : ""
}
>
Login with discord
Login with ${loginKey}
</button>
}
>
<Match when={res()}>
<button
onClick={() =>
authClient.logout({
onClick={() => ${
useSolidAuth
? `authClient.logout({
redirectTo: "/",
})
}${
withButtonStyles.length
? `\n ${withButtonStyles}`
: ""
}
})`
: "signOut()"
}}${
withButtonStyles.length ? `\n ${withButtonStyles}` : ""
}
>
Logout
</button>
Expand Down Expand Up @@ -174,30 +194,34 @@ const getContent = (
? `\n <Switch
fallback={
<button
onClick={() =>
authClient.login("discord", {
onClick={() => ${
useSolidAuth
? `authClient.login("${loginKey}", {
successRedirect: "/",
failureRedirect: "/",
})
})}`
: `signIn("${loginKey}")}`
}${
withButtonStyles.length
? `\n ${withButtonStyles}`
: ""
}
>
Login with discord
Login with ${loginKey}
</button>
}
>
<Match when={user.loading}>
<h1>Loading user</h1>
<Match when={${key}.loading}>
<h1>Loading ${key}</h1>
</Match>
<Match when={user()}>
<Match when={${key}()}>
<button
onClick={() =>
authClient.logout({
onClick={() => ${
useSolidAuth
? `authClient.logout({
redirectTo: "/",
})
})}`
: "signOut()}"
}${
withButtonStyles.length
? `\n ${withButtonStyles}`
Expand Down
15 changes: 5 additions & 10 deletions src/helpers/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@ import { ICtx, IUtil } from "~types";

export const getViteConfig: IUtil = (ctx) => {
const useUno = ctx.installers.includes("UnoCSS");
const shouldUseSSR = !ctx.installers.includes("tRPC");
const getPlugins = () => {
if (useUno && ctx.vercel) {
return `[
solid({ ssr: ${shouldUseSSR}, adapter: vercel({ edge: false }) }),
solid({ ssr: ${ctx.ssr}, adapter: vercel({ edge: false }) }),
UnoCSS(),
]`;
} else if (useUno) {
return `[solid({ ssr: ${shouldUseSSR} }), UnoCSS()]`;
return `[solid({ ssr: ${ctx.ssr} }), UnoCSS()]`;
} else if (ctx.vercel) {
return `[solid({ ssr: ${shouldUseSSR}, adapter: vercel({ edge: false }) })]`;
return `[solid({ ssr: ${ctx.ssr}, adapter: vercel({ edge: false }) })]`;
} else {
return `[solid({ ssr: ${shouldUseSSR} })]`;
return `[solid({ ssr: ${ctx.ssr} })]`;
}
};
const plugins = getPlugins();
Expand All @@ -41,11 +40,7 @@ export default defineConfig(() => {
};

export const modifyConfigIfNeeded = async (ctx: ICtx) => {
if (
ctx.vercel ||
ctx.installers.includes("UnoCSS") ||
ctx.installers.includes("tRPC")
) {
if (ctx.vercel || ctx.installers.includes("UnoCSS") || !ctx.ssr) {
await fs.writeFile(
path.join(ctx.userDir, "vite.config.ts"),
getViteConfig(ctx)
Expand Down
26 changes: 26 additions & 0 deletions src/installers/NextAuth/files/handler.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {
SolidAuth,
type ISolidAuthHandlerOpts,
} from "@solid-auth/next/handler";
import Github from "@auth/core/providers/github";
import { serverEnv } from "~/env/server";
import { type APIEvent } from "solid-start";

export const authOpts: ISolidAuthHandlerOpts = {
providers: [
Github({
clientId: serverEnv.GITHUB_ID,
clientSecret: serverEnv.GITHUB_SECRET,
}),
],
debug: false,
};

const handler = SolidAuth(authOpts);

export async function GET(event: APIEvent) {
return await handler(event);
}
export async function POST(event: APIEvent) {
return await handler(event);
}
29 changes: 29 additions & 0 deletions src/installers/NextAuth/files/prisma-handler.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {
SolidAuth,
type ISolidAuthHandlerOpts,
} from "@solid-auth/next/handler";
import Github from "@auth/core/providers/github";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { serverEnv } from "~/env/server";
import { type APIEvent } from "solid-start";
import { prisma } from "~/server/db/client";

export const authOpts: ISolidAuthHandlerOpts = {
adapter: PrismaAdapter(prisma),
providers: [
GitHub({
clientId: serverEnv.GITHUB_ID,
clientSecret: serverEnv.GITHUB_SECRET,
}),
],
debug: false,
};

const handler = SolidAuth(authOpts);

export async function GET(event: APIEvent) {
return await handler(event);
}
export async function POST(event: APIEvent) {
return await handler(event);
}
Loading

0 comments on commit 0f990d7

Please sign in to comment.