Add token pages.

This commit is contained in:
Yang Luo 2021-03-13 23:47:35 +08:00
parent 64c9548019
commit 85523fa9d4
8 changed files with 636 additions and 0 deletions

70
controllers/token.go Normal file
View File

@ -0,0 +1,70 @@
// Copyright 2021 The casbin 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.
package controllers
import (
"encoding/json"
"github.com/casdoor/casdoor/object"
)
func (c *ApiController) GetTokens() {
owner := c.Input().Get("owner")
c.Data["json"] = object.GetTokens(owner)
c.ServeJSON()
}
func (c *ApiController) GetToken() {
id := c.Input().Get("id")
c.Data["json"] = object.GetToken(id)
c.ServeJSON()
}
func (c *ApiController) UpdateToken() {
id := c.Input().Get("id")
var token object.Token
err := json.Unmarshal(c.Ctx.Input.RequestBody, &token)
if err != nil {
panic(err)
}
c.Data["json"] = object.UpdateToken(id, &token)
c.ServeJSON()
}
func (c *ApiController) AddToken() {
var token object.Token
err := json.Unmarshal(c.Ctx.Input.RequestBody, &token)
if err != nil {
panic(err)
}
c.Data["json"] = object.AddToken(&token)
c.ServeJSON()
}
func (c *ApiController) DeleteToken() {
var token object.Token
err := json.Unmarshal(c.Ctx.Input.RequestBody, &token)
if err != nil {
panic(err)
}
c.Data["json"] = object.DeleteToken(&token)
c.ServeJSON()
}

View File

@ -109,4 +109,9 @@ func (a *Adapter) createTable() {
if err != nil {
panic(err)
}
err = a.engine.Sync2(new(Token))
if err != nil {
panic(err)
}
}

95
object/token.go Normal file
View File

@ -0,0 +1,95 @@
// Copyright 2021 The casbin 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.
package object
import (
"github.com/casdoor/casdoor/util"
"xorm.io/core"
)
type Token struct {
Owner string `xorm:"varchar(100) notnull pk" json:"owner"`
Name string `xorm:"varchar(100) notnull pk" json:"name"`
CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
Application string `xorm:"varchar(100)" json:"application"`
AccessToken string `xorm:"varchar(100)" json:"accessToken"`
ExpiresIn int `json:"expiresIn"`
Scope string `xorm:"varchar(100)" json:"scope"`
TokenType string `xorm:"varchar(100)" json:"tokenType"`
}
func GetTokens(owner string) []*Token {
tokens := []*Token{}
err := adapter.engine.Desc("created_time").Find(&tokens, &Token{Owner: owner})
if err != nil {
panic(err)
}
return tokens
}
func getToken(owner string, name string) *Token {
token := Token{Owner: owner, Name: name}
existed, err := adapter.engine.Get(&token)
if err != nil {
panic(err)
}
if existed {
return &token
} else {
return nil
}
}
func GetToken(id string) *Token {
owner, name := util.GetOwnerAndNameFromId(id)
return getToken(owner, name)
}
func UpdateToken(id string, token *Token) bool {
owner, name := util.GetOwnerAndNameFromId(id)
if getToken(owner, name) == nil {
return false
}
_, err := adapter.engine.ID(core.PK{owner, name}).AllCols().Update(token)
if err != nil {
panic(err)
}
//return affected != 0
return true
}
func AddToken(token *Token) bool {
affected, err := adapter.engine.Insert(token)
if err != nil {
panic(err)
}
return affected != 0
}
func DeleteToken(token *Token) bool {
affected, err := adapter.engine.ID(core.PK{token.Owner, token.Name}).Delete(&Token{})
if err != nil {
panic(err)
}
return affected != 0
}

View File

@ -63,4 +63,10 @@ func initAPI() {
beego.Router("/api/update-application", &controllers.ApiController{}, "POST:UpdateApplication")
beego.Router("/api/add-application", &controllers.ApiController{}, "POST:AddApplication")
beego.Router("/api/delete-application", &controllers.ApiController{}, "POST:DeleteApplication")
beego.Router("/api/get-tokens", &controllers.ApiController{}, "GET:GetTokens")
beego.Router("/api/get-token", &controllers.ApiController{}, "GET:GetToken")
beego.Router("/api/update-token", &controllers.ApiController{}, "POST:UpdateToken")
beego.Router("/api/add-token", &controllers.ApiController{}, "POST:AddToken")
beego.Router("/api/delete-token", &controllers.ApiController{}, "POST:DeleteToken")
}

