// 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 from "react";
import {Button, Card, Col, Input, Popover, Row, Select, Switch, Upload} from 'antd';
import {CopyOutlined, LinkOutlined, UploadOutlined} from "@ant-design/icons";
import * as ApplicationBackend from "./backend/ApplicationBackend";
import * as CertBackend from "./backend/CertBackend";
import * as Setting from "./Setting";
import * as ProviderBackend from "./backend/ProviderBackend";
import * as OrganizationBackend from "./backend/OrganizationBackend";
import * as ResourceBackend from "./backend/ResourceBackend";
import SignupPage from "./auth/SignupPage";
import LoginPage from "./auth/LoginPage";
import i18next from "i18next";
import UrlTable from "./UrlTable";
import ProviderTable from "./ProviderTable";
import SignupTable from "./SignupTable";
import PromptPage from "./auth/PromptPage";
import copy from "copy-to-clipboard";
import {Controlled as CodeMirror} from 'react-codemirror2';
import "codemirror/lib/codemirror.css";
require('codemirror/theme/material-darker.css');
require("codemirror/mode/htmlmixed/htmlmixed");
require("codemirror/mode/xml/xml");
const { Option } = Select;
class ApplicationEditPage extends React.Component {
constructor(props) {
super(props);
this.state = {
classes: props,
applicationName: props.match.params.applicationName,
application: null,
organizations: [],
certs: [],
providers: [],
uploading: false,
mode: props.location.mode !== undefined ? props.location.mode : "edit",
samlMetadata: null,
};
}
UNSAFE_componentWillMount() {
this.getApplication();
this.getOrganizations();
this.getCerts();
this.getProviders();
this.getSamlMetadata();
}
getApplication() {
ApplicationBackend.getApplication("admin", this.state.applicationName)
.then((application) => {
if (application.grantTypes === null || application.grantTypes === undefined || application.grantTypes.length === 0) {
application.grantTypes = ["authorization_code"];
}
this.setState({
application: application,
});
});
}
getOrganizations() {
OrganizationBackend.getOrganizations("admin")
.then((res) => {
this.setState({
organizations: (res.msg === undefined) ? res : [],
});
});
}
getCerts() {
CertBackend.getCerts("admin")
.then((res) => {
this.setState({
certs: (res.msg === undefined) ? res : [],
});
});
}
getProviders() {
ProviderBackend.getProviders("admin")
.then((res) => {
this.setState({
providers: res,
});
});
}
getSamlMetadata() {
ApplicationBackend.getSamlMetadata("admin", this.state.applicationName)
.then((res) => {
this.setState({
samlMetadata: res,
})
});
}
parseApplicationField(key, value) {
if (["expireInHours", "refreshExpireInHours"].includes(key)) {
value = Setting.myParseInt(value);
}
return value;
}
updateApplicationField(key, value) {
value = this.parseApplicationField(key, value);
let application = this.state.application;
application[key] = value;
this.setState({
application: application,
});
}
handleUpload(info) {
if (info.file.type !== "text/html") {
Setting.showMessage("error", i18next.t("application:Please select a HTML file"));
return;
}
this.setState({uploading: true});
const fullFilePath = `termsOfUse/${this.state.application.owner}/${this.state.application.name}.html`;
ResourceBackend.uploadResource(this.props.account.owner, this.props.account.name, "termsOfUse", "ApplicationEditPage", fullFilePath, info.file)
.then(res => {
if (res.status === "ok") {
Setting.showMessage("success", i18next.t("application:File uploaded successfully"));
this.updateApplicationField("termsOfUse", res.data);
} else {
Setting.showMessage("error", res.msg);
}
}).finally(() => {
this.setState({uploading: false});
})
}
renderApplication() {
return (
{this.state.mode === "add" ? i18next.t("application:New Application") : i18next.t("application:Edit Application")}
this.submitApplicationEdit(false)}>{i18next.t("general:Save")}
this.submitApplicationEdit(true)}>{i18next.t("general:Save & Exit")}
{this.state.mode === "add" ? this.deleteApplication()}>{i18next.t("general:Cancel")} : null}
} style={(Setting.isMobile())? {margin: '5px'}:{}} type="inner">
{Setting.getLabel(i18next.t("general:Name"), i18next.t("general:Name - Tooltip"))} :
{
this.updateApplicationField('name', e.target.value);
}} />
{Setting.getLabel(i18next.t("general:Display name"), i18next.t("general:Display name - Tooltip"))} :
{
this.updateApplicationField('displayName', e.target.value);
}} />
{Setting.getLabel(i18next.t("general:Logo"), i18next.t("general:Logo - Tooltip"))} :
{Setting.getLabel(i18next.t("general:URL"), i18next.t("general:URL - Tooltip"))} :
} value={this.state.application.logo} onChange={e => {
this.updateApplicationField('logo', e.target.value);
}} />
{i18next.t("general:Preview")}:
{Setting.getLabel(i18next.t("general:Home"), i18next.t("general:Home - Tooltip"))} :
} value={this.state.application.homepageUrl} onChange={e => {
this.updateApplicationField('homepageUrl', e.target.value);
}} />
{Setting.getLabel(i18next.t("general:Description"), i18next.t("general:Description - Tooltip"))} :
{
this.updateApplicationField('description', e.target.value);
}} />
{Setting.getLabel(i18next.t("general:Organization"), i18next.t("general:Organization - Tooltip"))} :
{this.updateApplicationField('organization', value);})}>
{
this.state.organizations.map((organization, index) => {organization.name} )
}
{Setting.getLabel(i18next.t("provider:Client ID"), i18next.t("provider:Client ID - Tooltip"))} :
{
this.updateApplicationField('clientId', e.target.value);
}} />
{Setting.getLabel(i18next.t("provider:Client secret"), i18next.t("provider:Client secret - Tooltip"))} :
{
this.updateApplicationField('clientSecret', e.target.value);
}} />
{Setting.getLabel(i18next.t("general:Cert"), i18next.t("general:Cert - Tooltip"))} :
{this.updateApplicationField('cert', value);})}>
{
this.state.certs.map((cert, index) => {cert.name} )
}
{Setting.getLabel(i18next.t("application:Redirect URLs"), i18next.t("application:Redirect URLs - Tooltip"))} :
{ this.updateApplicationField('redirectUris', value)}}
/>
{Setting.getLabel(i18next.t("application:Token format"), i18next.t("application:Token format - Tooltip"))} :
{this.updateApplicationField('tokenFormat', value);})}>
{
['JWT', 'JWT-Empty']
.map((item, index) => {item} )
}
{Setting.getLabel(i18next.t("application:Token expire"), i18next.t("application:Token expire - Tooltip"))} :
{
this.updateApplicationField('expireInHours', e.target.value);
}} />
{Setting.getLabel(i18next.t("application:Refresh token expire"), i18next.t("application:Refresh token expire - Tooltip"))} :
{
this.updateApplicationField('refreshExpireInHours', e.target.value);
}} />
{Setting.getLabel(i18next.t("application:Password ON"), i18next.t("application:Password ON - Tooltip"))} :
{
this.updateApplicationField('enablePassword', checked);
}} />
{Setting.getLabel(i18next.t("application:Enable signup"), i18next.t("application:Enable signup - Tooltip"))} :
{
this.updateApplicationField('enableSignUp', checked);
}} />
{Setting.getLabel(i18next.t("application:Signin session"), i18next.t("application:Enable signin session - Tooltip"))} :
{
this.updateApplicationField('enableSigninSession', checked);
}} />
{Setting.getLabel(i18next.t("application:Enable code signin"), i18next.t("application:Enable code signin - Tooltip"))} :
{
this.updateApplicationField('enableCodeSignin', checked);
}} />
{Setting.getLabel(i18next.t("general:Signup URL"), i18next.t("general:Signup URL - Tooltip"))} :
} value={this.state.application.signupUrl} onChange={e => {
this.updateApplicationField('signupUrl', e.target.value);
}} />
{Setting.getLabel(i18next.t("general:Signin URL"), i18next.t("general:Signin URL - Tooltip"))} :
} value={this.state.application.signinUrl} onChange={e => {
this.updateApplicationField('signinUrl', e.target.value);
}} />
{Setting.getLabel(i18next.t("general:Forget URL"), i18next.t("general:Forget URL - Tooltip"))} :
} value={this.state.application.forgetUrl} onChange={e => {
this.updateApplicationField('forgetUrl', e.target.value);
}} />
{Setting.getLabel(i18next.t("general:Affiliation URL"), i18next.t("general:Affiliation URL - Tooltip"))} :
} value={this.state.application.affiliationUrl} onChange={e => {
this.updateApplicationField('affiliationUrl', e.target.value);
}} />
{Setting.getLabel(i18next.t("provider:Terms of Use"), i18next.t("provider:Terms of Use - Tooltip"))} :
{
this.updateApplicationField("termsOfUse", e.target.value);
}}/>
{return false}} onChange={info => {this.handleUpload(info)}}>
} loading={this.state.uploading}>{i18next.t("general:Click to Upload")}
{Setting.getLabel(i18next.t("provider:Signup HTML"), i18next.t("provider:Signup HTML - Tooltip"))} :
{
this.updateApplicationField("signupHtml", value);
}}
/>
} title={i18next.t("provider:Signup HTML - Edit")} trigger="click">
{
this.updateApplicationField("signupHtml", e.target.value)
}}/>
{Setting.getLabel(i18next.t("provider:Signin HTML"), i18next.t("provider:Signin HTML - Tooltip"))} :
{
this.updateApplicationField("signinHtml", value);
}}
/>
} title={i18next.t("provider:Signin HTML - Edit")} trigger="click">
{
this.updateApplicationField("signinHtml", e.target.value)
}}/>
{Setting.getLabel(i18next.t("application:Grant types"), i18next.t("application:Grant types - Tooltip"))} :
{
this.updateApplicationField('grantTypes', value);
})} >
{
[
{id: "authorization_code", name: "Authorization Code"},
{id: "password", name: "Password"},
{id: "client_credentials", name: "Client Credentials"},
{id: "token", name: "Token"},
{id: "id_token", name: "ID Token"},
{id: "refresh_token", name: "Refresh Token"},
].map((item, index) => {item.name} )
}
{Setting.getLabel(i18next.t("application:SAML metadata"), i18next.t("application:SAML metadata - Tooltip"))} :
{}}
/>
{Setting.getLabel(i18next.t("general:Providers"), i18next.t("general:Providers - Tooltip"))} :
{ this.updateApplicationField('providers', value)}}
/>
{Setting.getLabel(i18next.t("general:Preview"), i18next.t("general:Preview - Tooltip"))} :
{
this.renderSignupSigninPreview()
}
{
!this.state.application.enableSignUp ? null : (
{Setting.getLabel(i18next.t("application:Signup items"), i18next.t("application:Signup items - Tooltip"))} :
{ this.updateApplicationField('signupItems', value)}}
/>
)
}
{Setting.getLabel(i18next.t("general:Preview"), i18next.t("general:Preview - Tooltip"))} :
{
this.renderPromptPreview()
}
)
}
renderSignupSigninPreview() {
let signUpUrl = `/signup/${this.state.application.name}`;
let signInUrl = `/login/oauth/authorize?client_id=${this.state.application.clientId}&response_type=code&redirect_uri=${this.state.application.redirectUris[0]}&scope=read&state=casdoor`;
let maskStyle = {position: 'absolute', top: '0px', left: '0px', zIndex: 10, height: '100%', width: '100%', background: 'rgba(0,0,0,0.4)'};
if (!this.state.application.enablePassword) {
signUpUrl = signInUrl.replace("/login/oauth/authorize", "/signup/oauth/authorize");
}
return (
} onClick={() => {
copy(`${window.location.origin}${signUpUrl}`);
Setting.showMessage("success", i18next.t("application:Signup page URL copied to clipboard successfully, please paste it into the incognito window or another browser"));
}}
>
{i18next.t("application:Copy signup page URL")}
{
this.state.application.enablePassword ? (
) : (
)
}
} onClick={() => {
copy(`${window.location.origin}${signInUrl}`);
Setting.showMessage("success", i18next.t("application:Signin page URL copied to clipboard successfully, please paste it into the incognito window or another browser"));
}}
>
{i18next.t("application:Copy signin page URL")}
)
}
renderPromptPreview() {
let promptUrl = `/prompt/${this.state.application.name}`;
let maskStyle = {position: 'absolute', top: '0px', left: '0px', zIndex: 10, height: '100%', width: '100%', background: 'rgba(0,0,0,0.4)'};
return (
} onClick={() => {
copy(`${window.location.origin}${promptUrl}`);
Setting.showMessage("success", i18next.t("application:Prompt page URL copied to clipboard successfully, please paste it into the incognito window or another browser"));
}}
>
{i18next.t("application:Copy prompt page URL")}
)
}
submitApplicationEdit(willExist) {
let application = Setting.deepCopy(this.state.application);
ApplicationBackend.updateApplication(this.state.application.owner, this.state.applicationName, application)
.then((res) => {
if (res.msg === "") {
Setting.showMessage("success", `Successfully saved`);
this.setState({
applicationName: this.state.application.name,
});
if (willExist) {
this.props.history.push(`/applications`);
} else {
this.props.history.push(`/applications/${this.state.application.name}`);
}
} else {
Setting.showMessage("error", res.msg);
this.updateApplicationField('name', this.state.applicationName);
}
})
.catch(error => {
Setting.showMessage("error", `Failed to connect to server: ${error}`);
});
}
deleteApplication() {
ApplicationBackend.deleteApplication(this.state.application)
.then(() => {
this.props.history.push(`/applications`);
})
.catch(error => {
Setting.showMessage("error", `Application failed to delete: ${error}`);
});
}
render() {
return (
{
this.state.application !== null ? this.renderApplication() : null
}
this.submitApplicationEdit(false)}>{i18next.t("general:Save")}
this.submitApplicationEdit(true)}>{i18next.t("general:Save & Exit")}
{this.state.mode === "add" ? this.deleteApplication()}>{i18next.t("general:Cancel")} : null}
);
}
}
export default ApplicationEditPage;