Compare commits

...

21 Commits
2.5.2 ... 2.5.7

Author SHA1 Message Date
diced
19d2c63ea9 2.5.7 2020-11-25 21:04:33 -08:00
diced
70b5ff7562 no file type? 2020-11-25 21:04:24 -08:00
dicedtomato
15367f0495 Update README.md 2020-11-20 11:50:11 -08:00
diced
306b8812e2 2.5.5 2020-11-12 21:57:00 -08:00
diced
06c57851e4 fix bug 2020-11-12 21:56:53 -08:00
diced
0063c97e01 2.5.4 2020-11-12 21:30:06 -08:00
diced
cdf7af0283 shorten urling 2020-11-12 21:25:05 -08:00
diced
1b4c8373ea stats 2020-11-12 20:53:58 -08:00
diced
585b737c5f make zipline volume use custom dir 2020-11-12 10:08:34 -08:00
diced
b1cfed834c make starting msg under log 2020-11-12 10:01:30 -08:00
diced
ccde532880 fixes 2020-11-12 09:58:52 -08:00
diced
bc7a7a8c24 enforcing single line if statements 2020-11-12 09:42:09 -08:00
diced
27ec3de3ac add config option for logging 2020-11-12 09:30:44 -08:00
diced
96c0a72178 phase out using Error into normal requests 2020-11-12 09:26:46 -08:00
diced
dafbe647af route logging 2020-11-12 09:26:24 -08:00
diced
b679239109 notify invalid configs 2020-11-11 22:10:47 -08:00
diced
5de1293949 fix disabling mfa 2020-11-11 21:59:04 -08:00
diced
134ee7f38e new 404 2020-11-11 21:55:38 -08:00
diced
0c365d6364 updated logging 2020-11-11 21:32:50 -08:00
diced
12ad45387a 2.5.3 2020-11-11 13:13:15 -08:00
diced
f6d62388fa fix no image path 2020-11-11 13:13:07 -08:00
26 changed files with 1312 additions and 318 deletions

View File

@@ -29,6 +29,7 @@ module.exports = {
'linebreak-style': ['error', 'unix'],
quotes: ['error', 'single'],
semi: ['error', 'always'],
'comma-dangle': ['error', 'never']
'comma-dangle': ['error', 'never'],
'nonblock-statement-body-position': ['error', 'beside']
}
};

View File