View File

@ -26,6 +26,8 @@ import ProviderListPage from "./ProviderListPage";
import ProviderEditPage from "./ProviderEditPage";
import ApplicationListPage from "./ApplicationListPage";
import ApplicationEditPage from "./ApplicationEditPage";
import TokenListPage from "./TokenListPage";
import TokenEditPage from "./TokenEditPage";
import AccountPage from "./account/AccountPage";
import HomePage from "./basic/HomePage";
import CustomGithubCorner from "./CustomGithubCorner";
@ -76,6 +78,8 @@ class App extends Component {
this.setState({ selectedMenuKey: 3 });
} else if (uri.includes('applications')) {
this.setState({ selectedMenuKey: 4 });
} else if (uri.includes('tokens')) {
this.setState({ selectedMenuKey: 5 });
} else {
this.setState({ selectedMenuKey: -1 });
}
@ -227,6 +231,13 @@ class App extends Component {
</Link>
</Menu.Item>
);
res.push(
<Menu.Item key="5">
<Link to="/tokens">
{i18next.t("general:Tokens")}
</Link>
</Menu.Item>
);
}
return res;
}
@ -290,6 +301,8 @@ class App extends Component {
<Route exact path="/providers/:providerName" render={(props) => this.renderLoginIfNotLoggedIn(<ProviderEditPage account={this.state.account} {...props} />)}/>
<Route exact path="/applications" render={(props) => this.renderLoginIfNotLoggedIn(<ApplicationListPage account={this.state.account} {...props} />)}/>
<Route exact path="/applications/:applicationName" render={(props) => this.renderLoginIfNotLoggedIn(<ApplicationEditPage account={this.state.account} {...props} />)}/>
<Route exact path="/tokens" render={(props) => this.renderLoginIfNotLoggedIn(<TokenListPage account={this.state.account} {...props} />)}/>
<Route exact path="/tokens/:tokenName" render={(props) => this.renderLoginIfNotLoggedIn(<TokenEditPage account={this.state.account} {...props} />)}/>
</Switch>
</div>
)

181
web/src/TokenEditPage.js Normal file
View File

