feat: v3.6.0-rc4 (#207)

* feat: oauth reform for potential improvements

* fix: update avatars with new pfp

* fix: remove redundant include

* feat: v3.6.0-rc4

Co-authored-by: dicedtomato <diced@users.noreply.github.com>

* fix: remove console log

Co-authored-by: dicedtomato <diced@users.noreply.github.com>
This commit is contained in:
TacticalCoderJay 2022-10-30 21:42:39 -07:00 committed by GitHub
parent 8c9064fd93
commit 87fc9f2fb9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 683 additions and 300 deletions

View file

@ -17,8 +17,8 @@ module.exports = {
'getsharex.com',
// For flameshot icon, and maybe in the future other stuff from github
'raw.githubusercontent.com',
// Discord Icon
'assets-global.website-files.com',
// Google Icon
'madeby.google.com',
],
},
poweredByHeader: false,

View file

@ -1,6 +1,6 @@
{
"name": "zipline",
"version": "3.6.0-rc3",
"version": "3.6.0-rc4",
"license": "MIT",
"scripts": {
"dev": "npm-run-all build:server dev:run",

View file

@ -0,0 +1,31 @@
/*
Warnings:
- You are about to drop the column `oauth` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `oauthAccessToken` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `oauthProvider` on the `User` table. All the data in the column will be lost.
*/
-- CreateEnum
CREATE TYPE "OauthProviders" AS ENUM ('DISCORD', 'GITHUB');
-- AlterTable
ALTER TABLE "User" DROP COLUMN "oauth",
DROP COLUMN "oauthAccessToken",
DROP COLUMN "oauthProvider";
-- CreateTable
CREATE TABLE "OAuth" (
"id" SERIAL NOT NULL,
"provider" "OauthProviders" NOT NULL,
"userId" INTEGER NOT NULL,
"token" TEXT NOT NULL,
CONSTRAINT "OAuth_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "OAuth_provider_key" ON "OAuth"("provider");
-- AddForeignKey
ALTER TABLE "OAuth" ADD CONSTRAINT "OAuth_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View file

@ -0,0 +1,5 @@
-- DropIndex
DROP INDEX "OAuth_provider_key";
-- AlterTable
ALTER TABLE "OAuth" ADD COLUMN "refresh" TEXT;

View file

@ -0,0 +1,8 @@
-- DropForeignKey
ALTER TABLE "Image" DROP CONSTRAINT "Image_userId_fkey";
-- AlterTable
ALTER TABLE "Image" ALTER COLUMN "userId" DROP NOT NULL;
-- AddForeignKey
ALTER TABLE "Image" ADD CONSTRAINT "Image_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View file

@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "OauthProviders" ADD VALUE 'GOOGLE';

View file

@ -0,0 +1,8 @@
/*
Warnings:
- Added the required column `username` to the `OAuth` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "OAuth" ADD COLUMN "username" TEXT NOT NULL;

View file

@ -8,25 +8,23 @@ generator client {
}
model User {
id Int @id @default(autoincrement())
username String
password String?
oauth Boolean @default(false)
oauthProvider String?
oauthAccessToken String?
avatar String?
token String
administrator Boolean @default(false)
superAdmin Boolean @default(false)
systemTheme String @default("system")
embedTitle String?
embedColor String @default("#2f3136")
embedSiteName String? @default("{image.file} • {user.name}")
ratelimit DateTime?
domains String[]
images Image[]
urls Url[]
Invite Invite[]
id Int @id @default(autoincrement())
username String
password String?
avatar String?
token String
administrator Boolean @default(false)
superAdmin Boolean @default(false)
systemTheme String @default("system")
embedTitle String?
embedColor String @default("#2f3136")
embedSiteName String? @default("{image.file} • {user.name}")
ratelimit DateTime?
domains String[]
oauth OAuth[]
images Image[]
urls Url[]
Invite Invite[]
}
enum ImageFormat {
@ -49,8 +47,8 @@ model Image {
password String?
invisible InvisibleImage?
format ImageFormat @default(RANDOM)
user User @relation(fields: [userId], references: [id])
userId Int
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
userId Int?
}
model InvisibleImage {
@ -86,12 +84,27 @@ model Stats {
}
model Invite {
id Int @id @default(autoincrement())
code String @unique
created_at DateTime @default(now())
expires_at DateTime?
used Boolean @default(false)
createdBy User @relation(fields: [createdById], references: [id])
id Int @id @default(autoincrement())
code String @unique
created_at DateTime @default(now())
expires_at DateTime?
used Boolean @default(false)
createdBy User @relation(fields: [createdById], references: [id])
createdById Int
}
model OAuth {
id Int @id @default(autoincrement())
provider OauthProviders
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
username String
token String
refresh String?
}
enum OauthProviders {
DISCORD
GITHUB
GOOGLE
}

View file

@ -29,6 +29,7 @@ import { showNotification } from '@mantine/notifications';
import useFetch from 'hooks/useFetch';
import { useVersion } from 'lib/queries/version';
import { userSelector } from 'lib/recoil/user';
import { capitalize } from 'lib/utils/client';
import { useRecoilState } from 'recoil';
import Link from 'next/link';
import { useRouter } from 'next/router';
@ -52,6 +53,7 @@ import {
UserIcon,
DiscordIcon,
GitHubIcon,
GoogleIcon,
} from './icons';
import { friendlyThemeName, themes } from './Theming';
@ -161,7 +163,18 @@ const admin_items = [
export default function Layout({ children, props }) {
const [user, setUser] = useRecoilState(userSelector);
const { title } = props;
const { title, oauth_providers: unparsed } = props;
const oauth_providers = JSON.parse(unparsed);
const icons = {
GitHub: GitHubIcon,
Discord: DiscordIcon,
Google: GoogleIcon,
};
for (const provider of oauth_providers) {
provider.Icon = icons[provider.name];
}
const external_links = JSON.parse(props.external_links ?? '[]');
const [token, setToken] = useState(user?.token);
@ -393,24 +406,34 @@ export default function Layout({ children, props }) {
Logout
</MenuItemLink>
<Menu.Divider />
{user.oauth ? (
<>
<MenuItem
icon={
user.oauthProvider === 'discord' ? (
<DiscordIcon size={18} />
) : (
<GitHubIcon size={18} />
)
}
>
Logged in with{' '}
<span style={{ textTransform: 'capitalize' }}>{user.oauthProvider}</span>
</MenuItem>
<>
{oauth_providers
.filter((x) =>
user.oauth
?.map(({ provider }) => provider.toLowerCase())
.includes(x.name.toLowerCase())
)
.map(({ name, Icon }, i) => (
<>
<MenuItem
sx={{ '&:hover': { backgroundColor: 'inherit' } }}
key={i}
py={5}
px={4}
icon={<Icon size={18} colorScheme={theme.colorScheme} />}
>
Logged in with {capitalize(name)}
</MenuItem>
</>
))}
{oauth_providers.filter((x) =>
user.oauth
?.map(({ provider }) => provider.toLowerCase())
.includes(x.name.toLowerCase())
).length ? (
<Menu.Divider />
</>
) : null}
) : null}
</>
<MenuItem icon={<PencilIcon />}>
<Select
size='xs'

View file

@ -4,12 +4,18 @@ import Image from 'next/image';
export default function DiscordIcon({ ...props }) {
return (
<Image
alt='discord'
src='https://assets-global.website-files.com/6257adef93867e50d84d30e2/62595384f934b806f37f4956_145dc557845548a36a82337912ca3ac5.svg'
width={24}
height={24}
{...props}
/>
<svg width='24' height='24' viewBox='0 0 71 55' xmlns='http://www.w3.org/2000/svg'>
<g clipPath='url(#clip0)'>
<path
fill={props.colorScheme === 'manage' ? '#ffffff' : '#5865F2'}
d='M60.1045 4.8978C55.5792 2.8214 50.7265 1.2916 45.6527 0.41542C45.5603 0.39851 45.468 0.440769 45.4204 0.525289C44.7963 1.6353 44.105 3.0834 43.6209 4.2216C38.1637 3.4046 32.7345 3.4046 27.3892 4.2216C26.905 3.0581 26.1886 1.6353 25.5617 0.525289C25.5141 0.443589 25.4218 0.40133 25.3294 0.41542C20.2584 1.2888 15.4057 2.8186 10.8776 4.8978C10.8384 4.9147 10.8048 4.9429 10.7825 4.9795C1.57795 18.7309 -0.943561 32.1443 0.293408 45.3914C0.299005 45.4562 0.335386 45.5182 0.385761 45.5576C6.45866 50.0174 12.3413 52.7249 18.1147 54.5195C18.2071 54.5477 18.305 54.5139 18.3638 54.4378C19.7295 52.5728 20.9469 50.6063 21.9907 48.5383C22.0523 48.4172 21.9935 48.2735 21.8676 48.2256C19.9366 47.4931 18.0979 46.6 16.3292 45.5858C16.1893 45.5041 16.1781 45.304 16.3068 45.2082C16.679 44.9293 17.0513 44.6391 17.4067 44.3461C17.471 44.2926 17.5606 44.2813 17.6362 44.3151C29.2558 49.6202 41.8354 49.6202 53.3179 44.3151C53.3935 44.2785 53.4831 44.2898 53.5502 44.3433C53.9057 44.6363 54.2779 44.9293 54.6529 45.2082C54.7816 45.304 54.7732 45.5041 54.6333 45.5858C52.8646 46.6197 51.0259 47.4931 49.0921 48.2228C48.9662 48.2707 48.9102 48.4172 48.9718 48.5383C50.038 50.6034 51.2554 52.5699 52.5959 54.435C52.6519 54.5139 52.7526 54.5477 52.845 54.5195C58.6464 52.7249 64.529 50.0174 70.6019 45.5576C70.6551 45.5182 70.6887 45.459 70.6943 45.3942C72.1747 30.0791 68.2147 16.7757 60.1968 4.9823C60.1772 4.9429 60.1437 4.9147 60.1045 4.8978ZM23.7259 37.3253C20.2276 37.3253 17.3451 34.1136 17.3451 30.1693C17.3451 26.225 20.1717 23.0133 23.7259 23.0133C27.308 23.0133 30.1626 26.2532 30.1066 30.1693C30.1066 34.1136 27.28 37.3253 23.7259 37.3253ZM47.3178 37.3253C43.8196 37.3253 40.9371 34.1136 40.9371 30.1693C40.9371 26.225 43.7636 23.0133 47.3178 23.0133C50.9 23.0133 53.7545 26.2532 53.6986 30.1693C53.6986 34.1136 50.9 37.3253 47.3178 37.3253Z'
/>
</g>
<defs>
<clipPath id='clip0'>
<rect width='71' height='55' fill='white' />
</clipPath>
</defs>
</svg>
);
}

View file

@ -1,5 +1,17 @@
import { GitHub } from 'react-feather';
import Image from 'next/image';
export default function GitHubIcon({ ...props }) {
return <GitHub size={24} {...props} />;
// https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg
export default function GitHubIcon({ colorScheme, ...props }) {
return (
<svg width={24} height={24} viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg' {...props}>
<path
fillRule='evenodd'
clipRule='evenodd'
d='M8 0C3.58 0 0 3.58 0 8C0 11.54 2.29 14.53 5.47 15.59C5.87 15.66 6.02 15.42 6.02 15.21C6.02 15.02 6.01 14.39 6.01 13.72C4 14.09 3.48 13.23 3.32 12.78C3.23 12.55 2.84 11.84 2.5 11.65C2.22 11.5 1.82 11.13 2.49 11.12C3.12 11.11 3.57 11.7 3.72 11.94C4.44 13.15 5.59 12.81 6.05 12.6C6.12 12.08 6.33 11.73 6.56 11.53C4.78 11.33 2.92 10.64 2.92 7.58C2.92 6.71 3.23 5.99 3.74 5.43C3.66 5.23 3.38 4.41 3.82 3.31C3.82 3.31 4.49 3.1 6.02 4.13C6.66 3.95 7.34 3.86 8.02 3.86C8.7 3.86 9.38 3.95 10.02 4.13C11.55 3.09 12.22 3.31 12.22 3.31C12.66 4.41 12.38 5.23 12.3 5.43C12.81 5.99 13.12 6.7 13.12 7.58C13.12 10.65 11.25 11.33 9.47 11.53C9.76 11.78 10.01 12.26 10.01 13.01C10.01 14.08 10 14.94 10 15.21C10 15.42 10.15 15.67 10.55 15.59C13.71 14.53 16 11.53 16 8C16 3.58 12.42 0 8 0Z'
transform='scale(64)'
fill={colorScheme === 'dark' ? '#FFFFFF' : '#1B1F23'}
/>
</svg>
);
}

View file

@ -0,0 +1,15 @@
// https://developers.google.com/identity/branding-guidelines
import Image from 'next/image';
export default function GoogleIcon({ ...props }) {
return (
<Image
alt='google'
src='https://madeby.google.com/static/images/google_g_logo.svg'
width={24}
height={24}
{...props}
/>
);
}

View file

@ -29,6 +29,7 @@ import DownloadIcon from './DownloadIcon';
import FlameshotIcon from './FlameshotIcon';
import GitHubIcon from './GitHubIcon';
import DiscordIcon from './DiscordIcon';
import GoogleIcon from './GoogleIcon';
import EyeIcon from './EyeIcon';
import RefreshIcon from './RefreshIcon';
@ -64,6 +65,7 @@ export {
FlameshotIcon,
GitHubIcon,
DiscordIcon,
GoogleIcon,
EyeIcon,
RefreshIcon,
};

View file

@ -25,6 +25,7 @@ import {
DiscordIcon,
FlameshotIcon,
GitHubIcon,
GoogleIcon,
RefreshIcon,
SettingsIcon,
ShareXIcon,
@ -37,6 +38,7 @@ import { SmallTable } from 'components/SmallTable';
import useFetch from 'hooks/useFetch';
import { userSelector } from 'lib/recoil/user';
import { bytesToHuman } from 'lib/utils/bytes';
import { capitalize } from 'lib/utils/client';
import { useEffect, useState } from 'react';
import { useRecoilState } from 'recoil';
import Flameshot from './Flameshot';
@ -57,8 +59,9 @@ function ExportDataTooltip({ children }) {
export default function Manage({ oauth_registration, oauth_providers: raw_oauth_providers }) {
const oauth_providers = JSON.parse(raw_oauth_providers);
const icons = {
GitHub: GitHubIcon,
Discord: DiscordIcon,
GitHub: GitHubIcon,
Google: GoogleIcon,
};
for (const provider of oauth_providers) {
@ -233,7 +236,7 @@ export default function Manage({ oauth_registration, oauth_providers: raw_oauth_
setExports(
res.exports
.map((s) => ({
?.map((s) => ({
date: new Date(Number(s.name.split('_')[3].slice(0, -4))),
size: s.size,
full: s.name,
@ -303,8 +306,10 @@ export default function Manage({ oauth_registration, oauth_providers: raw_oauth_
}
};
const handleOauthUnlink = async () => {
const res = await useFetch('/api/auth/oauth', 'DELETE');
const handleOauthUnlink = async (provider) => {
const res = await useFetch('/api/auth/oauth', 'DELETE', {
provider,
});
if (res.error) {
showNotification({
title: 'Error while unlinking from OAuth',
@ -315,7 +320,7 @@ export default function Manage({ oauth_registration, oauth_providers: raw_oauth_
} else {
setUser(res);
showNotification({
title: 'Unlinked from OAuth',
title: `Unlinked from ${provider[0] + provider.slice(1).toLowerCase()}`,
message: '',
color: 'green',
icon: <CheckIcon />,
@ -374,19 +379,30 @@ export default function Manage({ oauth_registration, oauth_providers: raw_oauth_
<Group>
{oauth_providers
.filter((x) => x.name.toLowerCase() !== user.oauthProvider)
.filter(
(x) =>
!user.oauth?.map(({ provider }) => provider.toLowerCase()).includes(x.name.toLowerCase())
)
.map(({ link_url, name, Icon }, i) => (
<Link key={i} href={link_url} passHref legacyBehavior>
<Button size='lg' leftIcon={<Icon />} component='a' my='sm'>
<Button size='lg' leftIcon={<Icon colorScheme='manage' />} component='a' my='sm'>
Link account with {name}
</Button>
</Link>
))}
{user.oauth && user.oauthProvider && (
<Button onClick={handleOauthUnlink} size='lg' leftIcon={<TrashIcon />} my='sm' color='red'>
Unlink account with {user.oauthProvider[0].toUpperCase() + user.oauthProvider.slice(1)}
{user?.oauth?.map(({ provider }, i) => (
<Button
key={i}
onClick={() => handleOauthUnlink(provider)}
size='lg'
leftIcon={<TrashIcon />}
my='sm'
color='red'
>
Unlink account with {capitalize(provider)}
</Button>
)}
))}
</Group>
</Box>
)}

View file

@ -111,6 +111,9 @@ export interface ConfigOAuth {
discord_client_id?: string;
discord_client_secret?: string;
google_client_id?: string;
google_client_secret?: string;
}
export interface ConfigChunks {

View file

@ -128,6 +128,9 @@ export default function readConfig() {
map('OAUTH_DISCORD_CLIENT_ID', 'string', 'oauth.discord_client_id'),
map('OAUTH_DISCORD_CLIENT_SECRET', 'string', 'oauth.discord_client_secret'),
map('OAUTH_GOOGLE_CLIENT_ID', 'string', 'oauth.google_client_id'),
map('OAUTH_GOOGLE_CLIENT_SECRET', 'string', 'oauth.google_client_secret'),
map('FEATURES_INVITES', 'boolean', 'features.invites'),
map('FEATURES_OAUTH_REGISTRATION', 'boolean', 'features.oauth_registration'),
map('FEATURES_USER_REGISTRATION', 'boolean', 'features.user_registration'),

View file

@ -160,6 +160,9 @@ const validator = s.object({
discord_client_id: s.string.nullable.default(null),
discord_client_secret: s.string.nullable.default(null),
google_client_id: s.string.nullable.default(null),
google_client_secret: s.string.nullable.default(null),
})
.nullish.default(null),
features: s

View file

@ -6,6 +6,7 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => {
// this entire thing will also probably change before the stable release
const ghEnabled = notNull(config.oauth?.github_client_id, config.oauth?.github_client_secret);
const discEnabled = notNull(config.oauth?.discord_client_id, config.oauth?.discord_client_secret);
const googleEnabled = notNull(config.oauth?.google_client_id, config.oauth?.google_client_secret);
const oauth_providers = [];
@ -22,6 +23,13 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => {
link_url: '/api/auth/oauth/discord?state=link',
});
if (googleEnabled)
oauth_providers.push({
name: 'Google',
url: '/api/auth/oauth/google',
link_url: '/api/auth/oauth/google?state=link',
});
return {
props: {
title: config.website.title,

View file

@ -0,0 +1,143 @@
import { createToken } from 'lib/util';
import Logger from 'lib/logger';
import { NextApiReq, NextApiRes } from './withZipline';
import prisma from 'lib/prisma';
import { OauthProviders } from '@prisma/client';
export interface OAuthQuery {
state?: string;
code: string;
host: string;
}
export interface OAuthResponse {
username?: string;
access_token?: string;
refresh_token?: string;
avatar?: string;
error?: string;
error_code?: number;
redirect?: string;
}
export const withOAuth =
(provider: 'discord' | 'github' | 'google', oauth: (query: OAuthQuery) => Promise<OAuthResponse>) =>
async (req: NextApiReq, res: NextApiRes) => {
req.query.host = req.headers.host;
const oauth_resp = await oauth(req.query as unknown as OAuthQuery);
if (oauth_resp.error) {
return res.json({ error: oauth_resp.error }, oauth_resp.error_code || 500);
}
if (oauth_resp.redirect) {
return res.redirect(oauth_resp.redirect);
}
const { code, state } = req.query as { code: string; state?: string };
const existing = await prisma.user.findFirst({
where: {
oauth: {
some: {
provider: provider.toUpperCase() as OauthProviders,
username: oauth_resp.username,
},
},
},
include: {
oauth: true,
},
});
const user = await req.user();
const existingOauth = existing?.oauth?.find((o) => o.provider === provider.toUpperCase());
const existingUserOauth = user?.oauth?.find((o) => o.provider === provider.toUpperCase());
if (state === 'link') {
if (!user) return res.error('not logged in, unable to link account');
if (user.oauth && user.oauth.find((o) => o.provider === provider.toUpperCase()))
return res.error(`account already linked with ${provider}`);
await prisma.user.update({
where: {
id: user.id,
},
data: {
oauth: {
create: {
provider: OauthProviders[provider.toUpperCase()],
token: oauth_resp.access_token,
refresh: oauth_resp.refresh_token || null,
username: oauth_resp.username,
},
},
avatar: oauth_resp.avatar,
},
});
res.setUserCookie(user.id);
Logger.get('user').info(`User ${user.username} (${user.id}) linked account via oauth(${provider})`);
return res.redirect('/');
} else if (user && existingUserOauth) {
await prisma.oAuth.update({
where: {
id: existingUserOauth!.id,
},
data: {
token: oauth_resp.access_token,
refresh: oauth_resp.refresh_token || null,
username: oauth_resp.username,
},
});
res.setUserCookie(user.id);
Logger.get('user').info(`User ${user.username} (${user.id}) logged in via oauth(${provider})`);
return res.redirect('/dashboard');
} else if (existing && existingOauth) {
await prisma.oAuth.update({
where: {
id: existingOauth!.id,
},
data: {
token: oauth_resp.access_token,
refresh: oauth_resp.refresh_token || null,
username: oauth_resp.username,
},
});
res.setUserCookie(existing.id);
Logger.get('user').info(`User ${existing.username} (${existing.id}) logged in via oauth(${provider})`);
return res.redirect('/dashboard');
} else if (existing) {
return res.forbid('username is already taken');
}
const nuser = await prisma.user.create({
data: {
username: oauth_resp.username,
token: createToken(),
oauth: {
create: {
provider: OauthProviders[provider.toUpperCase()],
token: oauth_resp.access_token,
refresh: oauth_resp.refresh_token || null,
username: oauth_resp.username,
},
},
avatar: oauth_resp.avatar,
},
});
Logger.get('user').info(`Created user ${nuser.username} via oauth(${provider})`);
res.setUserCookie(nuser.id);
Logger.get('user').info(`User ${nuser.username} (${nuser.id}) logged in via oauth(${provider})`);
return res.redirect('/dashboard');
};

View file

@ -5,7 +5,7 @@ import { serialize } from 'cookie';
import { sign64, unsign64 } from 'lib/utils/crypto';
import config from 'lib/config';
import prisma from 'lib/prisma';
import { User } from '@prisma/client';
import { OAuth, User } from '@prisma/client';
export interface NextApiFile {
fieldname: string;
@ -16,8 +16,12 @@ export interface NextApiFile {
size: number;
}
interface UserExtended extends User {
oauth: OAuth[];
}
export type NextApiReq = NextApiRequest & {
user: () => Promise<User | null | void>;
user: () => Promise<UserExtended | null>;
getCookie: (name: string) => string | null;
cleanCookie: (name: string) => void;
files?: NextApiFile[];
@ -30,6 +34,7 @@ export type NextApiRes = NextApiResponse & {
json: (json: Record<string, any>, status?: number) => void;
ratelimited: (remaining: number) => void;
setCookie: (name: string, value: unknown, options: CookieSerializeOptions) => void;
setUserCookie: (id: number) => void;
};
export const withZipline =
@ -109,6 +114,9 @@ export const withZipline =
where: {
id: Number(userId),
},
include: {
oauth: true,
},
});
if (!user) return null;
@ -124,6 +132,15 @@ export const withZipline =
res.setCookie = (name: string, value: unknown, options?: CookieSerializeOptions) =>
setCookie(res, name, value, options || {});
res.setUserCookie = (id: number) => {
req.cleanCookie('user');
res.setCookie('user', String(id), {
sameSite: 'lax',
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
};
return handler(req, res);
};

View file

@ -31,3 +31,20 @@ export const discord_auth = {
return res.json();
},
};
export const google_auth = {
oauth_url: (clientId: string, origin: string, state?: string) =>
`https://accounts.google.com/o/oauth2/auth?client_id=${clientId}&redirect_uri=${encodeURIComponent(
`${origin}/api/auth/oauth/google`
)}&response_type=code&access_type=offline&scope=https://www.googleapis.com/auth/userinfo.profile${
state ? `&state=${state}` : ''
}`,
oauth_user: async (access_token: string) => {
const res = await fetch(
`https://people.googleapis.com/v1/people/me?access_token=${access_token}&personFields=names,photos`
);
if (!res.ok) return null;
return res.json();
},
};

View file

@ -1,3 +1,4 @@
import { OAuth } from '@prisma/client';
import { atom, selector } from 'recoil';
export interface User {
@ -11,8 +12,7 @@ export interface User {
avatar?: string;
administrator: boolean;
superAdmin: boolean;
oauth: boolean;
oauthProvider: 'github' | 'discord';
oauth: OAuth[];
id: number;
}

View file

@ -87,3 +87,7 @@ export function percentChange(initial: number, final: number) {
return ((final - initial) / initial) * 100;
}
export function capitalize(str: string) {
return str[0].toUpperCase() + str.slice(1).toLowerCase();
}

View file

@ -35,12 +35,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
const valid = await checkPassword(password, user.password);
if (!valid) return res.forbid('Wrong password');
res.setCookie('user', user.id, {
sameSite: 'lax',
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
res.setUserCookie(user.id);
Logger.get('user').info(`User ${user.username} (${user.id}) logged in`);
return res.json({ success: true });

View file

@ -1,27 +1,33 @@
import prisma from 'lib/prisma';
import { NextApiReq, NextApiRes, withZipline } from 'lib/middleware/withZipline';
import { createToken, getBase64URLFromURL, notNull } from 'lib/util';
import { withZipline } from 'lib/middleware/withZipline';
import { getBase64URLFromURL, notNull } from 'lib/util';
import Logger from 'lib/logger';
import config from 'lib/config';
import { discord_auth } from 'lib/oauth';
import { withOAuth, OAuthResponse, OAuthQuery } from 'lib/middleware/withOAuth';
async function handler(req: NextApiReq, res: NextApiRes) {
if (!config.features.oauth_registration) return res.forbid('oauth registration disabled');
async function handler({ code, state, host }: OAuthQuery): Promise<OAuthResponse> {
if (!config.features.oauth_registration)
return {
error_code: 403,
error: 'oauth registration is disabled',
};
if (!notNull(config.oauth.discord_client_id, config.oauth.discord_client_secret)) {
Logger.get('oauth').error('Discord OAuth is not configured');
return res.bad('Discord OAuth is not configured');
return {
error_code: 401,
error: 'Discord OAuth is not configured',
};
}
const { code, state } = req.query as { code: string; state?: string };
if (!code)
return res.redirect(
discord_auth.oauth_url(
return {
redirect: discord_auth.oauth_url(
config.oauth.discord_client_id,
`${config.core.https ? 'https' : 'http'}://${req.headers.host}`,
`${config.core.https ? 'https' : 'http'}://${host}`,
state
)
);
),
};
const resp = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
@ -33,100 +39,31 @@ async function handler(req: NextApiReq, res: NextApiRes) {
client_secret: config.oauth.discord_client_secret,
code,
grant_type: 'authorization_code',
redirect_uri: `${config.core.https ? 'https' : 'http'}://${req.headers.host}/api/auth/oauth/discord`,
redirect_uri: `${config.core.https ? 'https' : 'http'}://${host}/api/auth/oauth/discord`,
scope: 'identify',
}),
});
if (!resp.ok) return res.error('invalid request');
if (!resp.ok) return { error: 'invalid request' };
const json = await resp.json();
if (!json.access_token) return res.error('no access_token in response');
if (!json.access_token) return { error: 'no access_token in response' };
if (!json.refresh_token) return { error: 'no refresh_token in response' };
const userJson = await discord_auth.oauth_user(json.access_token);
if (!userJson) return res.error('invalid user request');
if (!userJson) return { error: 'invalid user request' };
const avatar = userJson.avatar
? `https://cdn.discordapp.com/avatars/${userJson.id}/${userJson.avatar}.png`
: `https://cdn.discordapp.com/embed/avatars/${userJson.discriminator % 5}.png`;
const avatarBase64 = await getBase64URLFromURL(avatar);
const existing = await prisma.user.findFirst({
where: {
username: userJson.username,
},
});
if (state && state === 'link') {
const user = await req.user();
if (!user) return res.error('not logged in, unable to link account');
if (user.oauth && user.oauthProvider === 'discord')
return res.error('account already linked with discord');
await prisma.user.update({
where: {
id: user.id,
},
data: {
oauth: true,
oauthProvider: 'discord',
oauthAccessToken: json.access_token,
avatar: avatarBase64,
},
});
req.cleanCookie('user');
res.setCookie('user', user.id, {
sameSite: 'lax',
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${user.username} (${user.id}) linked account via oauth(discord)`);
return res.redirect('/');
} else if (existing && existing.oauth && existing.oauthProvider === 'discord') {
await prisma.user.update({
where: {
id: existing.id,
},
data: {
oauthAccessToken: json.access_token,
},
});
req.cleanCookie('user');
res.setCookie('user', existing.id, {
sameSite: 'lax',
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${existing.username} (${existing.id}) logged in via oauth(discord)`);
return res.redirect('/dashboard');
} else if (existing) {
return res.forbid('username is already taken');
}
const user = await prisma.user.create({
data: {
username: userJson.username,
token: createToken(),
oauth: true,
oauthProvider: 'discord',
oauthAccessToken: json.access_token,
avatar: avatarBase64,
},
});
Logger.get('user').info(`Created user ${user.username} via oauth(discord)`);
req.cleanCookie('user');
res.setCookie('user', user.id, {
sameSite: 'lax',
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${user.username} (${user.id}) logged in via oauth(discord)`);
return res.redirect('/dashboard');
return {
username: userJson.username,
avatar: avatarBase64,
access_token: json.access_token,
refresh_token: json.refresh_token,
};
}
export default withZipline(handler);
export default withZipline(withOAuth('discord', handler));

View file

@ -1,21 +1,29 @@
import prisma from 'lib/prisma';
import { NextApiReq, NextApiRes, withZipline } from 'lib/middleware/withZipline';
import { createToken, getBase64URLFromURL, notNull } from 'lib/util';
import { withZipline } from 'lib/middleware/withZipline';
import { getBase64URLFromURL, notNull } from 'lib/util';
import Logger from 'lib/logger';
import config from 'lib/config';
import { github_auth } from 'lib/oauth';
import { withOAuth, OAuthResponse, OAuthQuery } from 'lib/middleware/withOAuth';
async function handler(req: NextApiReq, res: NextApiRes) {
if (!config.features.oauth_registration) return res.forbid('oauth registration disabled');
async function handler({ code, state }: OAuthQuery): Promise<OAuthResponse> {
if (!config.features.oauth_registration)
return {
error_code: 403,
error: 'oauth registration is disabled',
};
if (!notNull(config.oauth.github_client_id, config.oauth.github_client_secret)) {
Logger.get('oauth').error('GitHub OAuth is not configured');
return res.bad('GitHub OAuth is not configured');
return {
error_code: 401,
error: 'GitHub OAuth is not configured',
};
}
const { code, state } = req.query as { code: string; state: string };
if (!code) return res.redirect(github_auth.oauth_url(config.oauth.github_client_id, state));
if (!code)
return {
redirect: github_auth.oauth_url(config.oauth.github_client_id, state),
};
const resp = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
@ -30,93 +38,22 @@ async function handler(req: NextApiReq, res: NextApiRes) {
}),
});
if (!resp.ok) return res.error('invalid request');
if (!resp.ok) return { error: 'invalid request' };
const json = await resp.json();
if (!json.access_token) return res.error('no access_token in response');
if (!json.access_token) return { error: 'no access_token in response' };
const userJson = await github_auth.oauth_user(json.access_token);
if (!userJson) return res.error('invalid user request');
if (!userJson) return { error: 'invalid user request' };
const avatarBase64 = await getBase64URLFromURL(userJson.avatar_url);
const existing = await prisma.user.findFirst({
where: {
username: userJson.login,
},
});
if (state && state === 'link') {
const user = await req.user();
if (!user) return res.error('not logged in, unable to link account');
if (user.oauth && user.oauthProvider === 'github') return res.error('account already linked with github');
await prisma.user.update({
where: {
id: user.id,
},
data: {
oauth: true,
oauthProvider: 'github',
oauthAccessToken: json.access_token,
avatar: avatarBase64,
},
});
req.cleanCookie('user');
res.setCookie('user', user.id, {
sameSite: 'lax',
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${user.username} (${user.id}) linked account via oauth(github)`);
return res.redirect('/');
} else if (existing && existing.oauth && existing.oauthProvider === 'github') {
await prisma.user.update({
where: {
id: existing.id,
},
data: {
oauthAccessToken: json.access_token,
},
});
req.cleanCookie('user');
res.setCookie('user', existing.id, {
sameSite: 'lax',
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${existing.username} (${existing.id}) logged in via oauth(github)`);
return res.redirect('/dashboard');
} else if (existing) {
return res.forbid('username is already taken');
}
const user = await prisma.user.create({
data: {
username: userJson.login,
token: createToken(),
oauth: true,
oauthProvider: 'github',
oauthAccessToken: json.access_token,
avatar: avatarBase64,
},
});
Logger.get('user').info(`Created user ${user.username} via oauth(github)`);
req.cleanCookie('user');
res.setCookie('user', user.id, {
sameSite: 'lax',
expires: new Date(Date.now() + 6.048e8 * 2),
path: '/',
});
Logger.get('user').info(`User ${user.username} (${user.id}) logged in via oauth(github)`);
return res.redirect('/dashboard');
return {
username: userJson.login,
avatar: avatarBase64,
access_token: json.access_token,
};
}
export default withZipline(handler);
export default withZipline(withOAuth('github', handler));

View file

@ -0,0 +1,65 @@
import { withZipline } from 'lib/middleware/withZipline';
import { getBase64URLFromURL, notNull } from 'lib/util';
import Logger from 'lib/logger';
import config from 'lib/config';
import { google_auth } from 'lib/oauth';
import { withOAuth, OAuthResponse, OAuthQuery } from 'lib/middleware/withOAuth';
async function handler({ code, state, host }: OAuthQuery): Promise<OAuthResponse> {
if (!config.features.oauth_registration)
return {
error_code: 403,
error: 'oauth registration is disabled',
};
if (!notNull(config.oauth.google_client_id, config.oauth.google_client_secret)) {
Logger.get('oauth').error('Google OAuth is not configured');
return {
error_code: 401,
error: 'Google OAuth is not configured',
};
}
if (!code)
return {
redirect: google_auth.oauth_url(
config.oauth.google_client_id,
`${config.core.https ? 'https' : 'http'}://${host}`,
state
),
};
const resp = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
code,
client_id: config.oauth.google_client_id,
client_secret: config.oauth.google_client_secret,
redirect_uri: `${config.core.https ? 'https' : 'http'}://${host}/api/auth/oauth/google`,
grant_type: 'authorization_code',
}),
});
if (!resp.ok) return { error: 'invalid request' };
const json = await resp.json();
if (!json.access_token) return { error: 'no access_token in response' };
const userJson = await google_auth.oauth_user(json.access_token);
if (!userJson) return { error: 'invalid user request' };
const avatarBase64 = await getBase64URLFromURL(userJson?.photos[0]?.url);
return {
username: userJson.names[0].displayName,
avatar: avatarBase64,
access_token: json.access_token,
refresh_token: json.refresh_token,
};
}
export default withZipline(withOAuth('google', handler));

View file

@ -1,22 +1,42 @@
import prisma from 'lib/prisma';
import { NextApiReq, NextApiRes, withZipline } from 'lib/middleware/withZipline';
import { OauthProviders } from '@prisma/client';
async function handler(req: NextApiReq, res: NextApiRes) {
const user = await req.user();
if (!user) return res.error('not logged in');
if (req.method === 'DELETE') {
if (!user.password)
if (!user.password && user.oauth.length === 1)
return res.forbid("can't unlink account without a password, please set one then unlink.");
const { provider } = req.body as { provider: OauthProviders };
if (!provider) {
const nuser = await prisma.user.update({
where: { id: user.id },
data: {
oauth: {
deleteMany: {},
},
},
});
delete nuser.password;
return res.json(nuser);
}
const nuser = await prisma.user.update({
where: {
id: user.id,
},
data: {
oauth: false,
oauthProvider: null,
oauthAccessToken: null,
oauth: {
deleteMany: [{ provider }],
},
},
include: {
oauth: true,
},
});
@ -24,11 +44,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
return res.json(nuser);
} else {
return res.json({
enabled: user.oauth,
provider: user.oauthProvider,
access_token: user.oauthAccessToken,
});
return res.json(user.oauth);
}
}

View file

@ -141,6 +141,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
username: true,
domains: true,
avatar: true,
oauth: true,
},
});

View file

@ -3,7 +3,7 @@ import { hashPassword } from 'lib/util';
import { NextApiReq, NextApiRes, withZipline } from 'middleware/withZipline';
import Logger from 'lib/logger';
import config from 'lib/config';
import { discord_auth, github_auth } from 'lib/oauth';
import { discord_auth, github_auth, google_auth } from 'lib/oauth';
async function handler(req: NextApiReq, res: NextApiRes) {
const user = await req.user();
@ -11,33 +11,112 @@ async function handler(req: NextApiReq, res: NextApiRes) {
if (user.oauth) {
// this will probably change before the stable release
if (user.oauthProvider === 'github') {
const resp = await github_auth.oauth_user(user.oauthAccessToken);
if (user.oauth.find((o) => o.provider === 'GITHUB')) {
const resp = await github_auth.oauth_user(user.oauth.find((o) => o.provider === 'GITHUB').token);
if (!resp) {
req.cleanCookie('user');
Logger.get('user').info(`User ${user.username} (${user.id}) logged out (oauth token expired)`);
return res.json({
error: 'oauth token expired',
redirect_uri: github_auth.oauth_url(config.oauth.github_client_id),
});
}
} else if (user.oauthProvider === 'discord') {
} else if (user.oauth.find((o) => o.provider === 'DISCORD')) {
const resp = await fetch('https://discord.com/api/users/@me', {
headers: {
Authorization: `Bearer ${user.oauthAccessToken}`,
Authorization: `Bearer ${user.oauth.find((o) => o.provider === 'DISCORD').token}`,
},
});
if (!resp.ok) {
req.cleanCookie('user');
Logger.get('user').info(`User ${user.username} (${user.id}) logged out (oauth token expired)`);
const provider = user.oauth.find((o) => o.provider === 'DISCORD');
if (!provider.refresh)
return res.json({
error: 'oauth token expired',
redirect_uri: discord_auth.oauth_url(
config.oauth.discord_client_id,
`${config.core.https ? 'https' : 'http'}://${req.headers.host}`
),
});
return res.json({
error: 'oauth token expired',
redirect_uri: discord_auth.oauth_url(
config.oauth.discord_client_id,
`${config.core.https ? 'https' : 'http'}://${req.headers.host}`
),
const resp2 = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: config.oauth.discord_client_id,
client_secret: config.oauth.discord_client_secret,
grant_type: 'refresh_token',
refresh_token: provider.refresh,
}),
});
if (!resp2.ok)
return res.json({
error: 'oauth token expired',
redirect_uri: discord_auth.oauth_url(
config.oauth.discord_client_id,
`${config.core.https ? 'https' : 'http'}://${req.headers.host}`
),
});
const json = await resp2.json();
await prisma.oAuth.update({
where: {
id: provider.id,
},
data: {
token: json.access_token,
refresh: json.refresh_token,
},
});
}
} else if (user.oauth.find((o) => o.provider === 'GOOGLE')) {
const resp = await fetch(
`https://people.googleapis.com/v1/people/me?access_token=${
user.oauth.find((o) => o.provider === 'GOOGLE').token
}&personFields=names,photos`
);
if (!resp.ok) {
const provider = user.oauth.find((o) => o.provider === 'GOOGLE');
if (!provider.refresh)
return res.json({
error: 'oauth token expired',
redirect_uri: google_auth.oauth_url(
config.oauth.google_client_id,
`${config.core.https ? 'https' : 'http'}://${req.headers.host}`
),
});
const resp2 = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: config.oauth.google_client_id,
client_secret: config.oauth.google_client_secret,
grant_type: 'refresh_token',
refresh_token: provider.refresh,
}),
});
if (!resp2.ok)
return res.json({
error: 'oauth token expired',
redirect_uri: google_auth.oauth_url(
config.oauth.google_client_id,
`${config.core.https ? 'https' : 'http'}://${req.headers.host}`
),
});
const json = await resp2.json();
await prisma.oAuth.update({
where: {
id: provider.id,
},
data: {
token: json.access_token,
refresh: json.refresh_token,
},
});
}
}
@ -122,8 +201,6 @@ async function handler(req: NextApiReq, res: NextApiRes) {
where: { id: user.id },
data: { domains },
});
return res.json({ domains });
}
const newUser = await prisma.user.findFirst({
@ -143,6 +220,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
username: true,
domains: true,
avatar: true,
oauth: true,
},
});

View file

@ -43,7 +43,7 @@ async function handler(req: NextApiReq, res: NextApiRes) {
for (let i = 0; i !== files.length; ++i) {
try {
await datasource.delete(files[i].file);
} catch (e) {}
} catch {}
}
const { count } = await prisma.image.deleteMany({

View file

@ -1,11 +1,11 @@
import { Button, Center, TextInput, Title, PasswordInput, Divider } from '@mantine/core';
import { Button, Center, TextInput, Title, PasswordInput, Divider, Group } from '@mantine/core';
import { useForm } from '@mantine/form';
import Link from 'next/link';
import useFetch from 'hooks/useFetch';
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import Head from 'next/head';
import { GitHubIcon, DiscordIcon } from 'components/icons';
import { GitHubIcon, DiscordIcon, GoogleIcon } from 'components/icons';
export { getServerSideProps } from 'middleware/getServerSideProps';
export default function Login({ title, user_registration, oauth_registration, oauth_providers: unparsed }) {
@ -16,6 +16,7 @@ export default function Login({ title, user_registration, oauth_registration, oa
const icons = {
GitHub: GitHubIcon,
Discord: DiscordIcon,
Google: GoogleIcon,
};
for (const provider of oauth_providers) {
@ -67,18 +68,30 @@ export default function Login({ title, user_registration, oauth_registration, oa
</Head>
<Center sx={{ height: '100vh' }}>
<div>
<Title align='center'>{title}</Title>
<form onSubmit={form.onSubmit((v) => onSubmit(v))}>
<TextInput size='lg' id='username' label='Username' {...form.getInputProps('username')} />
<PasswordInput size='lg' id='password' label='Password' {...form.getInputProps('password')} />
<Title size={70} align='center'>
{title}
</Title>
<Button size='lg' type='submit' fullWidth mt='sm'>
<form onSubmit={form.onSubmit((v) => onSubmit(v))}>
<TextInput my='sm' size='lg' id='username' label='Username' {...form.getInputProps('username')} />
<PasswordInput
my='sm'
size='lg'
id='password'
label='Password'
{...form.getInputProps('password')}
/>
<Button size='lg' my='sm' fullWidth type='submit'>
Login
</Button>
</form>
{user_registration && (
<>
<Divider label='or' labelPosition='center' my='sm' />
<Divider my='sm' label='or' labelPosition='center'>
or
</Divider>
<Link href='/auth/register' passHref legacyBehavior>
<Button size='lg' fullWidth component='a'>
Register
@ -88,10 +101,12 @@ export default function Login({ title, user_registration, oauth_registration, oa
)}
{oauth_registration && (
<>
<Divider label='or' labelPosition='center' my='sm' />
<Divider my='sm' label='or' labelPosition='center'>
or
</Divider>
{oauth_providers.map(({ url, name, Icon }, i) => (
<Link key={i} href={url} passHref legacyBehavior>
<Button size='lg' fullWidth leftIcon={<Icon />} component='a' my={8}>
<Button size='lg' fullWidth leftIcon={<Icon colorScheme='manage' />} component='a' my='sm'>
Login in with {name}
</Button>
</Link>