@@ -1,15 +1,15 @@
<p align="center"><img src="https://raw.githubusercontent.com/ZiplineProject/zipline/next/public/zipline_small.png"/></p>
![Version](https://img.shields.io/github/package-json/v/dicedtomatoreal/zipline)
![LICENCE](https://img.shields.io/github/license/dicedtomatoreal/zipline)
![Version](https://img.shields.io/github/package-json/v/diced/zipline)
![LICENCE](https://img.shields.io/github/license/diced/zipline)
[![Discord](https://img.shields.io/discord/729771078196527176)](https://discord.gg/AtTSecwqeV)
![Stars](https://img.shields.io/github/stars/dicedtomatoreal/zipline)
![GitHub repo size](https://img.shields.io/github/repo-size/dicedtomatoreal/zipline)
![GitHub last commit (branch)](https://img.shields.io/github/last-commit/dicedtomatoreal/zipline/next)
![Stars](https://img.shields.io/github/stars/diced/zipline)
![GitHub repo size](https://img.shields.io/github/repo-size/diced/zipline)
![GitHub last commit (branch)](https://img.shields.io/github/last-commit/diced/zipline/next)
<br>
![David](https://img.shields.io/david/dicedtomatoreal/zipline)
![David](https://img.shields.io/david/dev/dicedtomatoreal/zipline)
![GitHub package.json dependency version (prod)](https://img.shields.io/github/package-json/dependency-version/dicedtomatoreal/zipline/react)
![David](https://img.shields.io/david/diced/zipline)
![David](https://img.shields.io/david/dev/diced/zipline)
![GitHub package.json dependency version (prod)](https://img.shields.io/github/package-json/dependency-version/diced/zipline/react)
# Zipline
The best and only **React + Next.js** ShareX / File Uploader you would ever want.
@@ -19,7 +19,7 @@ Wondering how Zipline compares to other popular uploaders? We have done some ben
| Uploader | Average ms (3 batches/1.5k files) |
|-|-|
| **[Zipline](https://github.com/dicedtomatoreal/zipline)** | **61 ms** |
| **[Zipline](https://github.com/diced/zipline)** | **61 ms** |
| [ShareX-Upload-Server](https://github.com/TannerReynolds/ShareX-Upload-Server) | 86 ms |
*Note: there were 3 batches of 1.5k requests, the average ms of each was averaged again*<br>
@@ -36,4 +36,3 @@ Wondering how Zipline compares to other popular uploaders? We have done some ben
# Installing
[See how to install here](https://zipline.diced.wtf/docs/)

View File

@@ -1,6 +1,6 @@
{
"name": "zipline-next",
"version": "2.5.2",
"version": "2.5.7",
"private": true,
"dependencies": {
"@dicedtomato/colors": "^1.0.3",
@@ -40,6 +40,7 @@
"scripts": {
"format": "prettier --write .",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"dev": "ts-node src",
"dev:verbose": "VERBOSE=true ts-node src",
"build": "next build && tsc -p .",
@@ -61,6 +62,7 @@
"eslint-plugin-react": "^7.21.3",
"mongodb": "^3.6.2",
"prettier": "2.1.2",
"release": "^6.3.0",
"ts-node": "^9.0.0",
"typescript": "^4.0.3"
}

View File

@@ -4,14 +4,14 @@ const { stringify } = require('toml-patch');
const { writeFileSync } = require('fs');
const { join } = require('path');
const createDockerCompose = port => {
const createDockerCompose = (port, dir) => {
return `version: "3"
services:
zipline:
ports:
- "${port}:${port}"
volumes:
- "${join(process.cwd(), 'uploads')}:/opt/zipline/uploads"
- "${join(process.cwd(), dir)}:${join('/opt/zipline', dir)}"
build: .
tty: true`;
};
@@ -160,7 +160,7 @@ const base = {
if (docker.useDocker) {
config.core.host = '0.0.0.0';
console.log('Generating docker-compose.yml...');
writeFileSync('docker-compose.yml', createDockerCompose(config.core.port));
writeFileSync('docker-compose.yml', createDockerCompose(config.core.port, config.uploader.directory));
console.log(
'Head to https://zipline.diced.wtf/docs/docker to learn how to run with docker.'
);

View File

@@ -98,6 +98,12 @@ export default function ManageUser({ config }: { config: Config }) {
}
};
const disableMfaAndClose = async () => {
const d = await (await fetch('/api/mfa/disable')).json();
if (!d.error) setMfaDialogOpen(false);
};
return (
<React.Fragment>
<Snackbar
@@ -115,7 +121,7 @@ export default function ManageUser({ config }: { config: Config }) {
</Snackbar>
<Dialog
open={mfaDialogOpen}
onClose={() => setMfaDialogOpen(false)}
onClose={disableMfaAndClose}
aria-labelledby='enable-mfa'
aria-describedby='mfa-desc'
>
@@ -143,6 +149,9 @@ export default function ManageUser({ config }: { config: Config }) {
</Grid>
</DialogContent>
<DialogActions>
<Button color='primary' autoFocus onClick={disableMfaAndClose}>
Disable
</Button>
<Button color='primary' autoFocus onClick={tryEnablingMfa}>
Enable
</Button>

View File

@@ -5,7 +5,6 @@ import dark from '../lib/themes/dark';
import light from '../lib/themes/light';
export default function ZiplineTheming({ Component, pageProps, theme }) {
console.log(theme);
return (
<ThemeProvider theme={theme == 'light' ? light : dark}>
<CssBaseline />

View File

@@ -12,28 +12,44 @@ import { Console } from './lib/logger';
import { AddressInfo } from 'net';
import { magenta, bold, green, reset, blue, red } from '@dicedtomato/colors';
import { Configuration } from './lib/Config';
import { UserController } from './lib/api/controllers/UserController';
import { RootController } from './lib/api/controllers/RootController';
import { UserController } from './lib/controllers/UserController';
import { RootController } from './lib/controllers/RootController';
import { join } from 'path';
import { ImagesController } from './lib/api/controllers/ImagesController';
import { URLSController } from './lib/api/controllers/URLSController';
import { ImagesController } from './lib/controllers/ImagesController';
import { URLSController } from './lib/controllers/URLSController';
import { checkVersion } from './lib/Util';
import { existsSync, readFileSync } from 'fs';
import { Image } from './lib/entities/Image';
import { User } from './lib/entities/User';
import { Zipline } from './lib/entities/Zipline';
import { URL } from './lib/entities/URL';
import { MultiFactorController } from './lib/api/controllers/MultiFactorController';
import { MultiFactorController } from './lib/controllers/MultiFactorController';
const dev = process.env.NODE_ENV !== 'production';
(async () => {
if (await checkVersion())
Console.logger('Zipline').info(
'running an outdated version of zipline, please update soon!'
);
if (await checkVersion()) Console.logger('Zipline').info(
'running an outdated version of zipline, please update soon!'
);
})();
console.log(`
Console.logger(Configuration).verbose('searching for config...');
const config = Configuration.readConfig();
if (!config) {
Console.logger(Configuration).error(
`could not find a Zipline.toml file in ${process.cwd()}`
);
process.exit(0);
}
if (!config.core || !config.database) {
Console.logger('Zipline').error(
'configuration seems to be invalid, did you generate a config? https://zipline.diced.wtf/docs/auto'
);
process.exit(0);
}
if (config.core.log) console.log(`
${magenta(text('Zipline'))}
Version : ${blue(
@@ -48,15 +64,6 @@ Mode : ${bold(dev ? red('dev') : green('production'))}
Verbose : ${bold(process.env.VERBOSE ? red('yes') : green('no'))}
`);
Console.logger(Configuration).verbose('searching for config...');
const config = Configuration.readConfig();
if (!config) {
Console.logger(Configuration).error(
`could not find a Zipline.toml file in ${process.cwd()}`
);
process.exit(0);
}
const dir = config.uploader.directory ? config.uploader.directory : 'uploads';
const path = dir.charAt(0) == '/' ? dir : join(process.cwd(), dir);
@@ -77,11 +84,10 @@ server.register(fastifyRateLimit, {
global: false
});
if (dev)
server.get('/_next/*', async (req, reply) => {
await handle(req.raw, reply.raw);
return (reply.sent = true);
});
if (dev) server.get('/_next/*', async (req, reply) => {
await handle(req.raw, reply.raw);
return (reply.sent = true);
});
server.all('/*', async (req, reply) => {
await handle(req.raw, reply.raw);
@@ -210,3 +216,14 @@ server.addHook('preHandler', async (req, reply) => {
return (reply.sent = true);
}
});
server.addHook('onResponse', (req, res, done) => {
if (!req.url.startsWith('/_next') && config.core.log) {
const status =
res.statusCode !== 200
? bold(red(res.statusCode.toString()))
: bold(green(res.statusCode.toString()));
Console.logger('server').info(`${status} ${req.url} was accessed`);
}
done();
});

View File

@@ -2,7 +2,7 @@ import { readFileSync } from 'fs';
import { resolve } from 'path';
import { parse } from 'toml-patch';
import { ConnectionOptions } from 'typeorm';
import { WebhookHelper, WebhookType } from './Webhooks';
import { Webhooks, WebhookType } from './Webhooks';
export interface Config {
database: ConnectionOptions;
@@ -49,6 +49,7 @@ export interface ConfigCore {
ratelimiter?: ConfigCoreRateLimiter;
theme?: 'dark' | 'light';
mfa?: boolean;
log?: boolean;
}
export interface ConfigWebhooks {
@@ -78,8 +79,7 @@ export class Configuration {
try {
const data = readFileSync(resolve(process.cwd(), 'Zipline.toml'), 'utf8');
const parsed = parse(data);
if (parsed.webhooks)
parsed.webhooks.events = WebhookHelper.convert(parsed.webhooks.events);
if (parsed.webhooks) parsed.webhooks.events = Webhooks.convert(parsed.webhooks.events);
return parsed;
} catch (e) {
return null;

View File

@@ -6,6 +6,7 @@ import { compare } from 'semver';
import { Zipline } from './entities/Zipline';
import { readFileSync } from 'fs';
import { join } from 'path';
import { FastifyReply } from 'fastify';
const config = Configuration.readConfig();
@@ -14,8 +15,7 @@ export function createRandomId(
charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
) {
let result = '';
for (let i = 0; i < length; i++)
result += charset.charAt(Math.floor(Math.random() * charset.length));
for (let i = 0; i < length; i++) result += charset.charAt(Math.floor(Math.random() * charset.length));
return result;
}
@@ -58,4 +58,11 @@ export async function checkVersion(): Promise<boolean> {
const compared = compare(currentVersion, latestVersion);
return compared == 0 || compared == 1 ? false : true;
}
export async function sendError(reply: FastifyReply, error: string) {
return reply.code(400).send({
code: 400,
error
});
}

5
src/lib/WebUtil.ts Normal file
View File

@@ -0,0 +1,5 @@
export function createURL(href: string, route: string, file: string): string {
const t = new URL(href);
t.pathname = `${route}/${file}`;
return t.toString();
}

View File

@@ -46,7 +46,7 @@ export type WebhookSendText =
| 'user_delete'
| 'user_edit';
export class WebhookHelper {
export class Webhooks {
public static convert(strings: WebhookSendText[]) {
return strings.map(x => WebhookType[x.toUpperCase()]);
}
@@ -81,11 +81,11 @@ export class WebhookHelper {
},
body: JSON.stringify({
username: config.webhooks.username,
content: WebhookHelper.parseContent(content, data)
content: Webhooks.parseContent(content, data)
})
});
} catch (e) {
Console.logger(WebhookHelper).error(e);
Console.logger(Webhooks).error(e);
}
}
}

View File

@@ -1,7 +0,0 @@
export class MissingBodyData extends Error {}
export class LoginError extends Error {}
export class NotAdministratorError extends Error {}
export class UserExistsError extends Error {}
export class UserNotFoundError extends Error {}
export class UserCredentialsError extends Error {}
export class AuthError extends Error {}

View File

@@ -9,12 +9,11 @@ import {
DELETE
} from 'fastify-decorators';
import { Repository } from 'typeorm';
import { Image } from '../../entities/Image';
import { LoginError } from '../APIErrors';
import { Configuration, ConfigWebhooks } from '../../Config';
import { Console } from '../../logger';
import { readBaseCookie } from '../../Util';
import { WebhookHelper, WebhookType } from '../../Webhooks';
import { Image } from '../entities/Image';
import { Configuration, ConfigWebhooks } from '../Config';
import { Console } from '../logger';
import { readBaseCookie, sendError } from '../Util';
import { Webhooks, WebhookType } from '../Webhooks';
const config = Configuration.readConfig();
@@ -24,11 +23,11 @@ export class ImagesController {
private instance!: FastifyInstance;
private images: Repository<Image> = this.instance.orm.getRepository(Image);
private webhooks: ConfigWebhooks = WebhookHelper.conf(config);
private webhooks: ConfigWebhooks = Webhooks.conf(config);
@GET('/')
async allImages(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const images = await this.images.find({
where: {
@@ -44,7 +43,7 @@ export class ImagesController {
req: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const image = await this.images.findOne({
where: {
@@ -53,24 +52,30 @@ export class ImagesController {
}
});
if (!image) throw new Error('No image');
if (!image) return sendError(reply, 'No image');
this.images.delete({
id: req.params.id
});
const dir = config.uploader.directory ? config.uploader.directory : 'uploads';
const path = join(dir.charAt(0) == '/' ? dir : join(process.cwd(), dir), image.file);
const dir = config.uploader.directory
? config.uploader.directory
: 'uploads';
const path = join(
dir.charAt(0) == '/' ? dir : join(process.cwd(), dir),
image.file
);
try {
unlinkSync(path);
Console.logger(Image).info(`image ${image.id} was deleted`);
if (this.webhooks.events.includes(WebhookType.DELETE_IMAGE))
WebhookHelper.sendWebhook(this.webhooks.upload.content, {
image,
host: `${config.core.secure ? 'https' : 'http'}://${req.hostname}${config.uploader.route}/`
});
if (this.webhooks.events.includes(WebhookType.DELETE_IMAGE)) Webhooks.sendWebhook(this.webhooks.upload.content, {
image,
host: `${config.core.secure ? 'https' : 'http'}://${req.hostname}${
config.uploader.route
}/`
});
return reply.send(image);
} catch (e) {
@@ -81,7 +86,7 @@ export class ImagesController {
@GET('/recent')
async recentImages(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const images = await this.images.find({
where: {
@@ -94,7 +99,7 @@ export class ImagesController {
@GET('/chunk')
async pages(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const images = await this.images.find({
where: {

View File

@@ -7,14 +7,18 @@ import {
POST
} from 'fastify-decorators';
import { Repository } from 'typeorm';
import { User } from '../../entities/User';
import { User } from '../entities/User';
import { totp, generateSecret, otpauthURL } from 'speakeasy';
import { toDataURL } from 'qrcode';
import { checkPassword, createBaseCookie, readBaseCookie } from '../../Util';
import { LoginError, MissingBodyData, UserNotFoundError } from '../APIErrors';
import { Console } from '../../logger';
import { WebhookType, WebhookHelper } from '../../Webhooks';
import { Configuration, ConfigWebhooks } from '../../Config';
import {
checkPassword,
createBaseCookie,
readBaseCookie,
sendError
} from '../Util';
import { Console } from '../logger';
import { WebhookType, Webhooks } from '../Webhooks';
import { Configuration, ConfigWebhooks } from '../Config';
const config = Configuration.readConfig();
@@ -25,11 +29,11 @@ export class MultiFactorController {
private users: Repository<User> = this.instance.orm.getRepository(User);
private logger: Console = Console.logger(User);
private webhooks: ConfigWebhooks = WebhookHelper.conf(config);
private webhooks: ConfigWebhooks = Webhooks.conf(config);
@GET('/qrcode')
async qrcode(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
let user = await this.users.findOne({
where: {
id: readBaseCookie(req.cookies.zipline)
@@ -62,7 +66,7 @@ export class MultiFactorController {
@GET('/disable')
async disable(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const user = await this.users.findOne({
where: {
id: readBaseCookie(req.cookies.zipline)
@@ -73,6 +77,7 @@ export class MultiFactorController {
this.users.save(user);
this.logger.info(`disabled mfa ${user.username} (${user.id})`);
reply.send({ disabled: true });
}
@@ -84,9 +89,9 @@ export class MultiFactorController {
}>,
reply: FastifyReply
) {
if (req.cookies.zipline) throw new LoginError('Already logged in.');
if (!req.body.username) throw new MissingBodyData('Missing username.');
if (!req.body.password) throw new MissingBodyData('Missing uassword.');
if (req.cookies.zipline) return sendError(reply, 'Already logged in.');
if (!req.body.username) return sendError(reply, 'Missing username.');
if (!req.body.password) return sendError(reply, 'Missing uassword.');
const user = await this.users.findOne({
where: {
@@ -94,13 +99,12 @@ export class MultiFactorController {
}
});
if (!user)
throw new UserNotFoundError(`User "${req.body.username}" was not found.`);
if (!user) return sendError(reply, `User "${req.body.username}" was not found.`);
if (!checkPassword(req.body.password, user.password)) {
this.logger.error(
`${user.username} (${user.id}) tried to login but failed`
`${user.username} (${user.id}) tried to login but failed with mfa`
);
throw new LoginError('Wrong credentials!');
return sendError(reply, 'Wrong credentials!');
}
delete user.password;
@@ -116,11 +120,10 @@ export class MultiFactorController {
maxAge: 1036800000
});
this.logger.info(`${user.username} (${user.id}) logged in`);
if (this.webhooks.events.includes(WebhookType.LOGIN))
WebhookHelper.sendWebhook(this.webhooks.login.content, {
user
});
this.logger.info(`${user.username} (${user.id}) logged in with mfa`);
if (this.webhooks.events.includes(WebhookType.LOGIN)) Webhooks.sendWebhook(this.webhooks.login.content, {
user
});
return reply.send({ user, passed });
}

View File

@@ -12,16 +12,21 @@ import { join } from 'path';
import { Repository } from 'typeorm';
import { pipeline } from 'stream';
import { promisify } from 'util';
import { Image } from '../../entities/Image';
import { User } from '../../entities/User';
import { AuthError } from '../APIErrors';
import { Configuration, ConfigWebhooks } from '../../Config';
import { createRandomId, getFirst } from '../../Util';
import { Console } from '../../logger';
import { WebhookHelper, WebhookType } from '../../Webhooks';
import { Image } from '../entities/Image';
import { User } from '../entities/User';
import { Configuration, ConfigWebhooks } from '../Config';
import { createRandomId, getFirst, sendError } from '../Util';
import { Console } from '../logger';
import { Webhooks, WebhookType } from '../Webhooks';
const pump = promisify(pipeline);
const config = Configuration.readConfig();
if (!config.core || !config.database) {
Console.logger('Zipline').error(
'configuration seems to be invalid, did you generate a config? https://zipline.diced.wtf/docs/auto'
);
process.exit(0);
}
const rateLimiterConfig = config.core.ratelimiter
? {
config: {
@@ -40,7 +45,7 @@ export class RootController {
private users: Repository<User> = this.instance.orm.getRepository(User);
private images: Repository<Image> = this.instance.orm.getRepository(Image);
private webhooks: ConfigWebhooks = WebhookHelper.conf(config);
private webhooks: ConfigWebhooks = Webhooks.conf(config);
private logger: Console = Console.logger(Image);
@GET('/first')
@@ -56,7 +61,7 @@ export class RootController {
@GET('/users')
async allUsers(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new Error('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const users = await this.users.find();
const final = [];
@@ -71,7 +76,7 @@ export class RootController {
@GET('/statistics')
async stats(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new Error('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const images = await this.images.find();
const users = await this.users.find();
@@ -104,26 +109,23 @@ export class RootController {
@POST('/upload', rateLimiterConfig)
async loginStatus(req: FastifyRequest, reply: FastifyReply) {
if (!req.headers.authorization)
return new AuthError('No authorization header!');
if (!req.headers.authorization) return sendError(reply, 'No authorization header!');
const user = await this.users.findOne({
where: {
token: req.headers.authorization
}
});
if (!user) return new AuthError('Incorrect token!');
if (!user) return sendError(reply, 'Incorrect token!');
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore stupid multipart types smh
const data: Multipart = await req.file();
if (!existsSync(config.uploader.directory))
mkdirSync(config.uploader.directory);
if (!existsSync(config.uploader.directory)) mkdirSync(config.uploader.directory);
const ext = data.filename.split('.')[1];
if (config.uploader.blacklisted.includes(ext))
throw new Error('Blacklisted file extension!');
const ext = data.mimetype === 'application/octet-stream' ? 'bin' : data.filename.split('.')[1];
if (config.uploader.blacklisted.includes(ext)) return sendError(reply, 'Blacklisted file extension!');
const fileName = config.uploader.original
? data.filename.split('.')[0]
@@ -146,13 +148,12 @@ export class RootController {
config.uploader.rich_content_route
? config.uploader.rich_content_route
: config.uploader.route
}/`;
}/${fileName}.${ext}`;
if (this.webhooks.events.includes(WebhookType.UPLOAD))
WebhookHelper.sendWebhook(this.webhooks.upload.content, {
image,
host
});
if (this.webhooks.events.includes(WebhookType.UPLOAD)) Webhooks.sendWebhook(this.webhooks.upload.content, {
image,
host
});
reply.send(host);
}

View File

@@ -8,13 +8,12 @@ import {
POST
} from 'fastify-decorators';
import { Repository } from 'typeorm';
import { URL } from '../../entities/URL';
import { User } from '../../entities/User';
import { LoginError } from '../APIErrors';
import { Configuration, ConfigWebhooks } from '../../Config';
import { Console } from '../../logger';
import { createRandomId, readBaseCookie } from '../../Util';
import { WebhookType, WebhookHelper } from '../../Webhooks';
import { URL } from '../entities/URL';
import { User } from '../entities/User';
import { Configuration, ConfigWebhooks } from '../Config';
import { Console } from '../logger';
import { createRandomId, readBaseCookie, sendError } from '../Util';
import { WebhookType, Webhooks } from '../Webhooks';
const config = Configuration.readConfig();
@@ -26,11 +25,11 @@ export class URLSController {
private urls: Repository<URL> = this.instance.orm.getRepository(URL);
private users: Repository<User> = this.instance.orm.getRepository(User);
private logger: Console = Console.logger(URL);
private webhooks: ConfigWebhooks = WebhookHelper.conf(config);
private webhooks: ConfigWebhooks = Webhooks.conf(config);
@GET('/')
async allURLS(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const all = await this.urls.find({
where: {
@@ -46,7 +45,7 @@ export class URLSController {
req: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const url = await this.urls.findOne({
where: {
@@ -55,7 +54,7 @@ export class URLSController {
}
});
if (!url) throw new Error('No url');
if (!url) return sendError(reply, 'No url');
this.logger.verbose(`attempting to delete url ${url.id}`);
this.urls.delete({
@@ -63,11 +62,12 @@ export class URLSController {
});
this.logger.info(`url ${url.id} was deleted`);
if (this.webhooks.events.includes(WebhookType.DELETE_URL))
WebhookHelper.sendWebhook(this.webhooks.delete_url.content, {
url,
host: `${config.core.secure ? 'https' : 'http'}://${req.hostname}${config.urls.route}/`
});
if (this.webhooks.events.includes(WebhookType.DELETE_URL)) Webhooks.sendWebhook(this.webhooks.delete_url.content, {
url,
host: `${config.core.secure ? 'https' : 'http'}://${req.hostname}${
config.urls.route
}/`
});
return reply.send(url);
}
@@ -77,7 +77,7 @@ export class URLSController {
req: FastifyRequest<{ Body: { vanity: string; url: string } }>,
reply: FastifyReply
) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
if (config.urls.vanity && req.body.vanity) {
const existingVanity = await this.urls.findOne({
@@ -85,7 +85,7 @@ export class URLSController {
vanity: req.body.vanity
}
});
if (existingVanity) throw new Error('There is an existing vanity!');
if (existingVanity) return sendError(reply, 'There is an existing vanity!');
}
const user = await this.users.findOne({
@@ -94,7 +94,7 @@ export class URLSController {
}
});
if (!user) throw new LoginError('No user');
if (!user) return sendError(reply, 'No user');
const id = createRandomId(config.urls.length);
@@ -104,11 +104,12 @@ export class URLSController {
);
this.logger.info(`saved url ${url.id}`);
if (this.webhooks.events.includes(WebhookType.SHORTEN))
WebhookHelper.sendWebhook(this.webhooks.shorten.content, {
url,
host: `${config.core.secure ? 'https' : 'http'}://${req.hostname}${config.urls.route}/`
});
if (this.webhooks.events.includes(WebhookType.SHORTEN)) Webhooks.sendWebhook(this.webhooks.shorten.content, {
url,
host: `${config.core.secure ? 'https' : 'http'}://${req.hostname}${
config.urls.route
}/`
});
return reply.send(url);
}

View File

@@ -9,25 +9,21 @@ import {
DELETE
} from 'fastify-decorators';
import { Repository } from 'typeorm';
import { User } from '../../entities/User';
import { Zipline } from '../../entities/Zipline';
import {
UserNotFoundError,
MissingBodyData,
LoginError,
UserExistsError
} from '../APIErrors';
import { Configuration, ConfigWebhooks } from '../../Config';
import { Console } from '../../logger';
import { User } from '../entities/User';
import { Image } from '../entities/Image';
import { Zipline } from '../entities/Zipline';
import { Configuration, ConfigWebhooks } from '../Config';
import { Console } from '../logger';
import {
checkPassword,
createBaseCookie,
createToken,
encryptPassword,
getFirst,
readBaseCookie
} from '../../Util';
import { WebhookType, WebhookHelper } from '../../Webhooks';
readBaseCookie,
sendError
} from '../Util';
import { WebhookType, Webhooks } from '../Webhooks';
const config = Configuration.readConfig();
@@ -37,8 +33,9 @@ export class UserController {
private instance!: FastifyInstance;
private users: Repository<User> = this.instance.orm.getRepository(User);
private images: Repository<Image> = this.instance.orm.getRepository(Image);
private logger: Console = Console.logger(User);
private webhooks: ConfigWebhooks = WebhookHelper.conf(config);
private webhooks: ConfigWebhooks = Webhooks.conf(config);
@GET('/login-status')
async loginStatus(req: FastifyRequest, reply: FastifyReply) {
@@ -49,18 +46,42 @@ export class UserController {
@GET('/')
async currentUser(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const user = await this.users.findOne({
where: {
id: readBaseCookie(req.cookies.zipline)
}
});
// eslint-disable-next-line quotes
if (!user) throw new UserExistsError("User doesn't exist");
if (!user) return sendError(reply, "User doesn't exist");
delete user.password;
return reply.send(user);
}
@GET('/stats')
async stats(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const user = await this.users.findOne({
where: {
id: readBaseCookie(req.cookies.zipline)
}
});
const images = await this.images.find({
where: {
user: user.id
}
});
const totalViews = images.map(x => x.views).reduce((a, b) => Number(a) + Number(b), 0);
return reply.send({
totalViews,
images: images.length,
averageViews: totalViews / images.length
});
}
@PATCH('/')
async editUser(
req: FastifyRequest<{
@@ -68,7 +89,7 @@ export class UserController {
}>,
reply: FastifyReply
) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const user = await this.users.findOne({
where: {
@@ -76,7 +97,7 @@ export class UserController {
}
});
// eslint-disable-next-line quotes
if (!user) throw new UserExistsError("User doesn't exist");
if (!user) return sendError(reply, "User doesn't exist");
this.logger.verbose(`attempting to save ${user.username} (${user.id})`);
user.username = req.body.username;
@@ -85,10 +106,9 @@ export class UserController {
await this.users.save(user);
this.logger.info(`saved ${user.username} (${user.id})`);
if (this.webhooks.events.includes(WebhookType.USER_EDIT))
WebhookHelper.sendWebhook(this.webhooks.user_edit.content, {
user
});
if (this.webhooks.events.includes(WebhookType.USER_EDIT)) Webhooks.sendWebhook(this.webhooks.user_edit.content, {
user
});
delete user.password;
return reply.send(user);
@@ -99,9 +119,9 @@ export class UserController {
req: FastifyRequest<{ Body: { username: string; password: string } }>,
reply: FastifyReply
) {
if (req.cookies.zipline) throw new LoginError('Already logged in.');
if (!req.body.username) throw new MissingBodyData('Missing username.');
if (!req.body.password) throw new MissingBodyData('Missing uassword.');
if (req.cookies.zipline) return sendError(reply, 'Already logged in.');
if (!req.body.username) return sendError(reply, 'Missing username.');
if (!req.body.password) return sendError(reply, 'Missing uassword.');
const user = await this.users.findOne({
where: {
@@ -109,13 +129,12 @@ export class UserController {
}
});
if (!user)
throw new UserNotFoundError(`User "${req.body.username}" was not found.`);
if (!user) return sendError(reply, `User "${req.body.username}" was not found.`);
if (!checkPassword(req.body.password, user.password)) {
this.logger.error(
`${user.username} (${user.id}) tried to verify their credentials but failed`
);
throw new LoginError('Wrong credentials!');
return sendError(reply, 'Wrong credentials!');
}
reply.send({
@@ -128,9 +147,9 @@ export class UserController {
req: FastifyRequest<{ Body: { username: string; password: string } }>,
reply: FastifyReply
) {
if (req.cookies.zipline) throw new LoginError('Already logged in.');
if (!req.body.username) throw new MissingBodyData('Missing username.');
if (!req.body.password) throw new MissingBodyData('Missing uassword.');
if (req.cookies.zipline) return sendError(reply, 'Already logged in.');
if (!req.body.username) return sendError(reply, 'Missing username.');
if (!req.body.password) return sendError(reply, 'Missing uassword.');
const user = await this.users.findOne({
where: {
@@ -138,13 +157,12 @@ export class UserController {
}
});
if (!user)
throw new UserNotFoundError(`User "${req.body.username}" was not found.`);
if (!user) return sendError(reply, `User "${req.body.username}" was not found.`);
if (!checkPassword(req.body.password, user.password)) {
this.logger.error(
`${user.username} (${user.id}) tried to login but failed`
);
throw new LoginError('Wrong credentials!');
return sendError(reply, 'Wrong credentials!');
}
delete user.password;
@@ -155,17 +173,16 @@ export class UserController {
});
this.logger.info(`${user.username} (${user.id}) logged in`);
if (this.webhooks.events.includes(WebhookType.LOGIN))
WebhookHelper.sendWebhook(this.webhooks.login.content, {
user
});
if (this.webhooks.events.includes(WebhookType.LOGIN)) Webhooks.sendWebhook(this.webhooks.login.content, {
user
});
return reply.send(user);
}
@POST('/logout')
async logout(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
try {
reply.clearCookie('zipline', { path: '/' });
return reply.send({ clearStore: true });
@@ -176,7 +193,7 @@ export class UserController {
@POST('/reset-token')
async resetToken(req: FastifyRequest, reply: FastifyReply) {
if (!req.cookies.zipline) throw new LoginError('Not logged in.');
if (!req.cookies.zipline) return sendError(reply, 'Not logged in.');
const user = await this.users.findOne({
where: {
@@ -184,7 +201,7 @@ export class UserController {
}
});
if (!user) throw new UserNotFoundError('User was not found.');
if (!user) return sendError(reply, 'User was not found.');
this.logger.verbose(
`attempting to reset token ${user.username} (${user.id})`
@@ -193,10 +210,9 @@ export class UserController {
await this.users.save(user);
this.logger.info(`reset token ${user.username} (${user.id})`);
if (this.webhooks.events.includes(WebhookType.TOKEN_RESET))
WebhookHelper.sendWebhook(this.webhooks.token_reset.content, {
user
});
if (this.webhooks.events.includes(WebhookType.TOKEN_RESET)) Webhooks.sendWebhook(this.webhooks.token_reset.content, {
user
});
return reply.send({ updated: true });
}
@@ -208,13 +224,13 @@ export class UserController {
}>,
reply: FastifyReply
) {
if (!req.body.username) throw new MissingBodyData('Missing username.');
if (!req.body.password) throw new MissingBodyData('Missing uassword.');
if (!req.body.username) return sendError(reply, 'Missing username.');
if (!req.body.password) return sendError(reply, 'Missing uassword.');
const existing = await this.users.findOne({
where: { username: req.body.username }
});
if (existing) throw new UserExistsError('User exists already');
if (existing) return sendError(reply, 'User exists already');
try {
this.logger.verbose(`attempting to create ${req.body.username}`);
@@ -227,26 +243,24 @@ export class UserController {
)
);
this.logger.info(`created user ${user.username} (${user.id})`);
if (this.webhooks.events.includes(WebhookType.CREATE_USER))
WebhookHelper.sendWebhook(this.webhooks.create_user.content, {
user
});
if (this.webhooks.events.includes(WebhookType.CREATE_USER)) Webhooks.sendWebhook(this.webhooks.create_user.content, {
user
});
const firstSetup = await getFirst(this.instance.orm);
if (firstSetup)
await this.instance.orm.getRepository(Zipline).update(
{
id: 'zipline'
},
{
first: false
}
);
if (firstSetup) await this.instance.orm.getRepository(Zipline).update(
{
id: 'zipline'
},
{
first: false
}
);
delete user.password;
return reply.send(user);
} catch (e) {
throw new Error(`Could not create user: ${e.message}`);
return sendError(reply, `Could not create user: ${e.message}`);
}
}
@@ -262,7 +276,7 @@ export class UserController {
const existing = await this.users.findOne({
where: { id: req.params.id }
});
if (!existing) throw new UserExistsError('User doesnt exist');
if (!existing) return sendError(reply, 'User doesnt exist');
try {
this.logger.verbose(
@@ -271,14 +285,13 @@ export class UserController {
await this.users.remove(existing);
this.logger.info(`deleted ${existing.username} (${existing.id})`);
if (this.webhooks.events.includes(WebhookType.USER_DELETE))
WebhookHelper.sendWebhook(this.webhooks.user_delete.content, {
user: existing
});
if (this.webhooks.events.includes(WebhookType.USER_DELETE)) Webhooks.sendWebhook(this.webhooks.user_delete.content, {
user: existing
});
return reply.send({ ok: true });
} catch (e) {
throw new Error(`Could not delete user: ${e.message}`);
return sendError(reply, `Could not delete user: ${e.message}`);
}
}
// @Hook('preValidation')

56
src/pages/404.tsx Normal file
View File

@@ -0,0 +1,56 @@
import React, { useEffect } from 'react';
import Head from 'next/head';
import Typography from '@material-ui/core/Typography';
import CssBaseline from '@material-ui/core/CssBaseline';
import Grid from '@material-ui/core/Grid';
import { ThemeProvider } from '@material-ui/core/styles';
import dark from '../lib/themes/dark';
export default function NotFound() {
useEffect(() => {
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) jssStyles.parentElement.removeChild(jssStyles);
}, []);
const faces = ['◉_◉', 'ರ_ರ'];
return (
<React.Fragment>
<Head>
<title>Not Found</title>
<meta
name='viewport'
content='minimum-scale=1, initial-scale=1, width=device-width'
/>
<link
rel='icon'
type='image/png'
href='https://twemoji.maxcdn.com/v/13.0.1/72x72/1f621.png'
/>
</Head>
<ThemeProvider theme={dark}>
<CssBaseline />
<Grid
container
spacing={0}
direction='column'
alignItems='center'
justify='center'
style={{ minHeight: '100vh' }}
>
<Grid item xs={6}>
<Typography variant='h2'>
<b>{faces[Math.floor(Math.random() * faces.length)]}</b>
</Typography>
</Grid>
<Grid item xs={6}>
<Typography variant='h4'>
<b>Looks like you&apos;ve hit a dead end...</b>
</Typography>
</Grid>
</Grid>
</ThemeProvider>
</React.Fragment>
);
}

View File

@@ -7,7 +7,7 @@ import { store, persistor } from '../store';
import ZiplineTheming from '../components/ZiplineTheming';
import UIPlaceholder from '../components/UIPlaceholder';
function MyApp({ Component, pageProps }) {
function App({ Component, pageProps }) {
const [theme, setTheme] = useState<'dark' | 'light'>('dark');
useEffect(() => {
const jssStyles = document.querySelector('#jss-server-side');
@@ -41,9 +41,9 @@ function MyApp({ Component, pageProps }) {
);
}
MyApp.propTypes = {
App.propTypes = {
Component: PropTypes.elementType.isRequired,
pageProps: PropTypes.object.isRequired
};
export default MyApp;
export default App;

View File

@@ -12,6 +12,7 @@ import UI from '../components/UI';
import UIPlaceholder from '../components/UIPlaceholder';
import { makeStyles } from '@material-ui/core';
import { store } from '../store';
import { createURL } from '../lib/WebUtil';
import { Configuration } from '../lib/Config';
const useStyles = makeStyles(theme => ({
@@ -33,8 +34,8 @@ export default function Dashboard({ config }) {
const router = useRouter();
const state = store.getState();
const [loading, setLoading] = React.useState(true);
const [stats, setStats] = React.useState<{totalViews:number, averageViews:number, images: number}>(null);
const [recentImages, setRecentImages] = React.useState([]);
const [images, setImages] = React.useState([]);
if (typeof window === 'undefined') return <UIPlaceholder />;
if (!state.loggedIn) router.push('/user/login');
@@ -44,9 +45,9 @@ export default function Dashboard({ config }) {
const recentImages = await (await fetch('/api/images/recent')).json();
if (!recentImages.error) setRecentImages(recentImages);
const allImages = await (await fetch('/api/images')).json();
if (!allImages.error) {
setImages(allImages);
const stats = await (await fetch('/api/user/stats')).json();
if (!stats.error) {
setStats(stats);
setLoading(false);
}
})();
@@ -59,17 +60,15 @@ export default function Dashboard({ config }) {
</Backdrop>
{!loading ? (
<Paper elevation={3} className={classes.padding}>
<Typography variant='h5'>
Welcome back, {state.user.username}
<Typography variant='h4'>
Welcome back, {state.user.username}
</Typography>
<Typography color='textSecondary'>
You have <b>{images.length}</b> images
You have <b>{stats.images}</b> images, with <b>{stats.totalViews}</b> ({Math.round(stats.averageViews)}) collectively.
</Typography>
<Typography variant='h5'>Recent Images</Typography>
<Grid container spacing={2}>
{recentImages.map(d => {
const t = new URL(window.location.href);
t.pathname = `${config ? config.uploader.route : '/u'}/${d.file}`;
return (
<Grid item key={d.id} xs={12} sm={4}>
<Card>
@@ -77,7 +76,7 @@ export default function Dashboard({ config }) {
<CardMedia
component='img'
height='140'
image={t.toString()}
image={createURL(window.location.href, config ? config.uploader.route : '/u', d.file)}
/>
</CardActionArea>
</Card>

View File

@@ -18,6 +18,7 @@ import { makeStyles } from '@material-ui/core';
import { store } from '../../store';
import { Image } from '../../lib/entities/Image';
import { Configuration } from '../../lib/Config';
import { createURL } from '../../lib/WebUtil';
const useStyles = makeStyles(theme => ({
margin: {
@@ -109,29 +110,25 @@ export default function Images({ config }) {
{showPagination ? (
<>
<Grid container spacing={2}>
{images.map(d => {
const t = new URL(window.location.href);
t.pathname = `${config ? config.uploader.route : '/u'}/${d.file}`;
return (
<Grid
item
xs={12}
sm={6}
key={d.id}
onClick={e => setImageOpenPopover(e, d)}
>
<Card>
<CardActionArea>
<CardMedia
component='img'
height='140'
image={t.toString()}
/>
</CardActionArea>
</Card>
</Grid>
);
})}
{images.map(d => ((
<Grid
item
xs={12}
sm={4}
key={d.id}
onClick={e => setImageOpenPopover(e, d)}
>
<Card>
<CardActionArea>
<CardMedia
component='img'
height='140'
image={createURL(window.location.href, config ? config.uploader.route : '/u', d.file)}
/>
</CardActionArea>
</Card>
</Grid>
)))}
</Grid>
<Pagination count={chunks.length} onChange={changePage} />
</>

View File

@@ -1,3 +1,6 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
import React from 'react';
import { useRouter } from 'next/router';
import Typography from '@material-ui/core/Typography';
@@ -32,6 +35,8 @@ export default function Upload() {
const state = store.getState();
const [files, setFiles] = React.useState<File[]>([]);
const [alertOpen, setAlertOpen] = React.useState<boolean>(false);
const [alertSev, setAlertSev] = React.useState('success');
const [alertMsg, setAlertMsg] = React.useState('Uploaded Image!');
const handleFileUpload = async () => {
const file = files[0];
@@ -46,41 +51,57 @@ export default function Upload() {
body
});
if (res.ok) setAlertOpen(true);
if (res.ok) {
setAlertOpen(true);
setAlertMsg('Uploaded Image!');
setAlertSev('success');
} else {
const d = await res.json();
setAlertOpen(true);
setAlertMsg(`Couldn't upload: ${d.error}`);
setAlertSev('error');
}
};
const snack = (
<Snackbar
anchorOrigin={{
vertical: 'top',
horizontal: 'center'
}}
open={alertOpen}
autoHideDuration={6000}
onClose={() => setAlertOpen(false)}
>
<Alert severity={alertSev} variant='filled'>
{alertMsg}
</Alert>
</Snackbar>
);
if (typeof window === 'undefined') return <UIPlaceholder />;
if (!state.loggedIn) router.push('/user/login');
else {
return (
<UI>
<Snackbar
anchorOrigin={{
vertical: 'top',
horizontal: 'center'
}}
open={alertOpen}
autoHideDuration={6000}
onClose={() => setAlertOpen(false)}
>
<Alert severity='success' variant='filled'>
Uploaded image!
</Alert>
</Snackbar>
<Paper elevation={3} className={classes.padding}>
<Typography variant='h5'>
Upload
</Typography>
<Box m={1}>
<DropzoneArea
acceptedFiles={['image/*']}
dropzoneText={'Drag an image or click to upload an image.'}
onChange={f => setFiles(f)}
maxFileSize={1073741824} // 1gb in byte
/>
</Box>
<Button onClick={handleFileUpload}>Submit</Button>
</Paper>
<>
{snack}
<Paper elevation={3} className={classes.padding}>
<Typography variant='h5'>
Upload
</Typography>
<Box m={1}>
<DropzoneArea
acceptedFiles={['image/*']}
dropzoneText={'Drag an image or click to upload an image.'}
onChange={f => setFiles(f)}
filesLimit={1}
maxFileSize={1073741824} // 1gb in byte
/>
</Box>
<Button onClick={handleFileUpload}>Upload</Button>
</Paper>
</>
</UI>
);
}

View File

@@ -1,4 +1,5 @@
import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import Typography from '@material-ui/core/Typography';
import Backdrop from '@material-ui/core/Backdrop';
import CircularProgress from '@material-ui/core/CircularProgress';
@@ -23,9 +24,11 @@ import AddIcon from '@material-ui/icons/Add';
import copy from 'copy-to-clipboard';
import UI from '../../components/UI';
import UIPlaceholder from '../../components/UIPlaceholder';
import OpenInNewIcon from '@material-ui/icons/OpenInNew';
import { makeStyles } from '@material-ui/core';
import { URL as URLEntity } from '../../lib/entities/URL';
import { Configuration } from '../../lib/Config';
import { createURL } from '../../lib/WebUtil';
const useStyles = makeStyles(theme => ({
margin: {
@@ -157,41 +160,46 @@ export default function Urls({ config }) {
<Typography variant='h5'>
URLs
<IconButton
aria-label='Create User'
aria-label='Create URL'
onClick={() => setCreateOpen(true)}
>
<AddIcon />
</IconButton>
</Typography>
<Grid container spacing={2}>
{urls.length > 0 ? urls.map(u => {
const url = new URL(window.location.href);
url.pathname = `${config ? config.urls.route : '/go'}/${u.id}`;
return (
<Grid item xs={12} sm={4} key={u.id}>
<Card elevation={3}>
<CardHeader
action={
<div>
<IconButton aria-label='Copy URL'>
<FileCopyIcon
onClick={() => copy(url.toString())}
/>
</IconButton>
<IconButton
aria-label='Delete Forever'
onClick={() => deleteUrl(u)}
>
<DeleteForeverIcon />
</IconButton>
</div>
}
title={u.vanity ? u.vanity : u.id}
/>
</Card>
</Grid>
);
}) : (
{urls.length > 0 ? urls.map(u => ((
<Grid item xs={12} sm={4} key={u.id}>
<Card elevation={3}>
<CardHeader
action={
<div>
<IconButton aria-label='Copy URL'>
<FileCopyIcon
onClick={() => copy(createURL(window.location.href, config ? config.urls.route : '/go', u.vanity || u.id))}
/>
</IconButton>
<Link href={u.url}>
<a target='_blank'>
<IconButton
aria-label='Open URL in new Tab'
>
<OpenInNewIcon />
</IconButton>
</a>
</Link>
<IconButton
aria-label='Delete Forever'
onClick={() => deleteUrl(u)}
>
<DeleteForeverIcon />
</IconButton>
</div>
}
title={u.vanity ? u.vanity : u.id}
/>
</Card>
</Grid>
))) : (
<Grid
container
spacing={0}

View File

@@ -219,7 +219,7 @@ export default function Users() {
}
title={`${u.username} (${u.id})`}
subheader={`${u.administrator ? 'Administrator' : 'User'
}`}
}`}
/>
</Card>
</Grid>

View File

@@ -10,8 +10,7 @@ export default function Manage({ config }) {
const router = useRouter();
const state = store.getState();
if (typeof window !== 'undefined' && !state.loggedIn)
router.push('/user/login');
if (typeof window !== 'undefined' && !state.loggedIn) router.push('/user/login');
else {
return (
<UI>

879
yarn.lock

File diff suppressed because it is too large Load Diff