@ -0,0 +1,181 @@
// Copyright 2021 The casbin 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, Row, Select} from 'antd';
import * as TokenBackend from "./backend/TokenBackend";
import * as Setting from "./Setting";
import i18next from "i18next";
const { Option } = Select;
class TokenEditPage extends React.Component {
constructor(props) {
super(props);
this.state = {
classes: props,
tokenName: props.match.params.tokenName,
token: null,
};
}
componentWillMount() {
this.getToken();
}
getToken() {
TokenBackend.getToken("admin", this.state.tokenName)
.then((token) => {
this.setState({
token: token,
});
});
}
parseTokenField(key, value) {
// if ([].includes(key)) {
// value = Setting.myParseInt(value);
// }
return value;
}
updateTokenField(key, value) {
value = this.parseTokenField(key, value);
let token = this.state.token;
token[key] = value;
this.setState({
token: token,
});
}
renderToken() {
return (
<Card size="small" title={
<div>
{i18next.t("token:Edit Token")}&nbsp;&nbsp;&nbsp;&nbsp;
<Button type="primary" onClick={this.submitTokenEdit.bind(this)}>{i18next.t("general:Save")}</Button>
</div>
} style={{marginLeft: '5px'}} type="inner">
<Row style={{marginTop: '10px'}} >
<Col style={{marginTop: '5px'}} span={2}>
{i18next.t("general:Name")}:
</Col>
<Col span={22} >
<Input value={this.state.token.name} onChange={e => {
this.updateTokenField('name', e.target.value);
}} />
</Col>
</Row>
<Row style={{marginTop: '20px'}} >
<Col style={{marginTop: '5px'}} span={2}>
{i18next.t("general:Application")}:
</Col>
<Col span={22} >
<Input value={this.state.token.application} onChange={e => {
this.updateTokenField('application', e.target.value);
}} />
</Col>
</Row>
<Row style={{marginTop: '20px'}} >
<Col style={{marginTop: '5px'}} span={2}>
{i18next.t("general:Access Token")}:
</Col>
<Col span={22} >
<Input value={this.state.token.accessToken} onChange={e => {
this.updateTokenField('accessToken', e.target.value);
}} />
</Col>
</Row>
<Row style={{marginTop: '20px'}} >
<Col style={{marginTop: '5px'}} span={2}>
{i18next.t("general:Expires In")}:
</Col>
<Col span={22} >
<Input value={this.state.token.expiresIn} onChange={e => {
this.updateTokenField('expiresIn', e.target.value);
}} />
</Col>
</Row>
<Row style={{marginTop: '20px'}} >
<Col style={{marginTop: '5px'}} span={2}>
{i18next.t("general:Scope")}:
</Col>
<Col span={22} >
<Input value={this.state.token.scope} onChange={e => {
this.updateTokenField('scope', e.target.value);
}} />
</Col>
</Row>
<Row style={{marginTop: '20px'}} >
<Col style={{marginTop: '5px'}} span={2}>
{i18next.t("general:Token Type")}:
</Col>
<Col span={22} >
<Input value={this.state.token.tokenType} onChange={e => {
this.updateTokenField('tokenType', e.target.value);
}} />
</Col>
</Row>
</Card>
)
}
submitTokenEdit() {
let token = Setting.deepCopy(this.state.token);
TokenBackend.updateToken(this.state.token.owner, this.state.tokenName, token)
.then((res) => {
if (res) {
Setting.showMessage("success", `Successfully saved`);
this.setState({
tokenName: this.state.token.name,
});
this.props.history.push(`/tokens/${this.state.token.name}`);
} else {
Setting.showMessage("error", `failed to save: server side failure`);
this.updateTokenField('name', this.state.tokenName);
}
})
.catch(error => {
Setting.showMessage("error", `failed to save: ${error}`);
});
}
render() {
return (
<div>
<Row style={{width: "100%"}}>
<Col span={1}>
</Col>
<Col span={22}>
{
this.state.token !== null ? this.renderToken() : null
}
</Col>
<Col span={1}>
</Col>
</Row>
<Row style={{margin: 10}}>
<Col span={2}>
</Col>
<Col span={18}>
<Button type="primary" size="large" onClick={this.submitTokenEdit.bind(this)}>{i18next.t("general:Save")}</Button>
</Col>
</Row>
</div>
);
}
}
export default TokenEditPage;

210
web/src/TokenListPage.js Normal file
View File

