feat(auth): add OAuth2 login (#276)

* feat(auth): add OAuth2 login with GitHub and Google

* chore(translations): add files for Japanese

* fix(auth): fix link function for GitHub

* feat(oauth): basic oidc implementation

* feat(oauth): oauth guard

* fix: disable image optimizations for logo to prevent caching issues with custom logos

* fix: memory leak while downloading large files

* chore(translations): update translations via Crowdin (#278)

* New translations en-us.ts (Japanese)

* New translations en-us.ts (Japanese)

* New translations en-us.ts (Japanese)

* release: 0.18.2

* doc(translations): Add Japanese README (#279)

* Added Japanese README.

* Added JAPANESE README link to README.md.

* Updated Japanese README.

* Updated Environment Variable Table.

* updated zh-cn README.

* feat(oauth): unlink account

* refactor(oauth): make providers extensible

* fix(oauth): fix discoveryUri error when toggle google-enabled

* feat(oauth): add microsoft and discord as oauth provider

* docs(oauth): update README.md

* docs(oauth): update oauth2-guide.md

* set password to null for new oauth users

* New translations en-us.ts (Japanese) (#281)

* chore(translations): add Polish files

* fix(oauth): fix random username and password

* feat(oauth): add totp

* fix(oauth): fix totp throttle

* fix(oauth): fix qrcode and remove comment

* feat(oauth): add error page

* fix(oauth): i18n of error page

* feat(auth): add OAuth2 login

* fix(auth): fix link function for GitHub

* feat(oauth): basic oidc implementation

* feat(oauth): oauth guard

* feat(oauth): unlink account

* refactor(oauth): make providers extensible

* fix(oauth): fix discoveryUri error when toggle google-enabled

* feat(oauth): add microsoft and discord as oauth provider

* docs(oauth): update README.md

* docs(oauth): update oauth2-guide.md

* set password to null for new oauth users

* fix(oauth): fix random username and password

* feat(oauth): add totp

* fix(oauth): fix totp throttle

* fix(oauth): fix qrcode and remove comment

* feat(oauth): add error page

* fix(oauth): i18n of error page

* refactor: return null instead of `false` in `getIdOfCurrentUser` functiom

* feat: show original oauth error if available

* refactor: run formatter

* refactor(oauth): error message i18n

* refactor(oauth): make OAuth token available
someone may use it (to revoke token or get other info etc.)
also improved the i18n message

* chore(oauth): remove unused import

* chore: add database migration

* fix: missing python installation for nanoid

---------

Co-authored-by: Elias Schneider <login@eliasschneider.com>
Co-authored-by: ふうせん <10260662+fusengum@users.noreply.github.com>
This commit is contained in:
Qing Fu
2023-10-22 22:09:53 +08:00
committed by GitHub
parent d327bc355c
commit 02cd98fa9c
52 changed files with 1983 additions and 161 deletions

View File

@@ -13,6 +13,7 @@ import {
} from "@mantine/core";
import { useForm, yupResolver } from "@mantine/form";
import { useModals } from "@mantine/modals";
import { useEffect, useState } from "react";
import { Tb2Fa } from "react-icons/tb";
import { FormattedMessage } from "react-intl";
import * as yup from "yup";
@@ -20,16 +21,28 @@ import Meta from "../../components/Meta";
import LanguagePicker from "../../components/account/LanguagePicker";
import ThemeSwitcher from "../../components/account/ThemeSwitcher";
import showEnableTotpModal from "../../components/account/showEnableTotpModal";
import useConfig from "../../hooks/config.hook";
import useTranslate from "../../hooks/useTranslate.hook";
import useUser from "../../hooks/user.hook";
import authService from "../../services/auth.service";
import userService from "../../services/user.service";
import { getOAuthIcon, getOAuthUrl, unlinkOAuth } from "../../utils/oauth.util";
import toast from "../../utils/toast.util";
const Account = () => {
const [oauth, setOAuth] = useState<string[]>([]);
const [oauthStatus, setOAuthStatus] = useState<Record<
string,
{
provider: string;
providerUsername: string;
}
> | null>(null);
const { user, refreshUser } = useUser();
const modals = useModals();
const t = useTranslate();
const config = useConfig();
const accountForm = useForm({
initialValues: {
@@ -53,10 +66,14 @@ const Account = () => {
},
validate: yupResolver(
yup.object().shape({
oldPassword: yup
.string()
.min(8, t("common.error.too-short", { length: 8 }))
.required(t("common.error.field-required")),
oldPassword: yup.string().when([], {
is: () => !!user?.hasPassword,
then: (schema) =>
schema
.min(8, t("common.error.too-short", { length: 8 }))
.required(t("common.error.field-required")),
otherwise: (schema) => schema.notRequired(),
}),
password: yup
.string()
.min(8, t("common.error.too-short", { length: 8 }))
@@ -96,6 +113,25 @@ const Account = () => {
),
});
const refreshOAuthStatus = () => {
authService
.getOAuthStatus()
.then((data) => {
setOAuthStatus(data.data);
})
.catch(toast.axiosError);
};
useEffect(() => {
authService
.getAvailableOAuth()
.then((data) => {
setOAuth(data.data);
})
.catch(toast.axiosError);
refreshOAuthStatus();
}, []);
return (
<>
<Meta title={t("account.title")} />
@@ -143,7 +179,8 @@ const Account = () => {
onSubmit={passwordForm.onSubmit((values) =>
authService
.updatePassword(values.oldPassword, values.password)
.then(() => {
.then(async () => {
refreshUser();
toast.success(t("account.notify.password.success"));
passwordForm.reset();
})
@@ -151,10 +188,16 @@ const Account = () => {
)}
>
<Stack>
<PasswordInput
label={t("account.card.password.old")}
{...passwordForm.getInputProps("oldPassword")}
/>
{user?.hasPassword ? (
<PasswordInput
label={t("account.card.password.old")}
{...passwordForm.getInputProps("oldPassword")}
/>
) : (
<Text size="sm" color="dimmed">
<FormattedMessage id="account.card.password.noPasswordSet" />
</Text>
)}
<PasswordInput
label={t("account.card.password.new")}
{...passwordForm.getInputProps("password")}
@@ -167,7 +210,79 @@ const Account = () => {
</Stack>
</form>
</Paper>
{oauth.length > 0 && (
<Paper withBorder p="xl" mt="lg">
<Title order={5} mb="xs">
<FormattedMessage id="account.card.oauth.title" />
</Title>
<Tabs defaultValue={oauth[0] || ""}>
<Tabs.List>
{oauth.map((provider) => (
<Tabs.Tab
value={provider}
icon={getOAuthIcon(provider)}
key={provider}
>
{t(`account.card.oauth.${provider}`)}
</Tabs.Tab>
))}
</Tabs.List>
{oauth.map((provider) => (
<Tabs.Panel value={provider} pt="xs" key={provider}>
<Group position="apart">
<Text>
{oauthStatus?.[provider]
? oauthStatus[provider].providerUsername
: t("account.card.oauth.unlinked")}
</Text>
{oauthStatus?.[provider] ? (
<Button
onClick={() => {
modals.openConfirmModal({
title: t("account.modal.unlink.title"),
children: (
<Text>
{t("account.modal.unlink.description")}
</Text>
),
labels: {
confirm: t("account.card.oauth.unlink"),
cancel: t("common.button.cancel"),
},
confirmProps: { color: "red" },
onConfirm: () => {
unlinkOAuth(provider)
.then(() => {
toast.success(
t("account.notify.oauth.unlinked.success"),
);
refreshOAuthStatus();
})
.catch(toast.axiosError);
},
});
}}
>
{t("account.card.oauth.unlink")}
</Button>
) : (
<Button
component="a"
href={getOAuthUrl(
config.get("general.appUrl"),
provider,
)}
>
{t("account.card.oauth.link")}
</Button>
)}
</Group>
</Tabs.Panel>
))}
</Tabs>
</Paper>
)}
<Paper withBorder p="xl" mt="lg">
<Title order={5} mb="xs">
<FormattedMessage id="account.card.security.title" />

View File

@@ -24,10 +24,7 @@ import CenterLoader from "../../../components/core/CenterLoader";
import useConfig from "../../../hooks/config.hook";
import configService from "../../../services/config.service";
import { AdminConfig, UpdateConfig } from "../../../types/config.type";
import {
camelToKebab,
capitalizeFirstLetter,
} from "../../../utils/string.util";
import { camelToKebab } from "../../../utils/string.util";
import toast from "../../../utils/toast.util";
import useTranslate from "../../../hooks/useTranslate.hook";
@@ -128,7 +125,7 @@ export default function AppShellDemo() {
<>
<Stack>
<Title mb="md" order={3}>
{capitalizeFirstLetter(categoryId)}
{t("admin.config.category." + categoryId)}
</Title>
{configVariables.map((configVariable) => (
<Group key={configVariable.key} position="apart">

View File

@@ -0,0 +1,18 @@
import useTranslate from "../../../hooks/useTranslate.hook";
import Meta from "../../../components/Meta";
import TotpForm from "../../../components/auth/TotpForm";
import { useRouter } from "next/router";
const Totp = () => {
const t = useTranslate();
const router = useRouter();
return (
<>
<Meta title={t("totp.title")} />
<TotpForm redirectPath={(router.query.redirect as string) || "/upload"} />
</>
);
};
export default Totp;

View File

@@ -0,0 +1,49 @@
import React from "react";
import { Button, createStyles, Stack, Text, Title } from "@mantine/core";
import Meta from "../components/Meta";
import useTranslate from "../hooks/useTranslate.hook";
import { useRouter } from "next/router";
import { FormattedMessage } from "react-intl";
const useStyle = createStyles({
title: {
fontSize: 100,
},
});
export default function Error() {
const { classes } = useStyle();
const t = useTranslate();
const router = useRouter();
const params = router.query.params
? (router.query.params as string).split(",").map((param) => {
return t(`error.param.${param}`);
})
: [];
return (
<>
<Meta title={t("error.title")} />
<Stack align="center">
<Title order={3} className={classes.title}>
{t("error.description")}
</Title>
<Text mt="xl" size="lg">
<FormattedMessage
id={`error.msg.${router.query.error || "default"}`}
values={Object.fromEntries(
[params].map((value, key) => [key.toString(), value]),
)}
/>
</Text>
<Button
mt="xl"
onClick={() => router.push((router.query.redirect as string) || "/")}
>
{t("error.button.back")}
</Button>
</Stack>
</>
);
}

View File

@@ -56,7 +56,7 @@ const Upload = ({
file.uploadingProgress = progress;
}
return file;
})
}),
);
};
@@ -84,7 +84,7 @@ const Upload = ({
name: file.name,
},
chunkIndex,
chunks
chunks,
)
.then((response) => {
fileId = response.id;
@@ -114,7 +114,7 @@ const Upload = ({
}
}
}
})
}),
);
Promise.all(fileUploadPromises);
@@ -129,19 +129,19 @@ const Upload = ({
isReverseShare,
appUrl: config.get("general.appUrl"),
allowUnauthenticatedShares: config.get(
"share.allowUnauthenticatedShares"
"share.allowUnauthenticatedShares",
),
enableEmailRecepients: config.get("email.enableShareEmailRecipients"),
},
files,
uploadFiles
uploadFiles,
);
};
useEffect(() => {
// Check if there are any files that failed to upload
const fileErrorCount = files.filter(
(file) => file.uploadingProgress == -1
(file) => file.uploadingProgress == -1,
).length;
if (fileErrorCount > 0) {
@@ -151,7 +151,7 @@ const Upload = ({
{
withCloseButton: false,
autoClose: false,
}
},
);
}
errorToastShown = true;