Skip to content

Commit

Permalink
Add AddRecord()
Browse files Browse the repository at this point in the history
  • Loading branch information
HeartLinked committed May 23, 2024
1 parent 110e91c commit 6309ca6
Show file tree
Hide file tree
Showing 10 changed files with 166 additions and 46 deletions.
11 changes: 11 additions & 0 deletions controllers/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"encoding/gob"

"github.com/beego/beego"
"github.com/casbin/caswaf/object"
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
)

Expand Down Expand Up @@ -47,6 +48,16 @@ func wrapActionResponse(affected bool, e ...error) *Response {
}
}

func wrapRecordResponse(record *object.Record, err error) *Response {
if err != nil {
return &Response{Status: "error", Msg: err.Error()}
}
if record != nil {
return &Response{Status: "ok", Data: record}
}
return &Response{Status: "error", Msg: "Record not found"}
}

func (c *ApiController) GetSessionClaims() *casdoorsdk.Claims {
s := c.GetSession("user")
if s == nil {
Expand Down
37 changes: 37 additions & 0 deletions controllers/record.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
// Copyright 2024 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/casbin/caswaf/object"
)

Expand Down Expand Up @@ -75,3 +90,25 @@ func (c *ApiController) GetRecord() {

c.ResponseOk(record)
}

func (c *ApiController) AddRecord() {
if c.RequireSignedIn() {
return
}

var record object.Record
err := json.Unmarshal(c.Ctx.Input.RequestBody, &record)
if err != nil {
c.ResponseError(err.Error())
return
}

addedRecord, err := object.AddRecord(&record)
if err != nil {
c.ResponseError(err.Error())
return
}

c.Data["json"] = wrapRecordResponse(addedRecord, err)
c.ServeJSON()
}
63 changes: 47 additions & 16 deletions object/record.go
Original file line number Diff line number Diff line change
@@ -1,39 +1,56 @@
// Copyright 2024 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 (
"fmt"
"github.com/xorm-io/core"
"net/http"
"strconv"
"strings"

"github.com/casbin/caswaf/util"
"github.com/xorm-io/core"
)

type Record struct {
Id int64 `xorm:"int notnull pk autoincr" json:"id"`
Owner string `xorm:"varchar(100) notnull" json:"owner"`
CreatedTime string `xorm:"varchar(100) notnull" json:"createdTime"`

Method string `xorm:"varchar(100)" json:"method"`
Host string `xorm:"varchar(100)" json:"host"`
RequestURI string `xorm:"varchar(100)" json:"requestURI"`
UserAgent string `xorm:"varchar(512)" json:"userAgent"`
Method string `xorm:"varchar(100)" json:"method"`
Host string `xorm:"varchar(100)" json:"host"`
Path string `xorm:"varchar(100)" json:"path"`
UserAgent string `xorm:"varchar(512)" json:"userAgent"`
}

func GetRecords(owner string) ([]*Record, error) {
records := []*Record{}
err := ormer.Engine.Asc("Id").Desc("created_time").Asc("Host").Asc("request_u_r_i").Find(&records, &Record{Owner: owner})
err := ormer.Engine.Asc("id").Asc("host").Find(&records, &Record{Owner: owner})
if err != nil {
return nil, err
}

return records, nil
}

