// Copyright 2021 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import React, {Suspense, lazy} from "react";
import {Button, Checkbox, Col, Form, Input, Result, Spin, Tabs, message} from "antd";
import {ArrowLeftOutlined, LockOutlined, UserOutlined} from "@ant-design/icons";
import {withRouter} from "react-router-dom";
import * as UserWebauthnBackend from "../backend/UserWebauthnBackend";
import OrganizationSelect from "../common/select/OrganizationSelect";
import * as Conf from "../Conf";
import * as Obfuscator from "./Obfuscator";
import * as AuthBackend from "./AuthBackend";
import * as OrganizationBackend from "../backend/OrganizationBackend";
import * as ApplicationBackend from "../backend/ApplicationBackend";
import * as Provider from "./Provider";
import * as Util from "./Util";
import * as Setting from "../Setting";
import * as AgreementModal from "../common/modal/AgreementModal";
import SelfLoginButton from "./SelfLoginButton";
import i18next from "i18next";
import CustomGithubCorner from "../common/CustomGithubCorner";
import {SendCodeInput} from "../common/SendCodeInput";
import LanguageSelect from "../common/select/LanguageSelect";
import {CaptchaModal, CaptchaRule} from "../common/modal/CaptchaModal";
import RedirectForm from "../common/RedirectForm";
import {RequiredMfa} from "./mfa/MfaAuthVerifyForm";
import {GoogleOneTapLoginVirtualButton} from "./GoogleLoginButton";
import * as ProviderButton from "./ProviderButton";
import {goToLink} from "../Setting";
const FaceRecognitionCommonModal = lazy(() => import("../common/modal/FaceRecognitionCommonModal"));
const FaceRecognitionModal = lazy(() => import("../common/modal/FaceRecognitionModal"));
class LoginPage extends React.Component {
constructor(props) {
super(props);
this.state = {
classes: props,
type: props.type,
applicationName: props.applicationName ?? (props.match?.params?.applicationName ?? null),
owner: props.owner ?? (props.match?.params?.owner ?? null),
mode: props.mode ?? (props.match?.params?.mode ?? null), // "signup" or "signin"
msg: null,
username: null,
validEmailOrPhone: false,
validEmail: false,
openCaptchaModal: false,
openFaceRecognitionModal: false,
verifyCaptcha: undefined,
samlResponse: "",
relayState: "",
redirectUrl: "",
isTermsOfUseVisible: false,
termsOfUseContent: "",
orgChoiceMode: new URLSearchParams(props.location?.search).get("orgChoiceMode") ?? null,
userLang: null,
loginLoading: false,
userCode: props.userCode ?? (props.match?.params?.userCode ?? null),
userCodeStatus: "",
};
if (this.state.type === "cas" && props.match?.params.casApplicationName !== undefined) {
this.state.owner = props.match?.params?.owner;
this.state.applicationName = props.match?.params?.casApplicationName;
}
localStorage.setItem("signinUrl", window.location.pathname + window.location.search);
this.form = React.createRef();
}
componentDidMount() {
if (this.getApplicationObj() === undefined) {
if (this.state.type === "login" || this.state.type === "saml") {
this.getApplication();
} else if (this.state.type === "code" || this.state.type === "cas" || this.state.type === "device") {
this.getApplicationLogin();
} else {
Setting.showMessage("error", `Unknown authentication type: ${this.state.type}`);
}
}
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (prevState.loginMethod === undefined && this.state.loginMethod === undefined) {
const application = this.getApplicationObj();
this.setState({loginMethod: this.getDefaultLoginMethod(application)});
}
if (prevProps.application !== this.props.application) {
this.setState({loginMethod: this.getDefaultLoginMethod(this.props.application)});
}
if (prevProps.account !== this.props.account && this.props.account !== undefined) {
if (this.props.account && this.props.account.owner === this.props.application?.organization) {
const params = new URLSearchParams(this.props.location.search);
const silentSignin = params.get("silentSignin");
if (silentSignin !== null) {
this.sendSilentSigninData("signing-in");
const values = {};
values["application"] = this.props.application.name;
this.login(values);
}
if (params.get("popup") === "1") {
window.addEventListener("beforeunload", () => {
this.sendPopupData({type: "windowClosed"}, params.get("redirect_uri"));
});
}
if (this.props.application.enableAutoSignin) {
const values = {};
values["application"] = this.props.application.name;
this.login(values);
}
}
}
}
getCaptchaRule(application) {
const captchaProviderItems = this.getCaptchaProviderItems(application);
if (captchaProviderItems) {
if (captchaProviderItems.some(providerItem => providerItem.rule === "Always")) {
return CaptchaRule.Always;
} else if (captchaProviderItems.some(providerItem => providerItem.rule === "Dynamic")) {
return CaptchaRule.Dynamic;
} else if (captchaProviderItems.some(providerItem => providerItem.rule === "Internet-Only")) {
return CaptchaRule.InternetOnly;
} else {
return CaptchaRule.Never;
}
}
}
checkCaptchaStatus(values) {
AuthBackend.getCaptchaStatus(values)
.then((res) => {
if (res.status === "ok") {
if (res.data) {
this.setState({
openCaptchaModal: true,
values: values,
});
return null;
}
}
this.login(values);
});
}
getApplicationLogin() {
let loginParams;
if (this.state.type === "cas") {
loginParams = Util.getCasLoginParameters("admin", this.state.applicationName);
} else if (this.state.type === "device") {
loginParams = {userCode: this.state.userCode, type: this.state.type};
} else {
loginParams = Util.getOAuthGetParameters();
}
AuthBackend.getApplicationLogin(loginParams)
.then((res) => {
if (res.status === "ok") {
const application = res.data;
this.onUpdateApplication(application);
} else {
if (this.state.type === "device") {
this.setState({
userCodeStatus: "expired",
});
}
this.onUpdateApplication(null);
this.setState({
msg: res.msg,
});
}
});
}
getApplication() {
if (this.state.applicationName === null) {
return null;
}
if (this.state.owner === null || this.state.type === "saml") {
ApplicationBackend.getApplication("admin", this.state.applicationName)
.then((res) => {
if (res.status === "error") {
this.onUpdateApplication(null);
this.setState({
msg: res.msg,
});
return ;
}
this.onUpdateApplication(res.data);
});
} else {
OrganizationBackend.getDefaultApplication("admin", this.state.owner)
.then((res) => {
if (res.status === "ok") {
const application = res.data;
this.onUpdateApplication(application);
this.setState({
applicationName: res.data.name,
});
} else {
this.onUpdateApplication(null);
Setting.showMessage("error", res.msg);
this.props.history.push("/404");
}
});
}
}
getApplicationObj() {
return this.props.application;
}
getDefaultLoginMethod(application) {
if (application?.signinMethods?.length > 0) {
switch (application?.signinMethods[0].name) {
case "Password": return "password";
case "Verification code": {
switch (application?.signinMethods[0].rule) {
case "All": return "verificationCode"; // All
case "Email only": return "verificationCodeEmail";
case "Phone only": return "verificationCodePhone";
}
break;
}
case "WebAuthn": return "webAuthn";
case "LDAP": return "ldap";
case "Face ID": return "faceId";
}
}
return "password";
}
getCurrentLoginMethod() {
if (this.state.loginMethod === "password") {
return "Password";
} else if (this.state.loginMethod?.includes("verificationCode")) {
return "Verification code";
} else if (this.state.loginMethod === "webAuthn") {
return "WebAuthn";
} else if (this.state.loginMethod === "ldap") {
return "LDAP";
} else if (this.state.loginMethod === "faceId") {
return "Face ID";
} else {
return "Password";
}
}
getPlaceholder(defaultPlaceholder = null) {
if (defaultPlaceholder) {
return defaultPlaceholder;
}
switch (this.state.loginMethod) {
case "verificationCode": return i18next.t("login:Email or phone");
case "verificationCodeEmail": return i18next.t("login:Email");
case "verificationCodePhone": return i18next.t("login:Phone");
case "ldap": return i18next.t("login:LDAP username, Email or phone");
default: return i18next.t("login:username, Email or phone");
}
}
onUpdateAccount(account) {
this.props.onUpdateAccount(account);
}
onUpdateApplication(application) {
this.props.onUpdateApplication(application);
if (application === null) {
return;
}
for (const idx in application.providers) {
const provider = application.providers[idx];
if (provider.provider?.category === "Face ID") {
this.setState({haveFaceIdProvider: true});
break;
}
}
}
parseOffset(offset) {
if (offset === 2 || offset === 4 || Setting.inIframe() || Setting.isMobile()) {
return "0 auto";
}
if (offset === 1) {
return "0 10%";
}
if (offset === 3) {
return "0 60%";
}
}
populateOauthValues(values) {
if (this.getApplicationObj()?.organization) {
values["organization"] = this.getApplicationObj().organization;
}
values["signinMethod"] = this.getCurrentLoginMethod();
const oAuthParams = Util.getOAuthGetParameters();
values["type"] = oAuthParams?.responseType ?? this.state.type;
if (this.state.userCode) {
values["userCode"] = this.state.userCode;
}
if (oAuthParams?.samlRequest) {
values["samlRequest"] = oAuthParams.samlRequest;
values["type"] = "saml";
values["relayState"] = oAuthParams.relayState;
}
}
sendPopupData(message, redirectUri) {
const params = new URLSearchParams(this.props.location.search);
if (params.get("popup") === "1") {
window.opener.postMessage(message, redirectUri);
}
}
postCodeLoginAction(resp) {
const application = this.getApplicationObj();
const ths = this;
const oAuthParams = Util.getOAuthGetParameters();
const code = resp.data;
const concatChar = oAuthParams?.redirectUri?.includes("?") ? "&" : "?";
const noRedirect = oAuthParams.noRedirect;
const redirectUrl = `${oAuthParams.redirectUri}${concatChar}code=${code}&state=${oAuthParams.state}`;
if (resp.data === RequiredMfa) {
this.props.onLoginSuccess(window.location.href);
return;
}
if (resp.data2) {
sessionStorage.setItem("signinUrl", window.location.pathname + window.location.search);
Setting.goToLinkSoft(ths, `/forget/${application.name}`);
return;
}
if (Setting.hasPromptPage(application)) {
AuthBackend.getAccount()
.then((res) => {
if (res.status === "ok") {
const account = res.data;
account.organization = res.data2;
this.onUpdateAccount(account);
if (Setting.isPromptAnswered(account, application)) {
Setting.goToLink(redirectUrl);
} else {
Setting.goToLinkSoft(ths, `/prompt/${application.name}?redirectUri=${oAuthParams.redirectUri}&code=${code}&state=${oAuthParams.state}`);
}
} else {
Setting.showMessage("error", `${i18next.t("application:Failed to sign in")}: ${res.msg}`);
}
});
} else {
if (noRedirect === "true") {
window.close();
const newWindow = window.open(redirectUrl);
if (newWindow) {
setInterval(() => {
if (!newWindow.closed) {
newWindow.close();
}
}, 1000);
}
} else {
Setting.goToLink(redirectUrl);
this.sendPopupData({type: "loginSuccess", data: {code: code, state: oAuthParams.state}}, oAuthParams.redirectUri);
}
}
}
onFinish(values) {
this.setState({loginLoading: true});
if (this.state.loginMethod === "webAuthn") {
let username = this.state.username;
if (username === null || username === "") {
username = values["username"];
}
this.signInWithWebAuthn(username, values);
return;
}
if (this.state.loginMethod === "faceId") {
let username = this.state.username;
if (username === null || username === "") {
username = values["username"];
}
const application = this.getApplicationObj();
fetch(`${Setting.ServerUrl}/api/faceid-signin-begin?owner=${application.organization}&name=${username}`, {
method: "GET",
credentials: "include",
headers: {
"Accept-Language": Setting.getAcceptLanguage(),
},
}).then(res => res.json())
.then((res) => {
if (res.status === "error") {
this.setState({
loginLoading: false,
});
Setting.showMessage("error", res.msg);
return;
}
this.setState({
openFaceRecognitionModal: true,
values: values,
});
});
return;
}
if (this.state.loginMethod === "password" || this.state.loginMethod === "ldap") {
const organization = this.getApplicationObj()?.organizationObj;
const [passwordCipher, errorMessage] = Obfuscator.encryptByPasswordObfuscator(organization?.passwordObfuscatorType, organization?.passwordObfuscatorKey, values["password"]);
if (errorMessage.length > 0) {
Setting.showMessage("error", errorMessage);
return;
} else {
values["password"] = passwordCipher;
}
const captchaRule = this.getCaptchaRule(this.getApplicationObj());
if (captchaRule === CaptchaRule.Always) {
this.setState({
openCaptchaModal: true,
values: values,
});
return;
} else if (captchaRule === CaptchaRule.Dynamic) {
this.checkCaptchaStatus(values);
return;
} else if (captchaRule === CaptchaRule.InternetOnly) {
this.checkCaptchaStatus(values);
return;
}
}
this.login(values);
}
login(values) {
// here we are supposed to determine whether Casdoor is working as an OAuth server or CAS server
values["language"] = this.state.userLang ?? "";
if (this.state.type === "cas") {
// CAS
const casParams = Util.getCasParameters();
values["signinMethod"] = this.getCurrentLoginMethod();
values["type"] = this.state.type;
AuthBackend.loginCas(values, casParams).then((res) => {
const loginHandler = (res) => {
let msg = "Logged in successfully. ";
if (casParams.service === "") {
// If service was not specified, Casdoor must display a message notifying the client that it has successfully initiated a single sign-on session.
msg += "Now you can visit apps protected by Casdoor.";
}
Setting.showMessage("success", msg);
if (casParams.service !== "") {
const st = res.data;
const newUrl = new URL(casParams.service);
newUrl.searchParams.append("ticket", st);
window.location.href = newUrl.toString();
}
};
if (res.status === "ok") {
Setting.checkLoginMfa(res, values, casParams, loginHandler, this);
} else {
Setting.showMessage("error", `${i18next.t("application:Failed to sign in")}: ${res.msg}`);
}
}).finally(() => {
this.setState({loginLoading: false});
});
} else {
// OAuth
const oAuthParams = Util.getOAuthGetParameters();
this.populateOauthValues(values);
AuthBackend.login(values, oAuthParams)
.then((res) => {
const loginHandler = (res) => {
const responseType = values["type"];
if (responseType === "login") {
if (res.data3) {
sessionStorage.setItem("signinUrl", window.location.pathname + window.location.search);
Setting.goToLinkSoft(this, `/forget/${this.state.applicationName}`);
}
Setting.showMessage("success", i18next.t("application:Logged in successfully"));
this.props.onLoginSuccess();
} else if (responseType === "code") {
this.postCodeLoginAction(res);
} else if (responseType === "device") {
Setting.showMessage("success", "Successful login");
this.setState({
userCodeStatus: "success",
});
} else if (responseType === "token" || responseType === "id_token") {
if (res.data3) {
sessionStorage.setItem("signinUrl", window.location.pathname + window.location.search);
Setting.goToLinkSoft(this, `/forget/${this.state.applicationName}`);
}
const amendatoryResponseType = responseType === "token" ? "access_token" : responseType;
const accessToken = res.data;
Setting.goToLink(`${oAuthParams.redirectUri}#${amendatoryResponseType}=${accessToken}&state=${oAuthParams.state}&token_type=bearer`);
} else if (responseType === "saml") {
if (res.data === RequiredMfa) {
this.props.onLoginSuccess(window.location.href);
return;
}
if (res.data3) {
sessionStorage.setItem("signinUrl", window.location.pathname + window.location.search);
Setting.goToLinkSoft(this, `/forget/${this.state.applicationName}`);
}
if (res.data2.method === "POST") {
this.setState({
samlResponse: res.data,
redirectUrl: res.data2.redirectUrl,
relayState: oAuthParams.relayState,
});
} else {
const SAMLResponse = res.data;
const redirectUri = res.data2.redirectUrl;
Setting.goToLink(`${redirectUri}${redirectUri.includes("?") ? "&" : "?"}SAMLResponse=${encodeURIComponent(SAMLResponse)}&RelayState=${oAuthParams.relayState}`);
}
}
};
if (res.status === "ok") {
Setting.checkLoginMfa(res, values, oAuthParams, loginHandler, this);
} else {
Setting.showMessage("error", `${i18next.t("application:Failed to sign in")}: ${res.msg}`);
}
}).finally(() => {
this.setState({loginLoading: false});
});
}
}
isProviderVisible(providerItem) {
if (this.state.mode === "signup") {
return Setting.isProviderVisibleForSignUp(providerItem);
} else {
return Setting.isProviderVisibleForSignIn(providerItem);
}
}
renderOtherFormProvider(application) {
if (Setting.inIframe()) {
return null;
}
for (const providerConf of application.providers) {
if (providerConf.provider?.type === "Google" && providerConf.rule === "OneTap" && this.props.preview !== "auto") {
return (
{i18next.t("login:Please select an organization to sign in")}
{i18next.t("login:Please type an organization to sign in")}