@ -0,0 +1,210 @@
// Copyright 2021 The casbin 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 {Link} from "react-router-dom";
import {Button, Col, Popconfirm, Row, Table} from 'antd';
import moment from "moment";
import * as Setting from "./Setting";
import * as TokenBackend from "./backend/TokenBackend";
import i18next from "i18next";
class TokenListPage extends React.Component {
constructor(props) {
super(props);
this.state = {
classes: props,
tokens: null,
};
}
componentWillMount() {
this.getTokens();
}
getTokens() {
TokenBackend.getTokens("admin")
.then((res) => {
this.setState({
tokens: res,
});
});
}
newToken() {
return {
owner: "admin", // this.props.account.tokenname,
name: `token_${this.state.tokens.length}`,
createdTime: moment().format(),
application: "app-built-in",
accessToken: "",
expiresIn: 7200,
scope: "read",
tokenType: "Bearer",
}
}
addToken() {
const newToken = this.newToken();
TokenBackend.addToken(newToken)
.then((res) => {
Setting.showMessage("success", `Token added successfully`);
this.setState({
tokens: Setting.prependRow(this.state.tokens, newToken),
});
}
)
.catch(error => {
Setting.showMessage("error", `Token failed to add: ${error}`);
});
}
deleteToken(i) {
TokenBackend.deleteToken(this.state.tokens[i])
.then((res) => {
Setting.showMessage("success", `Token deleted successfully`);
this.setState({
tokens: Setting.deleteRow(this.state.tokens, i),
});
}
)
.catch(error => {
Setting.showMessage("error", `Token failed to delete: ${error}`);
});
}
renderTable(tokens) {
const columns = [
{
title: i18next.t("general:Name"),
dataIndex: 'name',
key: 'name',
width: '120px',
sorter: (a, b) => a.name.localeCompare(b.name),
render: (text, record, index) => {
return (
<Link to={`/tokens/${text}`}>
{text}
</Link>
)
}
},
{
title: i18next.t("general:Created Time"),
dataIndex: 'createdTime',
key: 'createdTime',
width: '160px',
sorter: (a, b) => a.createdTime.localeCompare(b.createdTime),
render: (text, record, index) => {
return Setting.getFormattedDate(text);
}
},
{
title: i18next.t("token:Application"),
dataIndex: 'application',
key: 'application',
width: '150px',
sorter: (a, b) => a.application.localeCompare(b.application),
render: (text, record, index) => {
return (
<a href={`/applications/${text}`}>
{text}
</a>
)
}
},
{
title: i18next.t("token:Access Token"),
dataIndex: 'accessToken',
key: 'accessToken',
width: '150px',
sorter: (a, b) => a.accessToken.localeCompare(b.accessToken),
},
{
title: i18next.t("token:Expires In"),
dataIndex: 'expiresIn',
key: 'expiresIn',
width: '150px',
sorter: (a, b) => a.expiresIn - b.expiresIn,
},
{
title: i18next.t("token:Scope"),
dataIndex: 'scope',
key: 'scope',
width: '150px',
sorter: (a, b) => a.scope.localeCompare(b.scope),
},
{
title: i18next.t("token:Token Type"),
dataIndex: 'tokenType',
key: 'tokenType',
width: '150px',
sorter: (a, b) => a.tokenType.localeCompare(b.tokenType),
},
{
title: i18next.t("general:Action"),
dataIndex: '',
key: 'op',
width: '170px',
render: (text, record, index) => {
return (
<div>
<Button style={{marginTop: '10px', marginBottom: '10px', marginRight: '10px'}} type="primary" onClick={() => this.props.history.push(`/tokens/${record.name}`)}>{i18next.t("general:Edit")}</Button>
<Popconfirm
title={`Sure to delete token: ${record.name} ?`}
onConfirm={() => this.deleteToken(index)}
>
<Button style={{marginBottom: '10px'}} type="danger">{i18next.t("general:Delete")}</Button>
</Popconfirm>
</div>
)
}
},
];
return (
<div>
<Table columns={columns} dataSource={tokens} rowKey="name" size="middle" bordered pagination={{pageSize: 100}}
title={() => (
<div>
{i18next.t("general:Tokens")}&nbsp;&nbsp;&nbsp;&nbsp;
<Button type="primary" size="small" onClick={this.addToken.bind(this)}>{i18next.t("general:Add")}</Button>
</div>
)}
loading={tokens === null}
/>
</div>
);
}
render() {
return (
<div>
<Row style={{width: "100%"}}>
<Col span={1}>
</Col>
<Col span={22}>
{
this.renderTable(this.state.tokens)
}
</Col>
<Col span={1}>
</Col>
</Row>
</div>
);
}
}
export default TokenListPage;

View File

@ -0,0 +1,56 @@
// Copyright 2021 The casbin 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 * as Setting from "../Setting";
export function getTokens(owner) {
return fetch(`${Setting.ServerUrl}/api/get-tokens?owner=${owner}`, {
method: "GET",
credentials: "include"
}).then(res => res.json());
}
export function getToken(owner, name) {
return fetch(`${Setting.ServerUrl}/api/get-token?id=${owner}/${encodeURIComponent(name)}`, {
method: "GET",
credentials: "include"
}).then(res => res.json());
}
export function updateToken(owner, name, token) {
let newToken = Setting.deepCopy(token);
return fetch(`${Setting.ServerUrl}/api/update-token?id=${owner}/${encodeURIComponent(name)}`, {
method: 'POST',
credentials: 'include',
body: JSON.stringify(newToken),
}).then(res => res.json());
}
export function addToken(token) {
let newToken = Setting.deepCopy(token);
return fetch(`${Setting.ServerUrl}/api/add-token`, {
method: 'POST',
credentials: 'include',
body: JSON.stringify(newToken),
}).then(res => res.json());
}
export function deleteToken(token) {
let newToken = Setting.deepCopy(token);
return fetch(`${Setting.ServerUrl}/api/delete-token`, {
method: 'POST',
credentials: 'include',
body: JSON.stringify(newToken),
}).then(res => res.json());
}