mirror of
https://github.com/ajnart/homarr.git
synced 2026-02-26 08:20:56 +01:00
feat: add credentials authentication (#1)
This commit is contained in:
@@ -9,13 +9,7 @@ DB_URL='FULL_PATH_TO_YOUR_SQLITE_DB_FILE'
|
||||
|
||||
# @see https://next-auth.js.org/configuration/options#nextauth_url
|
||||
AUTH_URL='http://localhost:3000'
|
||||
AUTH_REDIRECT_PROXY_URL="http://localhost:3001/api"
|
||||
|
||||
# You can generate the secret via 'openssl rand -base64 32' on Unix
|
||||
# @see https://next-auth.js.org/configuration/options#secret
|
||||
AUTH_SECRET='supersecret'
|
||||
|
||||
# Preconfigured Discord OAuth provider, works out-of-the-box
|
||||
# @see https://next-auth.js.org/providers/discord
|
||||
AUTH_DISCORD_ID=''
|
||||
AUTH_DISCORD_SECRET=''
|
||||
|
||||
218
README.md
218
README.md
@@ -1,75 +1,5 @@
|
||||
# create-t3-turbo
|
||||
|
||||
> **Note**
|
||||
> Due to high demand, this repo now uses the `app` directory with some new experimental features. If you want to use the more traditional `pages` router, [check out the repo before the update](https://github.com/t3-oss/create-t3-turbo/tree/414aff131ca124573e721f3779df3edb64989fd4).
|
||||
|
||||
> **Note**
|
||||
> OAuth deployments are now working for preview deployments. Read [deployment guide](https://github.com/t3-oss/create-t3-turbo#auth-proxy) and [check out the source](./apps/auth-proxy) to learn more!
|
||||
|
||||
## Installation
|
||||
|
||||
There are two ways of initializing an app using the `create-t3-turbo` starter. You can either use this repository as a template:
|
||||
|
||||

|
||||
|
||||
or use Turbo's CLI to init your project (use PNPM as package manager):
|
||||
|
||||
```bash
|
||||
npx create-turbo@latest -e https://github.com/t3-oss/create-t3-turbo
|
||||
```
|
||||
|
||||
## About
|
||||
|
||||
Ever wondered how to migrate your T3 application into a monorepo? Stop right here! This is the perfect starter repo to get you running with the perfect stack!
|
||||
|
||||
It uses [Turborepo](https://turborepo.org) and contains:
|
||||
|
||||
```text
|
||||
.github
|
||||
└─ workflows
|
||||
└─ CI with pnpm cache setup
|
||||
.vscode
|
||||
└─ Recommended extensions and settings for VSCode users
|
||||
apps
|
||||
├─ auth-proxy
|
||||
| ├─ Nitro server to proxy OAuth requests in preview deployments
|
||||
| └─ Uses Auth.js Core
|
||||
├─ expo
|
||||
| ├─ Expo SDK 49
|
||||
| ├─ React Native using React 18
|
||||
| ├─ Navigation using Expo Router
|
||||
| ├─ Tailwind using Nativewind
|
||||
| └─ Typesafe API calls using tRPC
|
||||
└─ next.js
|
||||
├─ Next.js 14
|
||||
├─ React 18
|
||||
├─ Tailwind CSS
|
||||
└─ E2E Typesafe API Server & Client
|
||||
packages
|
||||
├─ api
|
||||
| └─ tRPC v10 router definition
|
||||
├─ auth
|
||||
| └─ Authentication using next-auth. **NOTE: Only for Next.js app, not Expo**
|
||||
└─ db
|
||||
└─ Typesafe db calls using Drizzle & Planetscale
|
||||
tooling
|
||||
├─ eslint
|
||||
| └─ shared, fine-grained, eslint presets
|
||||
├─ prettier
|
||||
| └─ shared prettier configuration
|
||||
├─ tailwind
|
||||
| └─ shared tailwind configuration
|
||||
└─ typescript
|
||||
└─ shared tsconfig you can extend from
|
||||
```
|
||||
|
||||
> In this template, we use `@alparr` as a placeholder for package names. As a user, you might want to replace it with your own organization or project name. You can use find-and-replace to change all the instances of `@alparr` to something like `@my-company` or `@project-name`.
|
||||
|
||||
## Quick Start
|
||||
|
||||
> **Note**
|
||||
> The [db](./packages/db) package is preconfigured to use PlanetScale and is **edge-bound** with the [database.js](https://github.com/planetscale/database-js) driver. If you're using something else, make the necesary modifications to the [schema](./packages/db/schema) as well as the [client](./packages/db/index.ts) and the [drizzle config](./packages/db/drizzle.config.ts). If you want to switch to non-edge database driver, remove `export const runtime = "edge";` [from all pages and api routes](https://github.com/t3-oss/create-t3-turbo/issues/634#issuecomment-1730240214).
|
||||
|
||||
To get it running, follow the steps below:
|
||||
|
||||
### 1. Setup dependencies
|
||||
@@ -86,33 +16,15 @@ cp .env.example .env
|
||||
pnpm db:push
|
||||
```
|
||||
|
||||
### 2. Configure Expo `dev`-script
|
||||
### 2. Start application
|
||||
|
||||
#### Use iOS Simulator
|
||||
Run `pnpm dev` at the project root folder to start the application.
|
||||
|
||||
1. Make sure you have XCode and XCommand Line Tools installed [as shown on expo docs](https://docs.expo.dev/workflow/ios-simulator).
|
||||
> **Note**
|
||||
> The authentication will currently fail with the message `TypeError: Failed to construct 'URL': Invalid base URL`. This issue will be resolved in the next next-auth beta release. You can track the issue [here](https://github.com/nextauthjs/next-auth/issues/9279).
|
||||
|
||||
> **NOTE:** If you just installed XCode, or if you have updated it, you need to open the simulator manually once. Run `npx expo start` in the root dir, and then enter `I` to launch Expo Go. After the manual launch, you can run `pnpm dev` in the root directory.
|
||||
|
||||
```diff
|
||||
+ "dev": "expo start --ios",
|
||||
```
|
||||
|
||||
2. Run `pnpm dev` at the project root folder.
|
||||
|
||||
#### Use Android Emulator
|
||||
|
||||
1. Install Android Studio tools [as shown on expo docs](https://docs.expo.dev/workflow/android-studio-emulator).
|
||||
|
||||
2. Change the `dev` script at `apps/expo/package.json` to open the Android emulator.
|
||||
|
||||
```diff
|
||||
+ "dev": "expo start --android",
|
||||
```
|
||||
|
||||
3. Run `pnpm dev` at the project root folder.
|
||||
|
||||
> **TIP:** It might be easier to run each app in separate terminal windows so you get the logs from each app separately. This is also required if you want your terminals to be interactive, e.g. to access the Expo QR code. You can run `pnpm --filter expo dev` and `pnpm --filter nextjs dev` to run each app in a separate terminal window.
|
||||
You can find the initial account creation page at [http://localhost:3000/init/user](http://localhost:3000/init/user).
|
||||
After that you can login at [http://localhost:3000/auth/login](http://localhost:3000/auth/login).
|
||||
|
||||
### 3. When it's time to add a new package
|
||||
|
||||
@@ -120,124 +32,6 @@ To add a new package, simply run `pnpm turbo gen init` in the monorepo root. Thi
|
||||
|
||||
The generator sets up the `package.json`, `tsconfig.json` and a `index.ts`, as well as configures all the necessary configurations for tooling around your package such as formatting, linting and typechecking. When the package is created, you're ready to go build out the package.
|
||||
|
||||
## FAQ
|
||||
|
||||
### Does the starter include Solito?
|
||||
|
||||
No. Solito will not be included in this repo. It is a great tool if you want to share code between your Next.js and Expo app. However, the main purpose of this repo is not the integration between Next.js and Expo — it's the codesplitting of your T3 App into a monorepo. The Expo app is just a bonus example of how you can utilize the monorepo with multiple apps but can just as well be any app such as Vite, Electron, etc.
|
||||
|
||||
Integrating Solito into this repo isn't hard, and there are a few [offical templates](https://github.com/nandorojo/solito/tree/master/example-monorepos) by the creators of Solito that you can use as a reference.
|
||||
|
||||
### What auth solution should I use instead of Next-Auth.js for Expo?
|
||||
|
||||
I've left this kind of open for you to decide. Some options are [Clerk](https://clerk.dev), [Supabase Auth](https://supabase.com/docs/guides/auth), [Firebase Auth](https://firebase.google.com/docs/auth/) or [Auth0](https://auth0.com/docs). Note that if you're dropping the Expo app for something more "browser-like", you can still use Next-Auth.js for those. [See an example in a Plasmo Chrome Extension here](https://github.com/t3-oss/create-t3-turbo/tree/chrome/apps/chrome).
|
||||
|
||||
The Clerk.dev team even made an [official template repository](https://github.com/clerkinc/t3-turbo-and-clerk) integrating Clerk.dev with this repo.
|
||||
|
||||
During Launch Week 7, Supabase [announced their fork](https://supabase.com/blog/launch-week-7-community-highlights#t3-turbo-x-supabase) of this repo integrating it with their newly announced auth improvements. You can check it out [here](https://github.com/supabase-community/create-t3-turbo).
|
||||
|
||||
### Does this pattern leak backend code to my client applications?
|
||||
|
||||
No, it does not. The `api` package should only be a production dependency in the Next.js application where it's served. The Expo app, and all other apps you may add in the future, should only add the `api` package as a dev dependency. This lets you have full typesafety in your client applications, while keeping your backend code safe.
|
||||
|
||||
If you need to share runtime code between the client and server, such as input validation schemas, you can create a separate `shared` package for this and import it on both sides.
|
||||
|
||||
## Deployment
|
||||
|
||||
### Next.js
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
> **Note**
|
||||
> Please note that the Next.js application with tRPC must be deployed in order for the Expo app to communicate with the server in a production environment.
|
||||
|
||||
#### Deploy to Vercel
|
||||
|
||||
Let's deploy the Next.js application to [Vercel](https://vercel.com). If you've never deployed a Turborepo app there, don't worry, the steps are quite straightforward. You can also read the [official Turborepo guide](https://vercel.com/docs/concepts/monorepos/turborepo) on deploying to Vercel.
|
||||
|
||||
1. Create a new project on Vercel, select the `apps/nextjs` folder as the root directory. Vercel's zero-config system should handle all configurations for you.
|
||||
|
||||
2. Add your `DATABASE_URL` environment variable.
|
||||
|
||||
3. Done! Your app should successfully deploy. Assign your domain and use that instead of `localhost` for the `url` in the Expo app so that your Expo app can communicate with your backend when you are not in development.
|
||||
|
||||
### Auth Proxy
|
||||
|
||||
The auth proxy is a Nitro server that proxies OAuth requests in preview deployments. This is required for the Next.js app to be able to authenticate users in preview deployments. The auth proxy is not used for OAuth requests in production deployments. To get it running, it's easiest to use Vercel Edge functions. See the [Nitro docs](https://nitro.unjs.io/deploy/providers/vercel#vercel-edge-functions) for how to deploy Nitro to Vercel.
|
||||
|
||||
Then, there are some environment variables you need to set in order to get OAuth working:
|
||||
|
||||
- For the Next.js app, set `AUTH_REDIRECT_PROXY_URL` to the URL of the auth proxy.
|
||||
- For the auth proxy server, set `AUTH_REDIRECT_PROXY_URL` to the same as above, as well as `AUTH_DISCORD_ID`, `AUTH_DISCORD_SECRET` (or the equivalent for your OAuth provider(s)). Lastly, set `AUTH_SECRET` **to the same value as in the Next.js app** for preview environments.
|
||||
|
||||
Read more about the setup in [the auth proxy README](./apps/auth-proxy/README.md).
|
||||
|
||||
### Expo
|
||||
|
||||
Deploying your Expo application works slightly differently compared to Next.js on the web. Instead of "deploying" your app online, you need to submit production builds of your app to app stores, like [Apple App Store](https://www.apple.com/app-store) and [Google Play](https://play.google.com/store/apps). You can read the full [guide to distributing your app](https://docs.expo.dev/distribution/introduction), including best practices, in the Expo docs.
|
||||
|
||||
1. Make sure to modify the `getBaseUrl` function to point to your backend's production URL:
|
||||
|
||||
<https://github.com/t3-oss/create-t3-turbo/blob/656965aff7db271e5e080242c4a3ce4dad5d25f8/apps/expo/src/utils/api.tsx#L20-L37>
|
||||
|
||||
2. Let's start by setting up [EAS Build](https://docs.expo.dev/build/introduction), which is short for Expo Application Services. The build service helps you create builds of your app, without requiring a full native development setup. The commands below are a summary of [Creating your first build](https://docs.expo.dev/build/setup).
|
||||
|
||||
```bash
|
||||
# Install the EAS CLI
|
||||
pnpm add -g eas-cli
|
||||
|
||||
# Log in with your Expo account
|
||||
eas login
|
||||
|
||||
# Configure your Expo app
|
||||
cd apps/expo
|
||||
eas build:configure
|
||||
```
|
||||
|
||||
3. After the initial setup, you can create your first build. You can build for Android and iOS platforms and use different [`eas.json` build profiles](https://docs.expo.dev/build-reference/eas-json) to create production builds or development, or test builds. Let's make a production build for iOS.
|
||||
|
||||
```bash
|
||||
eas build --platform ios --profile production
|
||||
```
|
||||
|
||||
> If you don't specify the `--profile` flag, EAS uses the `production` profile by default.
|
||||
|
||||
4. Now that you have your first production build, you can submit this to the stores. [EAS Submit](https://docs.expo.dev/submit/introduction) can help you send the build to the stores.
|
||||
|
||||
```bash
|
||||
eas submit --platform ios --latest
|
||||
```
|
||||
|
||||
> You can also combine build and submit in a single command, using `eas build ... --auto-submit`.
|
||||
|
||||
5. Before you can get your app in the hands of your users, you'll have to provide additional information to the app stores. This includes screenshots, app information, privacy policies, etc. _While still in preview_, [EAS Metadata](https://docs.expo.dev/eas/metadata) can help you with most of this information.
|
||||
|
||||
6. Once everything is approved, your users can finally enjoy your app. Let's say you spotted a small typo; you'll have to create a new build, submit it to the stores, and wait for approval before you can resolve this issue. In these cases, you can use EAS Update to quickly send a small bugfix to your users without going through this long process. Let's start by setting up EAS Update.
|
||||
|
||||
The steps below summarize the [Getting started with EAS Update](https://docs.expo.dev/eas-update/getting-started/#configure-your-project) guide.
|
||||
|
||||
```bash
|
||||
# Add the `expo-updates` library to your Expo app
|
||||
cd apps/expo
|
||||
pnpm expo install expo-updates
|
||||
|
||||
# Configure EAS Update
|
||||
eas update:configure
|
||||
```
|
||||
|
||||
7. Before we can send out updates to your app, you have to create a new build and submit it to the app stores. For every change that includes native APIs, you have to rebuild the app and submit the update to the app stores. See steps 2 and 3.
|
||||
|
||||
8. Now that everything is ready for updates, let's create a new update for `production` builds. With the `--auto` flag, EAS Update uses your current git branch name and commit message for this update. See [How EAS Update works](https://docs.expo.dev/eas-update/how-eas-update-works/#publishing-an-update) for more information.
|
||||
|
||||
```bash
|
||||
cd apps/expo
|
||||
eas update --auto
|
||||
```
|
||||
|
||||
> Your OTA (Over The Air) updates must always follow the app store's rules. You can't change your app's primary functionality without getting app store approval. But this is a fast way to update your app for minor changes and bug fixes.
|
||||
|
||||
9. Done! Now that you have created your production build, submitted it to the stores, and installed EAS Update, you are ready for anything!
|
||||
|
||||
## References
|
||||
|
||||
The stack originates from [create-t3-app](https://github.com/t3-oss/create-t3-app).
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
|
||||
AUTH_SECRET=""
|
||||
AUTH_DISCORD_ID=""
|
||||
AUTH_DISCORD_SECRET=""
|
||||
AUTH_REDIRECT_PROXY_URL=""
|
||||
|
||||
NITRO_PRESET="vercel_edge"
|
||||
@@ -1,16 +0,0 @@
|
||||
# Auth Proxy
|
||||
|
||||
This is a simple proxy server that enables OAuth authentication for preview environments.
|
||||
|
||||
## Setup
|
||||
|
||||
Deploy it somewhere (Vercel is a one-click, zero-config option) and set the following environment variables:
|
||||
|
||||
- `AUTH_DISCORD_ID` - The Discord OAuth client ID
|
||||
- `AUTH_DISCORD_SECRET` - The Discord OAuth client secret
|
||||
- `AUTH_REDIRECT_PROXY_URL` - The URL of this proxy server
|
||||
- `AUTH_SECRET` - Your secret
|
||||
|
||||
Make sure the `AUTH_SECRET` and `AUTH_REDIRECT_PROXY_URL` match the values set for the main application's deployment for preview environments, and that you're using the same OAuth credentials for the proxy and the application's preview environment. The lines below shows what values should match eachother in both deployments.
|
||||
|
||||

|
||||
@@ -1,17 +0,0 @@
|
||||
import { Auth } from "@auth/core";
|
||||
import Discord from "@auth/core/providers/discord";
|
||||
import { eventHandler, toWebRequest } from "h3";
|
||||
|
||||
export default eventHandler(async (event) =>
|
||||
Auth(toWebRequest(event), {
|
||||
secret: process.env.AUTH_SECRET,
|
||||
trustHost: !!process.env.VERCEL,
|
||||
redirectProxyUrl: process.env.AUTH_REDIRECT_PROXY_URL,
|
||||
providers: [
|
||||
Discord({
|
||||
clientId: process.env.AUTH_DISCORD_ID,
|
||||
clientSecret: process.env.AUTH_DISCORD_SECRET,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"extends": "@alparr/tsconfig/base.json",
|
||||
"include": ["routes"]
|
||||
}
|
||||
@@ -6,12 +6,18 @@ import "@alparr/auth/env.mjs";
|
||||
const config = {
|
||||
reactStrictMode: true,
|
||||
/** Enables hot reloading for local packages without a build step */
|
||||
transpilePackages: ["@alparr/api", "@alparr/auth", "@alparr/db", "@alparr/ui"],
|
||||
transpilePackages: [
|
||||
"@alparr/api",
|
||||
"@alparr/auth",
|
||||
"@alparr/db",
|
||||
"@alparr/ui",
|
||||
"@alparr/validation",
|
||||
],
|
||||
/** We already do linting and typechecking as separate tasks in CI */
|
||||
eslint: { ignoreDuringBuilds: true },
|
||||
typescript: { ignoreBuildErrors: true },
|
||||
experimental: {
|
||||
optimizePackageImports: ['@mantine/core', '@mantine/hooks'],
|
||||
optimizePackageImports: ["@mantine/core", "@mantine/hooks"],
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
"@alparr/api": "workspace:^0.1.0",
|
||||
"@alparr/auth": "workspace:^0.1.0",
|
||||
"@alparr/db": "workspace:^0.1.0",
|
||||
"@alparr/ui": "workspace:^",
|
||||
"@alparr/ui": "workspace:^0.1.0",
|
||||
"@alparr/validation": "workspace:^0.1.0",
|
||||
"@mantine/core": "^7.3.1",
|
||||
"@mantine/dates": "^7.3.1",
|
||||
"@mantine/form": "^7.3.1",
|
||||
@@ -65,4 +66,4 @@
|
||||
]
|
||||
},
|
||||
"prettier": "@alparr/prettier-config"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
'postcss-preset-mantine': {},
|
||||
'postcss-simple-vars': {
|
||||
"postcss-preset-mantine": {},
|
||||
"postcss-simple-vars": {
|
||||
variables: {
|
||||
'mantine-breakpoint-xs': '36em',
|
||||
'mantine-breakpoint-sm': '48em',
|
||||
'mantine-breakpoint-md': '62em',
|
||||
'mantine-breakpoint-lg': '75em',
|
||||
'mantine-breakpoint-xl': '88em',
|
||||
"mantine-breakpoint-xs": "36em",
|
||||
"mantine-breakpoint-sm": "48em",
|
||||
"mantine-breakpoint-md": "62em",
|
||||
"mantine-breakpoint-lg": "75em",
|
||||
"mantine-breakpoint-xl": "88em",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
BIN
apps/nextjs/public/logo/alparr.png
Normal file
BIN
apps/nextjs/public/logo/alparr.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.4 KiB |
@@ -1,3 +1,14 @@
|
||||
export { GET, POST } from "@alparr/auth";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export const runtime = "edge";
|
||||
import { createHandlers } from "@alparr/auth";
|
||||
|
||||
export const GET = async (req: NextRequest) => {
|
||||
return await createHandlers(isCredentialsRequest(req)).handlers.GET(req);
|
||||
};
|
||||
export const POST = async (req: NextRequest) => {
|
||||
return await createHandlers(isCredentialsRequest(req)).handlers.POST(req);
|
||||
};
|
||||
|
||||
const isCredentialsRequest = (req: NextRequest) => {
|
||||
return req.url.includes("credentials") && req.method === "POST";
|
||||
};
|
||||
|
||||
@@ -3,8 +3,6 @@ import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
|
||||
import { appRouter, createTRPCContext } from "@alparr/api";
|
||||
import { auth } from "@alparr/auth";
|
||||
|
||||
export const runtime = "edge";
|
||||
|
||||
/**
|
||||
* Configure basic CORS headers
|
||||
* You should extend this to match your needs
|
||||
|
||||
74
apps/nextjs/src/app/auth/login/_components/login-form.tsx
Normal file
74
apps/nextjs/src/app/auth/login/_components/login-form.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
PasswordInput,
|
||||
rem,
|
||||
Stack,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { useForm, zodResolver } from "@mantine/form";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { signIn } from "@alparr/auth/client";
|
||||
import { signInSchema } from "@alparr/validation";
|
||||
|
||||
export const LoginForm = () => {
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
const form = useForm<FormType>({
|
||||
validate: zodResolver(signInSchema),
|
||||
initialValues: {
|
||||
name: "",
|
||||
password: "",
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (values: FormType) => {
|
||||
setIsLoading(true);
|
||||
setError(undefined);
|
||||
await signIn("credentials", {
|
||||
...values,
|
||||
redirect: false,
|
||||
callbackUrl: "/",
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response?.ok) {
|
||||
throw response?.error;
|
||||
}
|
||||
|
||||
void router.push("/");
|
||||
})
|
||||
.catch((error: Error | string) => {
|
||||
setIsLoading(false);
|
||||
setError(error.toString());
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack gap="xl">
|
||||
<form onSubmit={form.onSubmit((v) => void handleSubmit(v))}>
|
||||
<Stack gap="lg">
|
||||
<TextInput label="Username" {...form.getInputProps("name")} />
|
||||
<PasswordInput label="Password" {...form.getInputProps("password")} />
|
||||
<Button type="submit" fullWidth loading={isLoading}>
|
||||
Login
|
||||
</Button>
|
||||
</Stack>
|
||||
</form>
|
||||
|
||||
{error && (
|
||||
<Alert icon={<IconAlertTriangle size={rem(16)} />} color="red">
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
type FormType = z.infer<typeof signInSchema>;
|
||||
25
apps/nextjs/src/app/auth/login/page.tsx
Normal file
25
apps/nextjs/src/app/auth/login/page.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Card, Center, Stack, Text, Title } from "@mantine/core";
|
||||
|
||||
import { LogoWithTitle } from "~/components/layout/logo";
|
||||
import { LoginForm } from "./_components/login-form";
|
||||
|
||||
export default function Login() {
|
||||
return (
|
||||
<Center>
|
||||
<Stack align="center" mt="xl">
|
||||
<LogoWithTitle />
|
||||
<Stack gap={6} align="center">
|
||||
<Title order={3} fw={400} ta="center">
|
||||
Log in to your account
|
||||
</Title>
|
||||
<Text size="sm" c="gray.5" ta="center">
|
||||
Welcome back! Please enter your credentials
|
||||
</Text>
|
||||
</Stack>
|
||||
<Card bg="dark.8" w={64 * 6} maw="90vw">
|
||||
<LoginForm />
|
||||
</Card>
|
||||
</Stack>
|
||||
</Center>
|
||||
);
|
||||
}
|
||||
70
apps/nextjs/src/app/init/user/_components/init-user-form.tsx
Normal file
70
apps/nextjs/src/app/init/user/_components/init-user-form.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button, PasswordInput, Stack, TextInput } from "@mantine/core";
|
||||
import { useForm, zodResolver } from "@mantine/form";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { initUserSchema } from "@alparr/validation";
|
||||
|
||||
import { showErrorNotification, showSuccessNotification } from "~/notification";
|
||||
import { api } from "~/utils/api";
|
||||
|
||||
export const InitUserForm = () => {
|
||||
const router = useRouter();
|
||||
const { mutateAsync, error, isPending } = api.user.initUser.useMutation();
|
||||
const form = useForm<FormType>({
|
||||
validate: zodResolver(initUserSchema),
|
||||
validateInputOnBlur: true,
|
||||
validateInputOnChange: true,
|
||||
initialValues: {
|
||||
username: "",
|
||||
password: "",
|
||||
repeatPassword: "",
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (values: FormType) => {
|
||||
console.log(values);
|
||||
await mutateAsync(values, {
|
||||
onSuccess: () => {
|
||||
showSuccessNotification({
|
||||
title: "User created",
|
||||
message: "You can now log in",
|
||||
});
|
||||
router.push("/auth/login");
|
||||
},
|
||||
onError: () => {
|
||||
showErrorNotification({
|
||||
title: "User creation failed",
|
||||
message: error?.message ?? "Unknown error",
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack gap="xl">
|
||||
<form
|
||||
onSubmit={form.onSubmit(
|
||||
(v) => void handleSubmit(v),
|
||||
(err) => console.log(err),
|
||||
)}
|
||||
>
|
||||
<Stack gap="lg">
|
||||
<TextInput label="Username" {...form.getInputProps("username")} />
|
||||
<PasswordInput label="Password" {...form.getInputProps("password")} />
|
||||
<PasswordInput
|
||||
label="Repeat password"
|
||||
{...form.getInputProps("repeatPassword")}
|
||||
/>
|
||||
<Button type="submit" fullWidth loading={isPending}>
|
||||
Create user
|
||||
</Button>
|
||||
</Stack>
|
||||
</form>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
type FormType = z.infer<typeof initUserSchema>;
|
||||
38
apps/nextjs/src/app/init/user/page.tsx
Normal file
38
apps/nextjs/src/app/init/user/page.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Card, Center, Stack, Text, Title } from "@mantine/core";
|
||||
|
||||
import { db } from "@alparr/db";
|
||||
|
||||
import { LogoWithTitle } from "~/components/layout/logo";
|
||||
import { InitUserForm } from "./_components/init-user-form";
|
||||
|
||||
export default async function InitUser() {
|
||||
const firstUser = await db.query.users.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (firstUser) {
|
||||
return notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<Center>
|
||||
<Stack align="center" mt="xl">
|
||||
<LogoWithTitle />
|
||||
<Stack gap={6} align="center">
|
||||
<Title order={3} fw={400} ta="center">
|
||||
New Alparr installation
|
||||
</Title>
|
||||
<Text size="sm" c="gray.5" ta="center">
|
||||
Please create the initial administator user.
|
||||
</Text>
|
||||
</Stack>
|
||||
<Card bg="dark.8" w={64 * 6} maw="90vw">
|
||||
<InitUserForm />
|
||||
</Card>
|
||||
</Stack>
|
||||
</Center>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
|
||||
import '@mantine/core/styles.css';
|
||||
import '@mantine/dates/styles.css';
|
||||
import '@mantine/notifications/styles.css';
|
||||
import "@mantine/core/styles.css";
|
||||
import "@mantine/dates/styles.css";
|
||||
import "@mantine/notifications/styles.css";
|
||||
|
||||
import { MantineProvider, ColorSchemeScript } from '@mantine/core';
|
||||
import { headers } from "next/headers";
|
||||
import { ColorSchemeScript, MantineProvider } from "@mantine/core";
|
||||
import { Notifications } from "@mantine/notifications";
|
||||
|
||||
import { uiConfiguration } from "@alparr/ui";
|
||||
|
||||
import { TRPCReactProvider } from "./providers";
|
||||
@@ -29,14 +31,22 @@ export const metadata: Metadata = {
|
||||
};
|
||||
|
||||
export default function Layout(props: { children: React.ReactNode }) {
|
||||
const colorScheme = "dark";
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<ColorSchemeScript />
|
||||
<ColorSchemeScript defaultColorScheme={colorScheme} />
|
||||
</head>
|
||||
<body className={["font-sans", fontSans.variable].join(" ")}>
|
||||
<TRPCReactProvider headers={headers()}>
|
||||
<MantineProvider defaultColorScheme="dark" {...uiConfiguration}>{props.children}</MantineProvider>
|
||||
<MantineProvider
|
||||
defaultColorScheme={colorScheme}
|
||||
{...uiConfiguration}
|
||||
>
|
||||
<Notifications />
|
||||
{props.children}
|
||||
</MantineProvider>
|
||||
</TRPCReactProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { db } from "@alparr/db";
|
||||
import { Button, Stack, Title } from "@mantine/core";
|
||||
|
||||
import { auth } from "@alparr/auth";
|
||||
import { db } from "@alparr/db";
|
||||
|
||||
export default async function HomePage() {
|
||||
const currentSession = await auth();
|
||||
const users = await db.query.users.findMany();
|
||||
|
||||
return (
|
||||
@@ -9,6 +12,11 @@ export default async function HomePage() {
|
||||
<Title>Home</Title>
|
||||
<Button>Test</Button>
|
||||
<pre>{JSON.stringify(users)}</pre>
|
||||
{currentSession && (
|
||||
<span>
|
||||
Currently logged in as <b>{currentSession.user.name}</b>
|
||||
</span>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
17
apps/nextjs/src/components/layout/logo.tsx
Normal file
17
apps/nextjs/src/components/layout/logo.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import Image from "next/image";
|
||||
import { Group, Title } from "@mantine/core";
|
||||
|
||||
interface LogoProps {
|
||||
size: number;
|
||||
}
|
||||
|
||||
export const Logo = ({ size = 60 }: LogoProps) => (
|
||||
<Image src="/logo/alparr.png" alt="Alparr logo" width={size} height={size} />
|
||||
);
|
||||
|
||||
export const LogoWithTitle = () => (
|
||||
<Group gap={0}>
|
||||
<Logo size={48} />
|
||||
<Title order={1}>lparr</Title>
|
||||
</Group>
|
||||
);
|
||||
20
apps/nextjs/src/notification.tsx
Normal file
20
apps/nextjs/src/notification.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import { rem } from "@mantine/core";
|
||||
import type { NotificationData } from "@mantine/notifications";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { IconCheck, IconX } from "@tabler/icons-react";
|
||||
|
||||
type CommonNotificationProps = Pick<NotificationData, "title" | "message">;
|
||||
|
||||
export const showSuccessNotification = (props: CommonNotificationProps) =>
|
||||
notifications.show({
|
||||
...props,
|
||||
color: "teal",
|
||||
icon: <IconCheck size={rem(20)} />,
|
||||
});
|
||||
|
||||
export const showErrorNotification = (props: CommonNotificationProps) =>
|
||||
notifications.show({
|
||||
...props,
|
||||
color: "red",
|
||||
icon: <IconX size={rem(20)} />,
|
||||
});
|
||||
@@ -14,6 +14,7 @@
|
||||
"dependencies": {
|
||||
"@alparr/auth": "workspace:^0.1.0",
|
||||
"@alparr/db": "workspace:^0.1.0",
|
||||
"@alparr/validation": "workspace:^0.1.0",
|
||||
"@trpc/client": "next",
|
||||
"@trpc/server": "next",
|
||||
"superjson": "2.2.1",
|
||||
@@ -34,4 +35,4 @@
|
||||
]
|
||||
},
|
||||
"prettier": "@alparr/prettier-config"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { authRouter } from "./router/auth";
|
||||
import { postRouter } from "./router/post";
|
||||
import { userRouter } from "./router/user";
|
||||
import { createTRPCRouter } from "./trpc";
|
||||
|
||||
export const appRouter = createTRPCRouter({
|
||||
auth: authRouter,
|
||||
post: postRouter,
|
||||
user: userRouter,
|
||||
});
|
||||
|
||||
// export type definition of API
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
|
||||
|
||||
export const authRouter = createTRPCRouter({
|
||||
getSession: publicProcedure.query(({ ctx }) => {
|
||||
return ctx.session;
|
||||
}),
|
||||
getSecretMessage: protectedProcedure.query(() => {
|
||||
// testing type validation of overridden next-auth Session in @alparr/auth package
|
||||
return "you can see this secret message!";
|
||||
}),
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { desc, eq, schema } from "@alparr/db";
|
||||
|
||||
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
|
||||
|
||||
export const postRouter = createTRPCRouter({
|
||||
all: publicProcedure.query(({ ctx }) => {
|
||||
// return ctx.db.select().from(schema.post).orderBy(desc(schema.post.id));
|
||||
return ctx.db.query.post.findMany({ orderBy: desc(schema.post.id) });
|
||||
}),
|
||||
|
||||
byId: publicProcedure
|
||||
.input(z.object({ id: z.number() }))
|
||||
.query(({ ctx, input }) => {
|
||||
// return ctx.db
|
||||
// .select()
|
||||
// .from(schema.post)
|
||||
// .where(eq(schema.post.id, input.id));
|
||||
|
||||
return ctx.db.query.post.findFirst({
|
||||
where: eq(schema.post.id, input.id),
|
||||
});
|
||||
}),
|
||||
|
||||
create: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
title: z.string().min(1),
|
||||
content: z.string().min(1),
|
||||
}),
|
||||
)
|
||||
.mutation(({ ctx, input }) => {
|
||||
return ctx.db.insert(schema.post).values(input);
|
||||
}),
|
||||
|
||||
delete: protectedProcedure.input(z.number()).mutation(({ ctx, input }) => {
|
||||
return ctx.db.delete(schema.post).where(eq(schema.post.id, input));
|
||||
}),
|
||||
});
|
||||
39
packages/api/src/router/user.ts
Normal file
39
packages/api/src/router/user.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import "server-only";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createSalt, hashPassword } from "@alparr/auth";
|
||||
import { createId, schema } from "@alparr/db";
|
||||
import { initUserSchema } from "@alparr/validation";
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from "../trpc";
|
||||
|
||||
export const userRouter = createTRPCRouter({
|
||||
initUser: publicProcedure
|
||||
.input(initUserSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const firstUser = await ctx.db.query.users.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (firstUser) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "User already exists",
|
||||
});
|
||||
}
|
||||
|
||||
const salt = await createSalt();
|
||||
const hashedPassword = await hashPassword(input.password, salt);
|
||||
|
||||
const userId = createId();
|
||||
await ctx.db.insert(schema.users).values({
|
||||
id: userId,
|
||||
name: input.username,
|
||||
password: hashedPassword,
|
||||
salt,
|
||||
});
|
||||
}),
|
||||
});
|
||||
1
packages/auth/client.ts
Normal file
1
packages/auth/client.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { signIn, signOut } from "next-auth/react";
|
||||
76
packages/auth/configuration.ts
Normal file
76
packages/auth/configuration.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { DrizzleAdapter } from "@auth/drizzle-adapter";
|
||||
import NextAuth from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
|
||||
import { db } from "@alparr/db";
|
||||
|
||||
import { credentialsConfiguration } from "./providers/credentials";
|
||||
import { EmptyNextAuthProvider } from "./providers/empty";
|
||||
import { expireDateAfter, generateSessionToken } from "./session";
|
||||
|
||||
const adapter = DrizzleAdapter(db);
|
||||
const sessionMaxAgeInSeconds = 30 * 24 * 60 * 60; // 30 days
|
||||
|
||||
export const createConfiguration = (isCredentialsRequest: boolean) =>
|
||||
NextAuth({
|
||||
adapter,
|
||||
providers: [Credentials(credentialsConfiguration), EmptyNextAuthProvider()],
|
||||
callbacks: {
|
||||
session: ({ session, user }) => ({
|
||||
...session,
|
||||
user: {
|
||||
...session.user,
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
},
|
||||
}),
|
||||
signIn: async ({ user }) => {
|
||||
if (!isCredentialsRequest) return true;
|
||||
|
||||
if (!user) return true;
|
||||
|
||||
const sessionToken = generateSessionToken();
|
||||
const sessionExpiry = expireDateAfter(sessionMaxAgeInSeconds);
|
||||
|
||||
// https://github.com/nextauthjs/next-auth/issues/6106
|
||||
if (!adapter?.createSession) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await adapter.createSession({
|
||||
sessionToken: sessionToken,
|
||||
userId: user.id,
|
||||
expires: sessionExpiry,
|
||||
});
|
||||
|
||||
cookies().set("next-auth.session-token", sessionToken, {
|
||||
path: "/",
|
||||
expires: sessionExpiry,
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: true,
|
||||
});
|
||||
|
||||
return true;
|
||||
},
|
||||
},
|
||||
session: {
|
||||
strategy: "database",
|
||||
maxAge: sessionMaxAgeInSeconds,
|
||||
},
|
||||
pages: {
|
||||
signIn: "/auth/login",
|
||||
error: "/auth/login",
|
||||
},
|
||||
jwt: {
|
||||
encode() {
|
||||
const cookie = cookies().get("next-auth.session-token")?.value;
|
||||
return cookie ?? "";
|
||||
},
|
||||
|
||||
decode() {
|
||||
return null;
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -3,8 +3,6 @@ import { z } from "zod";
|
||||
|
||||
export const env = createEnv({
|
||||
server: {
|
||||
AUTH_DISCORD_ID: z.string().min(1),
|
||||
AUTH_DISCORD_SECRET: z.string().min(1),
|
||||
AUTH_SECRET:
|
||||
process.env.NODE_ENV === "production"
|
||||
? z.string().min(1)
|
||||
@@ -19,8 +17,6 @@ export const env = createEnv({
|
||||
},
|
||||
client: {},
|
||||
runtimeEnv: {
|
||||
AUTH_DISCORD_ID: process.env.AUTH_DISCORD_ID,
|
||||
AUTH_DISCORD_SECRET: process.env.AUTH_DISCORD_SECRET,
|
||||
AUTH_SECRET: process.env.AUTH_SECRET,
|
||||
AUTH_URL: process.env.AUTH_URL,
|
||||
},
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* @see https://github.com/nextauthjs/next-auth/pull/8932 */
|
||||
|
||||
import Discord from "@auth/core/providers/discord";
|
||||
import type { DefaultSession } from "@auth/core/types";
|
||||
import { DrizzleAdapter } from "@auth/drizzle-adapter";
|
||||
import NextAuth from "next-auth";
|
||||
|
||||
import { db, tableCreator } from "@alparr/db";
|
||||
import { createConfiguration } from "./configuration";
|
||||
|
||||
export type { Session } from "next-auth";
|
||||
|
||||
@@ -18,21 +12,8 @@ declare module "next-auth" {
|
||||
}
|
||||
}
|
||||
|
||||
export const {
|
||||
handlers: { GET, POST },
|
||||
auth,
|
||||
signIn,
|
||||
signOut,
|
||||
} = NextAuth({
|
||||
adapter: DrizzleAdapter(db, tableCreator),
|
||||
providers: [Discord],
|
||||
callbacks: {
|
||||
session: ({ session, user }) => ({
|
||||
...session,
|
||||
user: {
|
||||
...session.user,
|
||||
id: user.id,
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
export * from "./security";
|
||||
|
||||
export const createHandlers = (isCredentialsRequest: boolean) =>
|
||||
createConfiguration(isCredentialsRequest);
|
||||
export const { auth } = createConfiguration(false);
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
"@auth/core": "^0.18.4",
|
||||
"@auth/drizzle-adapter": "^0.3.9",
|
||||
"@t3-oss/env-nextjs": "^0.7.1",
|
||||
"bcrypt": "^5.1.1",
|
||||
"cookies": "^0.8.0",
|
||||
"next": "^14.0.3",
|
||||
"next-auth": "5.0.0-beta.4",
|
||||
"react": "18.2.0",
|
||||
@@ -26,6 +28,9 @@
|
||||
"@alparr/eslint-config": "workspace:^0.2.0",
|
||||
"@alparr/prettier-config": "workspace:^0.1.0",
|
||||
"@alparr/tsconfig": "workspace:^0.1.0",
|
||||
"@alparr/validation": "workspace:^0.1.0",
|
||||
"@types/bcrypt": "5.0.2",
|
||||
"@types/cookies": "0.7.10",
|
||||
"eslint": "^8.53.0",
|
||||
"prettier": "^3.1.0",
|
||||
"typescript": "^5.3.3"
|
||||
@@ -37,4 +42,4 @@
|
||||
]
|
||||
},
|
||||
"prettier": "@alparr/prettier-config"
|
||||
}
|
||||
}
|
||||
|
||||
49
packages/auth/providers/credentials.ts
Normal file
49
packages/auth/providers/credentials.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import type Credentials from "@auth/core/providers/credentials";
|
||||
import bcrypt from "bcrypt";
|
||||
|
||||
import { db, eq } from "@alparr/db";
|
||||
import { users } from "@alparr/db/schema/sqlite";
|
||||
import { signInSchema } from "@alparr/validation";
|
||||
|
||||
type CredentialsConfiguration = Parameters<typeof Credentials>[0];
|
||||
|
||||
export const credentialsConfiguration = {
|
||||
type: "credentials",
|
||||
name: "Credentials",
|
||||
credentials: {
|
||||
name: {
|
||||
label: "Username",
|
||||
type: "text",
|
||||
},
|
||||
password: {
|
||||
label: "Password",
|
||||
type: "password",
|
||||
},
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const data = await signInSchema.parseAsync(credentials);
|
||||
|
||||
const user = await db.query.users.findFirst({
|
||||
where: eq(users.name, data.name),
|
||||
});
|
||||
|
||||
if (!user?.password) {
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log(`user ${user.name} is trying to log in. checking password...`);
|
||||
const isValidPassword = await bcrypt.compare(data.password, user.password);
|
||||
|
||||
if (!isValidPassword) {
|
||||
console.log(`password for user ${user.name} was incorrect`);
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log(`user ${user.name} successfully authorized`);
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
};
|
||||
},
|
||||
} satisfies CredentialsConfiguration;
|
||||
16
packages/auth/providers/empty.ts
Normal file
16
packages/auth/providers/empty.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import type { OAuthConfig } from "next-auth/providers";
|
||||
|
||||
export function EmptyNextAuthProvider(): OAuthConfig<unknown> {
|
||||
return {
|
||||
id: "empty",
|
||||
name: "Empty",
|
||||
type: "oauth",
|
||||
profile: () => {
|
||||
throw new Error(
|
||||
"EmptyNextAuthProvider can not be used and is only a placeholder because credentials authentication can not be used as session authentication without additional providers.",
|
||||
);
|
||||
},
|
||||
issuer: "empty",
|
||||
authorization: new URL("https://example.empty"),
|
||||
};
|
||||
}
|
||||
9
packages/auth/security.ts
Normal file
9
packages/auth/security.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import bcrypt from "bcrypt";
|
||||
|
||||
export const createSalt = async () => {
|
||||
return bcrypt.genSalt(10);
|
||||
};
|
||||
|
||||
export const hashPassword = async (password: string, salt: string) => {
|
||||
return bcrypt.hash(password, salt);
|
||||
};
|
||||
9
packages/auth/session.ts
Normal file
9
packages/auth/session.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export const expireDateAfter = (seconds: number) => {
|
||||
return new Date(Date.now() + seconds * 1000);
|
||||
};
|
||||
|
||||
export const generateSessionToken = () => {
|
||||
return randomUUID();
|
||||
};
|
||||
@@ -1,9 +1,8 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import Database from "better-sqlite3";
|
||||
import { drizzle } from "drizzle-orm/better-sqlite3";
|
||||
|
||||
import * as sqliteSchema from "./schema/sqlite";
|
||||
|
||||
|
||||
export const schema = sqliteSchema;
|
||||
|
||||
export * from "drizzle-orm";
|
||||
@@ -11,3 +10,5 @@ export * from "drizzle-orm";
|
||||
const sqlite = new Database(process.env.DB_URL!);
|
||||
|
||||
export const db = drizzle(sqlite, { schema });
|
||||
|
||||
export { createId } from "@paralleldrive/cuid2";
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/better-sqlite3": "^7.6.8",
|
||||
"@paralleldrive/cuid2": "^2.2.2",
|
||||
"better-sqlite3": "^9.2.2",
|
||||
"drizzle-orm": "^0.29.1"
|
||||
},
|
||||
@@ -22,6 +22,7 @@
|
||||
"@alparr/eslint-config": "workspace:^0.2.0",
|
||||
"@alparr/prettier-config": "workspace:^0.1.0",
|
||||
"@alparr/tsconfig": "workspace:^0.1.0",
|
||||
"@types/better-sqlite3": "7.6.8",
|
||||
"dotenv-cli": "^7.3.0",
|
||||
"drizzle-kit": "^0.20.6",
|
||||
"eslint": "^8.53.0",
|
||||
@@ -35,4 +36,4 @@
|
||||
]
|
||||
},
|
||||
"prettier": "@alparr/prettier-config"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,65 +1,73 @@
|
||||
import type { AdapterAccount } from '@auth/core/adapters';
|
||||
import type { InferSelectModel } from 'drizzle-orm';
|
||||
import { relations } from 'drizzle-orm';
|
||||
import { index, integer, primaryKey, sqliteTable, text } from 'drizzle-orm/sqlite-core';
|
||||
import type { AdapterAccount } from "@auth/core/adapters";
|
||||
import type { InferSelectModel } from "drizzle-orm";
|
||||
import { relations } from "drizzle-orm";
|
||||
import {
|
||||
index,
|
||||
integer,
|
||||
primaryKey,
|
||||
sqliteTable,
|
||||
text,
|
||||
} from "drizzle-orm/sqlite-core";
|
||||
|
||||
export const users = sqliteTable('user', {
|
||||
id: text('id').notNull().primaryKey(),
|
||||
name: text('name'),
|
||||
email: text('email'),
|
||||
emailVerified: integer('emailVerified', { mode: 'timestamp_ms' }),
|
||||
image: text('image'),
|
||||
password: text('password'),
|
||||
salt: text('salt'),
|
||||
export const users = sqliteTable("user", {
|
||||
id: text("id").notNull().primaryKey(),
|
||||
name: text("name"),
|
||||
email: text("email"),
|
||||
emailVerified: integer("emailVerified", { mode: "timestamp_ms" }),
|
||||
image: text("image"),
|
||||
password: text("password"),
|
||||
salt: text("salt"),
|
||||
});
|
||||
|
||||
export const accounts = sqliteTable(
|
||||
'account',
|
||||
"account",
|
||||
{
|
||||
userId: text('userId')
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
type: text('type').$type<AdapterAccount['type']>().notNull(),
|
||||
provider: text('provider').notNull(),
|
||||
providerAccountId: text('providerAccountId').notNull(),
|
||||
refresh_token: text('refresh_token'),
|
||||
access_token: text('access_token'),
|
||||
expires_at: integer('expires_at'),
|
||||
token_type: text('token_type'),
|
||||
scope: text('scope'),
|
||||
id_token: text('id_token'),
|
||||
session_state: text('session_state'),
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
type: text("type").$type<AdapterAccount["type"]>().notNull(),
|
||||
provider: text("provider").notNull(),
|
||||
providerAccountId: text("providerAccountId").notNull(),
|
||||
refresh_token: text("refresh_token"),
|
||||
access_token: text("access_token"),
|
||||
expires_at: integer("expires_at"),
|
||||
token_type: text("token_type"),
|
||||
scope: text("scope"),
|
||||
id_token: text("id_token"),
|
||||
session_state: text("session_state"),
|
||||
},
|
||||
(account) => ({
|
||||
compoundKey: primaryKey({ columns: [account.provider, account.providerAccountId] }),
|
||||
userIdIdx: index('userId_idx').on(account.userId),
|
||||
})
|
||||
compoundKey: primaryKey({
|
||||
columns: [account.provider, account.providerAccountId],
|
||||
}),
|
||||
userIdIdx: index("userId_idx").on(account.userId),
|
||||
}),
|
||||
);
|
||||
|
||||
export const sessions = sqliteTable(
|
||||
'session',
|
||||
"session",
|
||||
{
|
||||
sessionToken: text('sessionToken').notNull().primaryKey(),
|
||||
userId: text('userId')
|
||||
sessionToken: text("sessionToken").notNull().primaryKey(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
expires: integer('expires', { mode: 'timestamp_ms' }).notNull(),
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
expires: integer("expires", { mode: "timestamp_ms" }).notNull(),
|
||||
},
|
||||
(session) => ({
|
||||
userIdIdx: index('user_id_idx').on(session.userId),
|
||||
})
|
||||
userIdIdx: index("user_id_idx").on(session.userId),
|
||||
}),
|
||||
);
|
||||
|
||||
export const verificationTokens = sqliteTable(
|
||||
'verificationToken',
|
||||
"verificationToken",
|
||||
{
|
||||
identifier: text('identifier').notNull(),
|
||||
token: text('token').notNull(),
|
||||
expires: integer('expires', { mode: 'timestamp_ms' }).notNull(),
|
||||
identifier: text("identifier").notNull(),
|
||||
token: text("token").notNull(),
|
||||
expires: integer("expires", { mode: "timestamp_ms" }).notNull(),
|
||||
},
|
||||
(vt) => ({
|
||||
compoundKey: primaryKey({ columns: [vt.identifier, vt.token] }),
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
export const accountRelations = relations(accounts, ({ one }) => ({
|
||||
|
||||
@@ -1 +1 @@
|
||||
export * from './src';
|
||||
export * from "./src";
|
||||
|
||||
@@ -35,4 +35,4 @@
|
||||
"dependencies": {
|
||||
"@mantine/core": "^7.3.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { MantineProviderProps } from "@mantine/core";
|
||||
|
||||
import { theme } from "./theme";
|
||||
|
||||
|
||||
export const uiConfiguration = ({
|
||||
theme,
|
||||
}) satisfies MantineProviderProps;
|
||||
export const uiConfiguration = {
|
||||
theme,
|
||||
} satisfies MantineProviderProps;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { createTheme } from "@mantine/core";
|
||||
|
||||
import { primaryColor } from "./theme/colors/primary";
|
||||
import { secondaryColor } from "./theme/colors/secondary";
|
||||
|
||||
export const theme = createTheme({
|
||||
colors: {
|
||||
primaryColor,
|
||||
secondaryColor,
|
||||
},
|
||||
primaryColor: "primaryColor",
|
||||
});
|
||||
colors: {
|
||||
primaryColor,
|
||||
secondaryColor,
|
||||
},
|
||||
primaryColor: "primaryColor",
|
||||
});
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import type { MantineColorsTuple } from "@mantine/core";
|
||||
|
||||
export const primaryColor: MantineColorsTuple = [
|
||||
'#eafbf0',
|
||||
'#ddefe3',
|
||||
'#bedcc7',
|
||||
'#9bc8aa',
|
||||
'#7eb892',
|
||||
'#6bad81',
|
||||
'#60a878',
|
||||
'#509265',
|
||||
'#438359',
|
||||
'#35724a'
|
||||
"#eafbf0",
|
||||
"#ddefe3",
|
||||
"#bedcc7",
|
||||
"#9bc8aa",
|
||||
"#7eb892",
|
||||
"#6bad81",
|
||||
"#60a878",
|
||||
"#509265",
|
||||
"#438359",
|
||||
"#35724a",
|
||||
];
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import type { MantineColorsTuple } from "@mantine/core";
|
||||
|
||||
export const secondaryColor: MantineColorsTuple = [
|
||||
'#e6f7ff',
|
||||
'#d9e8f6',
|
||||
'#b6cde6',
|
||||
'#90b2d4',
|
||||
'#6f9ac5',
|
||||
'#5a8bbd',
|
||||
'#4d84ba',
|
||||
'#3d71a4',
|
||||
'#326595',
|
||||
'#205885'
|
||||
];
|
||||
"#e6f7ff",
|
||||
"#d9e8f6",
|
||||
"#b6cde6",
|
||||
"#90b2d4",
|
||||
"#6f9ac5",
|
||||
"#5a8bbd",
|
||||
"#4d84ba",
|
||||
"#3d71a4",
|
||||
"#326595",
|
||||
"#205885",
|
||||
];
|
||||
|
||||
1
packages/validation/index.ts
Normal file
1
packages/validation/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./src";
|
||||
@@ -1,32 +1,38 @@
|
||||
{
|
||||
"name": "@alparr/auth-proxy",
|
||||
"name": "@alparr/validation",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "0.1.0",
|
||||
"exports": {
|
||||
".": "./index.ts"
|
||||
},
|
||||
"typesVersions": {
|
||||
"*": {
|
||||
"*": [
|
||||
"src/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"build": "nitro build",
|
||||
"clean": "rm -rf .turbo node_modules",
|
||||
"dev": "nitro dev --port 3001",
|
||||
"lint": "eslint .",
|
||||
"format": "prettier --check . --ignore-path ../../.gitignore",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@auth/core": "^0.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@alparr/eslint-config": "workspace:^0.2.0",
|
||||
"@alparr/prettier-config": "workspace:^0.1.0",
|
||||
"@alparr/tsconfig": "workspace:^0.1.0",
|
||||
"eslint": "^8.53.0",
|
||||
"nitropack": "^2.8.1",
|
||||
"prettier": "^3.1.0",
|
||||
"typescript": "^5.3.3"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"root": true,
|
||||
"extends": [
|
||||
"@alparr/eslint-config/base"
|
||||
]
|
||||
},
|
||||
"prettier": "@alparr/prettier-config"
|
||||
}
|
||||
"prettier": "@alparr/prettier-config",
|
||||
"dependencies": {
|
||||
"zod": "^3.22.2"
|
||||
}
|
||||
}
|
||||
1
packages/validation/src/index.ts
Normal file
1
packages/validation/src/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./user";
|
||||
20
packages/validation/src/user.ts
Normal file
20
packages/validation/src/user.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const usernameSchema = z.string().min(3).max(255);
|
||||
const passwordSchema = z.string().min(8).max(255);
|
||||
|
||||
export const initUserSchema = z
|
||||
.object({
|
||||
username: usernameSchema,
|
||||
password: passwordSchema,
|
||||
repeatPassword: z.string(),
|
||||
})
|
||||
.refine((data) => data.password === data.repeatPassword, {
|
||||
path: ["repeatPassword"],
|
||||
message: "Passwords do not match",
|
||||
});
|
||||
|
||||
export const signInSchema = z.object({
|
||||
name: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
8
packages/validation/tsconfig.json
Normal file
8
packages/validation/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "@alparr/tsconfig/base.json",
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
|
||||
},
|
||||
"include": ["*.ts", "src"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
1864
pnpm-lock.yaml
generated
1864
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -39,4 +39,4 @@
|
||||
]
|
||||
},
|
||||
"prettier": "@alparr/prettier-config"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
|
||||
/** @typedef {import("prettier").Config} PrettierConfig */
|
||||
/** @typedef {import("@ianvs/prettier-plugin-sort-imports").PluginConfig} SortImportsConfig */
|
||||
|
||||
/** @type { PrettierConfig | SortImportsConfig } */
|
||||
const config = {
|
||||
plugins: [
|
||||
"@ianvs/prettier-plugin-sort-imports"
|
||||
],
|
||||
plugins: ["@ianvs/prettier-plugin-sort-imports"],
|
||||
importOrder: [
|
||||
"^(react/(.*)$)|^(react$)$)",
|
||||
"^(react/(.*)$)|^react$",
|
||||
"^(next/(.*)$)|^(next$)",
|
||||
"<THIRD_PARTY_MODULES>",
|
||||
"",
|
||||
|
||||
@@ -17,4 +17,4 @@
|
||||
"typescript": "^5.3.3"
|
||||
},
|
||||
"prettier": "@alparr/prettier-config"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
"@alparr/prettier-config": "workspace:^0.1.0",
|
||||
"@alparr/tsconfig": "workspace:^0.1.0",
|
||||
"eslint": "^8.53.0",
|
||||
"typescript": "^5.2.2"
|
||||
"typescript": "^5.3.3"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
|
||||
Reference in New Issue
Block a user