func AddRecord(record *Record) (bool, error) {
affected, err := ormer.Engine.Insert(record)
func AddRecord(record *Record) (*Record, error) {
_, err := ormer.Engine.Insert(record)
if err != nil {
return false, err
return nil, err
}

return affected != 0, nil
return record, nil
}

func DeleteRecord(record *Record) (bool, error) {
Expand All @@ -46,11 +63,6 @@ func DeleteRecord(record *Record) (bool, error) {
}

func UpdateRecord(owner string, id string, record *Record) (bool, error) {
//id_num, err := strconv.ParseInt(id, 10, 64)
//if err != nil {
// fmt.Println("Failed to transform id(string) to num: ", err)
//}

affected, err := ormer.Engine.ID(core.PK{record.Id}).AllCols().Update(record)
if err != nil {
return false, err
Expand Down Expand Up @@ -84,3 +96,22 @@ func getRecord(owner string, id int64) (*Record, error) {
}
return nil, nil
}

func LogRequest(r *http.Request) {
if !strings.Contains(r.UserAgent(), "Uptime-Kuma") {
fmt.Printf("handleRequest: %s\t%s\t%s\t%s\t%s\n", r.RemoteAddr, r.Method, r.Host, r.RequestURI, r.UserAgent())
record := Record{
Owner: "admin",
CreatedTime: util.GetCurrentFormattedTime(),
Method: r.Method,
Host: r.Host,
Path: r.RequestURI,
UserAgent: r.UserAgent(),
}
fmt.Println(util.GetCurrentTime())
_, err := AddRecord(&record)
if err != nil {
fmt.Println(err.Error())
}
}
}
2 changes: 2 additions & 0 deletions routers/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,6 @@ func initAPI() {
beego.Router("/api/get-record", &controllers.ApiController{}, "GET:GetRecord")
beego.Router("/api/delete-record", &controllers.ApiController{}, "POST:DeleteRecord")
beego.Router("/api/update-record", &controllers.ApiController{}, "POST:UpdateRecord")
beego.Router("/api/add-record", &controllers.ApiController{}, "POST:AddRecord")

}
19 changes: 2 additions & 17 deletions service/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,17 @@ package service
import (
"crypto/tls"
"fmt"
httptx "github.com/corazawaf/coraza/v3/http"
"net"
"net/http"
"net/http/httputil"
"net/url"
"path/filepath"
"strings"
"time"

"github.com/beego/beego"
"github.com/casbin/caswaf/object"
"github.com/casbin/caswaf/util"
httptx "github.com/corazawaf/coraza/v3/http"
)

func forwardHandler(targetUrl string, writer http.ResponseWriter, request *http.Request) {
Expand Down Expand Up @@ -83,21 +82,7 @@ func redirectToHost(w http.ResponseWriter, r *http.Request, host string) {
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.UserAgent(), "Uptime-Kuma") {
fmt.Printf("handleRequest: %s\t%s\t%s\t%s\t%s\n", r.RemoteAddr, r.Method, r.Host, r.RequestURI, r.UserAgent())
record := object.Record{
Owner: "admin",
CreatedTime: time.Now().Format("2006-01-02 15:04:05.000000"),
Method: r.Method,
Host: r.Host,
RequestURI: r.RequestURI,
UserAgent: r.UserAgent(),
}
_, err := object.AddRecord(&record)
if err != nil {
fmt.Println(err.Error())
}
}
object.LogRequest(r)

site := getSiteByDomainWithWww(r.Host)
if site == nil {
Expand Down
10 changes: 10 additions & 0 deletions util/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,13 @@ func GetCurrentTime() string {
tm := time.Unix(timestamp, 0)
return tm.In(location).Format(time.RFC3339)
}

func GetCurrentFormattedTime() string {
location, err := time.LoadLocation("Asia/Singapore")
if err != nil {
panic(err)
}

tm := time.Now().In(location)
return tm.Format("2006-01-02 15:04:05")
}
4 changes: 1 addition & 3 deletions web/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,8 @@ import CertListPage from "./CertListPage";
import CertEditPage from "./CertEditPage";
import SigninPage from "./SigninPage";
import RecordListPage from "./RecordListPage";

import i18next from "i18next";
import RecordEditPage from "./RecordEditPage";
// import SelectLanguageBox from "./SelectLanguageBox";
import i18next from "i18next";

const {Header, Footer} = Layout;

Expand Down
6 changes: 3 additions & 3 deletions web/src/RecordEditPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,11 @@ class RecordEditPage extends React.Component {
</Row>
<Row style={{marginTop: "10px"}} >
<Col style={{marginTop: "5px"}} span={2}>
{i18next.t("general:RequestURI")}:
{i18next.t("general:Path")}:
</Col>
<Col span={22} >
<Input value={this.state.record.requestURI} onChange={e => {
this.updateRecordField("requestURI", e.target.value);
<Input value={this.state.record.path} onChange={e => {
this.updateRecordField("path", e.target.value);
}} />
</Col>
</Row>
Expand Down
48 changes: 41 additions & 7 deletions web/src/RecordListPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import React from "react";
import {Button, Col, Popconfirm, Row, Table} from "antd";
import moment from "moment";
import * as Setting from "./Setting";
import * as RecordBackend from "./backend/RecordBackend";
import i18next from "i18next";
Expand Down Expand Up @@ -44,6 +45,38 @@ class RecordListPage extends React.Component {
});
}

newRecord() {
const randomName = Setting.getRandomName();
return {
owner: this.props.account.name,
name: `record_${randomName}`,
createdTime: moment().format("YYYY-MM-DD HH:mm:ss"),
method: "GET",
host: "door.casdoor.com",
path: "/",
userAgent: "",
};
}

addRecord() {
const newRecord = this.newRecord();
RecordBackend.addRecord(newRecord)
.then((res) => {
if (res.status === "error") {
Setting.showMessage("error", `Failed to add: ${res.msg}`);
} else {
Setting.showMessage("success", "Record added successfully");
this.setState({
records: Setting.addRow(this.state.records, res.data),
});
}
}
)
.catch(error => {
Setting.showMessage("error", `Record failed to add: ${error}`);
});
}

deleteRecord(i) {
RecordBackend.deleteRecord(this.state.records[i])
.then((res) => {
Expand All @@ -66,7 +99,7 @@ class RecordListPage extends React.Component {

const columns = [
{
title: i18next.t("general:Id"),
title: i18next.t("general:ID"),
dataIndex: "id",
key: "id",
width: "40px",
Expand All @@ -80,7 +113,7 @@ class RecordListPage extends React.Component {
sorter: (a, b) => a.owner.localeCompare(b.owner),
},
{
title: i18next.t("general:CreatedTime"),
title: i18next.t("general:Created time"),
dataIndex: "createdTime",
key: "createdTime",
width: "70px",
Expand All @@ -101,14 +134,14 @@ class RecordListPage extends React.Component {
sorter: (a, b) => a.host.localeCompare(b.host),
},
{
title: i18next.t("general:RequestURI"),
dataIndex: "requestURI",
key: "requestURI",
title: i18next.t("general:Path"),
dataIndex: "path",
key: "path",
width: "100px",
sorter: (a, b) => a.requestURI.localeCompare(b.requestURI),
sorter: (a, b) => a.path.localeCompare(b.path),
},
{
title: i18next.t("general:UserAgent"),
title: i18next.t("general:User agent"),
dataIndex: "userAgent",
key: "userAgent",
width: "240px",
Expand Down Expand Up @@ -143,6 +176,7 @@ class RecordListPage extends React.Component {
title={() => (
<div>
{i18next.t("general:Records")}&nbsp;&nbsp;&nbsp;&nbsp;
<Button type="primary" size="small" onClick={this.addRecord.bind(this)}>{i18next.t("general:Add")}</Button>
</div>
)}
loading={records === null}
Expand Down
12 changes: 12 additions & 0 deletions web/src/backend/RecordBackend.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,15 @@ export function updateRecord(owner, id, record) {
body: JSON.stringify(newRecord),
}).then(res => res.json());
}

export function addRecord(record) {
const newRecord = Setting.deepCopy(record);
return fetch(`${Setting.ServerUrl}/api/add-record`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newRecord),
}).then(res => res.json());
}

0 comments on commit 6309ca6

Please sign in to comment.