1
0
mirror of https://github.com/stonith404/pingvin-share.git synced 2024-07-02 07:20:38 +02:00

refactor: convert config variables to upper case

This commit is contained in:
Elias Schneider 2022-12-05 16:53:52 +01:00
parent d4a0f1a4f1
commit 0499548dd3
20 changed files with 54 additions and 51 deletions

View File

@ -3,7 +3,7 @@ import * as crypto from "crypto";
const configVariables = [ const configVariables = [
{ {
key: "setupFinished", key: "SETUP_FINISHED",
description: "Whether the setup has been finished", description: "Whether the setup has been finished",
type: "boolean", type: "boolean",
value: "false", value: "false",
@ -11,49 +11,49 @@ const configVariables = [
locked: true, locked: true,
}, },
{ {
key: "appUrl", key: "APP_URL",
description: "On which URL Pingvin Share is available", description: "On which URL Pingvin Share is available",
type: "string", type: "string",
value: "http://localhost:3000", value: "http://localhost:3000",
secret: false, secret: false,
}, },
{ {
key: "showHomePage", key: "SHOW_HOME_PAGE",
description: "Whether to show the home page", description: "Whether to show the home page",
type: "boolean", type: "boolean",
value: "true", value: "true",
secret: false, secret: false,
}, },
{ {
key: "allowRegistration", key: "ALLOW_REGISTRATION",
description: "Whether registration is allowed", description: "Whether registration is allowed",
type: "boolean", type: "boolean",
value: "true", value: "true",
secret: false, secret: false,
}, },
{ {
key: "allowUnauthenticatedShares", key: "ALLOW_UNAUTHENTICATED_SHARES",
description: "Whether unauthorized users can create shares", description: "Whether unauthorized users can create shares",
type: "boolean", type: "boolean",
value: "false", value: "false",
secret: false, secret: false,
}, },
{ {
key: "maxFileSize", key: "MAX_FILE_SIZE",
description: "Maximum file size in bytes", description: "Maximum file size in bytes",
type: "number", type: "number",
value: "1000000000", value: "1000000000",
secret: false, secret: false,
}, },
{ {
key: "jwtSecret", key: "JWT_SECRET",
description: "Long random string used to sign JWT tokens", description: "Long random string used to sign JWT tokens",
type: "string", type: "string",
value: crypto.randomBytes(256).toString("base64"), value: crypto.randomBytes(256).toString("base64"),
locked: true, locked: true,
}, },
{ {
key: "emailRecipientsEnabled", key: "ENABLE_EMAIL_RECIPIENTS",
description: description:
"Whether to send emails to recipients. Only set this to true if you entered the host, port, email and password of your SMTP server.", "Whether to send emails to recipients. Only set this to true if you entered the host, port, email and password of your SMTP server.",
type: "boolean", type: "boolean",
@ -61,25 +61,25 @@ const configVariables = [
secret: false, secret: false,
}, },
{ {
key: "smtpHost", key: "SMTP_HOST",
description: "Host of the SMTP server", description: "Host of the SMTP server",
type: "string", type: "string",
value: "", value: "",
}, },
{ {
key: "smtpPort", key: "SMTP_PORT",
description: "Port of the SMTP server", description: "Port of the SMTP server",
type: "number", type: "number",
value: "", value: "",
}, },
{ {
key: "smtpEmail", key: "SMTP_EMAIL",
description: "Email address of the SMTP server", description: "Email address of the SMTP server",
type: "string", type: "string",
value: "", value: "",
}, },
{ {
key: "smtpPassword", key: "SMTP_PASSWORD",
description: "Password of the SMTP server", description: "Password of the SMTP server",
type: "string", type: "string",
value: "", value: "",

View File

@ -26,13 +26,13 @@ import { UserModule } from "./user/user.module";
MulterModule.registerAsync({ MulterModule.registerAsync({
useFactory: (config: ConfigService) => ({ useFactory: (config: ConfigService) => ({
fileFilter: (req: Request, file, cb) => { fileFilter: (req: Request, file, cb) => {
const maxFileSize = config.get("maxFileSize"); const MAX_FILE_SIZE = config.get("MAX_FILE_SIZE");
const requestFileSize = parseInt(req.headers["content-length"]); const requestFileSize = parseInt(req.headers["content-length"]);
const isValidFileSize = requestFileSize <= maxFileSize; const isValidFileSize = requestFileSize <= MAX_FILE_SIZE;
cb( cb(
!isValidFileSize && !isValidFileSize &&
new HttpException( new HttpException(
`File must be smaller than ${maxFileSize} bytes`, `File must be smaller than ${MAX_FILE_SIZE} bytes`,
HttpStatus.PAYLOAD_TOO_LARGE HttpStatus.PAYLOAD_TOO_LARGE
), ),
isValidFileSize isValidFileSize

View File

@ -28,7 +28,7 @@ export class AuthController {
@Throttle(10, 5 * 60) @Throttle(10, 5 * 60)
@Post("signUp") @Post("signUp")
async signUp(@Body() dto: AuthRegisterDTO) { async signUp(@Body() dto: AuthRegisterDTO) {
if (!this.config.get("allowRegistration")) if (!this.config.get("ALLOW_REGISTRATION"))
throw new ForbiddenException("Registration is not allowed"); throw new ForbiddenException("Registration is not allowed");
return this.authService.signUp(dto); return this.authService.signUp(dto);
} }

View File

@ -30,7 +30,7 @@ export class AuthService {
email: dto.email, email: dto.email,
username: dto.username, username: dto.username,
password: hash, password: hash,
isAdmin: !this.config.get("setupFinished"), isAdmin: !this.config.get("SETUP_FINISHED"),
}, },
}); });
@ -74,7 +74,7 @@ export class AuthService {
throw new ForbiddenException("Invalid password"); throw new ForbiddenException("Invalid password");
const hash = await argon.hash(newPassword); const hash = await argon.hash(newPassword);
this.prisma.user.update({ this.prisma.user.update({
where: { id: user.id }, where: { id: user.id },
data: { password: hash }, data: { password: hash },
@ -89,7 +89,7 @@ export class AuthService {
}, },
{ {
expiresIn: "15min", expiresIn: "15min",
secret: this.config.get("jwtSecret"), secret: this.config.get("JWT_SECRET"),
} }
); );
} }

View File

@ -11,7 +11,7 @@ export class JwtGuard extends AuthGuard("jwt") {
try { try {
return (await super.canActivate(context)) as boolean; return (await super.canActivate(context)) as boolean;
} catch { } catch {
return this.config.get("allowUnauthenticatedShares"); return this.config.get("ALLOW_UNAUTHENTICATED_SHARES");
} }
} }
} }

View File

@ -8,10 +8,10 @@ import { PrismaService } from "src/prisma/prisma.service";
@Injectable() @Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) { export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(config: ConfigService, private prisma: PrismaService) { constructor(config: ConfigService, private prisma: PrismaService) {
config.get("jwtSecret"); config.get("JWT_SECRET");
super({ super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.get("jwtSecret"), secretOrKey: config.get("JWT_SECRET"),
}); });
} }

View File

@ -63,7 +63,7 @@ export class ConfigService {
async finishSetup() { async finishSetup() {
return await this.prisma.config.update({ return await this.prisma.config.update({
where: { key: "setupFinished" }, where: { key: "SETUP_FINISHED" },
data: { value: "true" }, data: { value: "true" },
}); });
} }

View File

@ -22,8 +22,7 @@ export class EmailService {
if (!this.config.get("emailRecepientsEnabled")) if (!this.config.get("emailRecepientsEnabled"))
throw new InternalServerErrorException("Email service disabled"); throw new InternalServerErrorException("Email service disabled");
const shareUrl = `${this.config.get("appUrl")}/share/${shareId}`; const shareUrl = `${this.config.get("APP_URL")}/share/${shareId}`;
await transporter.sendMail({ await transporter.sendMail({
from: `"Pingvin Share" <${this.config.get("SMTP_EMAIL")}>`, from: `"Pingvin Share" <${this.config.get("SMTP_EMAIL")}>`,

View File

@ -82,7 +82,7 @@ export class FileService {
const downloadToken = this.generateFileDownloadToken(shareId, fileId); const downloadToken = this.generateFileDownloadToken(shareId, fileId);
return `${this.config.get( return `${this.config.get(
"appUrl" "APP_URL"
)}/api/shares/${shareId}/files/${fileId}?token=${downloadToken}`; )}/api/shares/${shareId}/files/${fileId}?token=${downloadToken}`;
} }
@ -96,7 +96,7 @@ export class FileService {
}, },
{ {
expiresIn: "10min", expiresIn: "10min",
secret: this.config.get("jwtSecret"), secret: this.config.get("JWT_SECRET"),
} }
); );
} }
@ -104,7 +104,7 @@ export class FileService {
verifyFileDownloadToken(shareId: string, token: string) { verifyFileDownloadToken(shareId: string, token: string) {
try { try {
const claims = this.jwtService.verify(token, { const claims = this.jwtService.verify(token, {
secret: this.config.get("jwtSecret"), secret: this.config.get("JWT_SECRET"),
}); });
return claims.shareId == shareId; return claims.shareId == shareId;
} catch { } catch {

View File

@ -10,7 +10,7 @@ import { ConfigService } from "src/config/config.service";
export class FileValidationPipe implements PipeTransform { export class FileValidationPipe implements PipeTransform {
constructor(private config: ConfigService) {} constructor(private config: ConfigService) {}
async transform(value: any, metadata: ArgumentMetadata) { async transform(value: any, metadata: ArgumentMetadata) {
if (value.size > this.config.get("maxFileSize")) if (value.size > this.config.get("MAX_FILE_SIZE"))
throw new BadRequestException("File is "); throw new BadRequestException("File is ");
return value; return value;
} }

View File

@ -235,7 +235,7 @@ export class ShareService {
}, },
{ {
expiresIn: moment(expiration).diff(new Date(), "seconds") + "s", expiresIn: moment(expiration).diff(new Date(), "seconds") + "s",
secret: this.config.get("jwtSecret"), secret: this.config.get("JWT_SECRET"),
} }
); );
} }
@ -247,7 +247,7 @@ export class ShareService {
try { try {
const claims = this.jwtService.verify(token, { const claims = this.jwtService.verify(token, {
secret: this.config.get("jwtSecret"), secret: this.config.get("JWT_SECRET"),
// Ignore expiration if expiration is 0 // Ignore expiration if expiration is 0
ignoreExpiration: moment(expiration).isSame(0), ignoreExpiration: moment(expiration).isSame(0),
}); });

View File

@ -49,7 +49,7 @@ const SignInForm = () => {
> >
Welcome back Welcome back
</Title> </Title>
{config.get("allowRegistration") && ( {config.get("ALLOW_REGISTRATION") && (
<Text color="dimmed" size="sm" align="center" mt={5}> <Text color="dimmed" size="sm" align="center" mt={5}>
You don't have an account yet?{" "} You don't have an account yet?{" "}
<Anchor component={Link} href={"signUp"} size="sm"> <Anchor component={Link} href={"signUp"} size="sm">
@ -65,6 +65,7 @@ const SignInForm = () => {
> >
<TextInput <TextInput
label="Email or username" label="Email or username"
type="email"
placeholder="you@email.com" placeholder="you@email.com"
{...form.getInputProps("emailOrUsername")} {...form.getInputProps("emailOrUsername")}
/> />

View File

@ -57,7 +57,7 @@ const SignUpForm = () => {
> >
Sign up Sign up
</Title> </Title>
{config.get("allowRegistration") && ( {config.get("ALLOW_REGISTRATION") && (
<Text color="dimmed" size="sm" align="center" mt={5}> <Text color="dimmed" size="sm" align="center" mt={5}>
You have an account already?{" "} You have an account already?{" "}
<Anchor component={Link} href={"signIn"} size="sm"> <Anchor component={Link} href={"signIn"} size="sm">
@ -78,6 +78,7 @@ const SignUpForm = () => {
/> />
<TextInput <TextInput
label="Email" label="Email"
type="email"
placeholder="you@email.com" placeholder="you@email.com"
mt="md" mt="md"
{...form.getInputProps("email")} {...form.getInputProps("email")}

View File

@ -130,7 +130,7 @@ const NavBar = () => {
]); ]);
useEffect(() => { useEffect(() => {
if (config.get("showHomePage")) if (config.get("SHOW_HOME_PAGE"))
setUnauthenticatedLinks((array) => [ setUnauthenticatedLinks((array) => [
{ {
link: "/", link: "/",
@ -139,7 +139,7 @@ const NavBar = () => {
...array, ...array,
]); ]);
if (config.get("allowRegistration")) if (config.get("ALLOW_REGISTRATION"))
setUnauthenticatedLinks((array) => [ setUnauthenticatedLinks((array) => [
...array, ...array,
{ {

View File

@ -45,7 +45,7 @@ const Dropzone = ({
return ( return (
<div className={classes.wrapper}> <div className={classes.wrapper}>
<MantineDropzone <MantineDropzone
maxSize={parseInt(config.get("maxFileSize"))} maxSize={parseInt(config.get("MAX_FILE_SIZE"))}
onReject={(e) => { onReject={(e) => {
toast.error(e[0].errors[0].message); toast.error(e[0].errors[0].message);
}} }}
@ -75,7 +75,7 @@ const Dropzone = ({
<Text align="center" size="sm" mt="xs" color="dimmed"> <Text align="center" size="sm" mt="xs" color="dimmed">
Drag&apos;n&apos;drop files here to start your share. We can accept Drag&apos;n&apos;drop files here to start your share. We can accept
only files that are less than{" "} only files that are less than{" "}
{byteStringToHumanSizeString(config.get("maxFileSize"))} in size. {byteStringToHumanSizeString(config.get("MAX_FILE_SIZE"))} in size.
</Text> </Text>
</div> </div>
</MantineDropzone> </MantineDropzone>

View File

@ -29,8 +29,8 @@ const showCreateUploadModal = (
modals: ModalsContextProps, modals: ModalsContextProps,
options: { options: {
isUserSignedIn: boolean; isUserSignedIn: boolean;
allowUnauthenticatedShares: boolean; ALLOW_UNAUTHENTICATED_SHARES: boolean;
emailRecipientsEnabled: boolean; ENABLE_EMAIL_RECIPIENTS: boolean;
}, },
uploadCallback: ( uploadCallback: (
id: string, id: string,
@ -62,14 +62,14 @@ const CreateUploadModalBody = ({
) => void; ) => void;
options: { options: {
isUserSignedIn: boolean; isUserSignedIn: boolean;
allowUnauthenticatedShares: boolean; ALLOW_UNAUTHENTICATED_SHARES: boolean;
emailRecipientsEnabled: boolean; ENABLE_EMAIL_RECIPIENTS: boolean;
}; };
}) => { }) => {
const modals = useModals(); const modals = useModals();
const [showNotSignedInAlert, setShowNotSignedInAlert] = useState( const [showNotSignedInAlert, setShowNotSignedInAlert] = useState(
options.emailRecipientsEnabled options.ENABLE_EMAIL_RECIPIENTS
); );
const validationSchema = yup.object().shape({ const validationSchema = yup.object().shape({
@ -230,7 +230,7 @@ const CreateUploadModalBody = ({
{ExpirationPreview({ form })} {ExpirationPreview({ form })}
</Text> </Text>
<Accordion> <Accordion>
{options.emailRecipientsEnabled && ( {options.ENABLE_EMAIL_RECIPIENTS && (
<Accordion.Item value="recipients" sx={{ borderBottom: "none" }}> <Accordion.Item value="recipients" sx={{ borderBottom: "none" }}>
<Accordion.Control>Email recipients</Accordion.Control> <Accordion.Control>Email recipients</Accordion.Control>
<Accordion.Panel> <Accordion.Panel>

View File

@ -17,7 +17,7 @@ const Setup = () => {
if (!user) { if (!user) {
router.push("/auth/signUp"); router.push("/auth/signUp");
return; return;
} else if (config.get("setupFinished")) { } else if (config.get("SETUP_FINISHED")) {
router.push("/"); router.push("/");
return; return;
} }

View File

@ -10,7 +10,7 @@ const SignUp = () => {
const router = useRouter(); const router = useRouter();
if (user) { if (user) {
router.replace("/"); router.replace("/");
} else if (config.get("allowRegistration") == "false") { } else if (config.get("ALLOW_REGISTRATION") == "false") {
router.replace("/auth/signIn"); router.replace("/auth/signIn");
} else { } else {
return ( return (

View File

@ -74,9 +74,9 @@ export default function Home() {
const { classes } = useStyles(); const { classes } = useStyles();
const router = useRouter(); const router = useRouter();
if (user || config.get("allowUnauthenticatedShares")) { if (user || config.get("ALLOW_UNAUTHENTICATED_SHARES")) {
router.replace("/upload"); router.replace("/upload");
} else if (!config.get("showHomePage")) { } else if (!config.get("SHOW_HOME_PAGE")) {
router.replace("/auth/signIn"); router.replace("/auth/signIn");
} else { } else {
return ( return (

View File

@ -95,7 +95,7 @@ const Upload = () => {
} }
} }
}, [files]); }, [files]);
if (!user && !config.get("allowUnauthenticatedShares")) { if (!user && !config.get("ALLOW_UNAUTHENTICATED_SHARES")) {
router.replace("/"); router.replace("/");
} else { } else {
return ( return (
@ -110,10 +110,12 @@ const Upload = () => {
modals, modals,
{ {
isUserSignedIn: user ? true : false, isUserSignedIn: user ? true : false,
allowUnauthenticatedShares: config.get( ALLOW_UNAUTHENTICATED_SHARES: config.get(
"allowUnauthenticatedShares" "ALLOW_UNAUTHENTICATED_SHARES"
),
ENABLE_EMAIL_RECIPIENTS: config.get(
"ENABLE_EMAIL_RECIPIENTS"
), ),
emailRecipientsEnabled: config.get("emailRecipientsEnabled"),
}, },
uploadFiles uploadFiles
) )