Next: , Up: SQL Injection in Action   [Index]


1.1.4.1 client

{
  "name": "psql-demo",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.0",
    "@material-ui/icons": "^4.9.1",
    "material-table": "^1.69.1",
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "react-scripts": "2.1.2"
  },
  "scripts": {
    "start": "PORT=15000 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}
  1. public
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        <meta name="theme-color" content="#000000" />
        <!--
          manifest.json provides metadata used when your web app is added to the
          homescreen on Android. See https://developers.google.com/web/fundamentals/web-app-manifest/
        -->
        <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
        <!--
          Notice the use of %PUBLIC_URL% in the tags above.
          It will be replaced with the URL of the `public` folder during the build.
          Only files inside the `public` folder can be referenced from the HTML.
    
          Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
          work correctly both with client-side routing and a non-root public URL.
          Learn how to configure a non-root public URL by running `npm run build`.
        -->
        <title>simple-mern</title>
      </head>
      <body>
        <noscript>You need to enable JavaScript to run this app.</noscript>
        <div id="root"></div>
        <!--
          This HTML file is a template.
          If you open it directly in the browser, you will see an empty page.
    
          You can add webfonts, meta tags, or analytics to this file.
          The build step will place the bundled scripts into the <body> tag.
    
          To begin the development, run `npm start` or `yarn start`.
          To create a production bundle, use `npm run build` or `yarn build`.
        -->
      </body>
    </html>
    
    {
      "short_name": "simple-mern",
      "name": "simple-mern",
      "icons": [
        {
          "src": "favicon.ico",
          "sizes": "64x64 32x32 24x24 16x16",
          "type": "image/x-icon"
        }
      ],
      "start_url": ".",
      "display": "standalone",
      "theme_color": "#000000",
      "background_color": "#ffffff"
    }
    
  2. src
    .App {
      max-width: 600px;
      margin: auto;
      margin-top: 2em;
      padding: 1em;
      background: white;
      border: 1px solid #ddd;
      border-radius: 8px;
      box-shadow: 0 4px 8px 0px rgba(0, 0, 0, 0.1);
    }
    
    h1 {
      font-weight: normal;
      margin: 0;
      padding-bottom: 8px;
    }
    
    .tasks {
      list-style: none;
      padding: 0;
    }
    
    .done {
      text-decoration: line-through;
      opacity: 0.5;
    }
    
    label {
      vertical-align: top;
    }
    
    .delete-button {
      padding-top: 4px;
      margin-left: 8px;
      cursor: pointer;
      opacity: 0.3;
      visibility: hidden;
    }
    
    li:hover .delete-button {
      visibility: visible;
    }
    
    .delete-button:hover {
      opacity: 0.6;
    }
    
    table {
      font-family: arial, sans-serif;
      border-collapse: collapse;
      width: 100%;
      padding: 8px;
    }
    
    td,
    th {
      border: 1px solid #dddddd;
      text-align: center;
      padding: 8px;
    }
    
    tr:nth-child(even) {
      background-color: #dddddd;
    }
    
    import React, { Component } from "react";
    import { TextField } from "@material-ui/core";
    import Button from "@material-ui/core/Button";
    import "./App.css";
    
    import StudentList from "./components/StudentList";
    
    class App extends Component {
      state = {
        new_first_name: "",
        new_last_name: "",
        new_id: "",
      };
    
      handleChange = (event) => {
        this.setState({ [event.target.name]: event.target.value });
      };
    
      clickAddStudent = (event) => {
        event.preventDefault();
    
        const first_name = this.state.new_first_name;
        const last_name = this.state.new_last_name;
        const id = this.state.new_id;
        const url = window.location.href.slice(0, -1);
    
        fetch(url + ":3000/api/students/add", {
          method: "post",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ first_name, last_name, id }),
        }).then(() => {
          this.setState({ newStudentTitle: "" });
          this.refs.studentList.getStudents();
        });
      };
    
      render() {
        return (
          <React.Fragment>
            <div className="App">
              <StudentList ref="studentList" />
              <form onSubmit={this.clickAddStudent}>
                <TextField
                  variant="outlined"
                  margin="normal"
                  required
                  fullWidth
                  id="new_first_name"
                  label="First Name"
                  name="new_first_name"
                  autoComplete="first_name"
                  autoFocus
                  onChange={this.handleChange}
                />
                <TextField
                  variant="outlined"
                  margin="normal"
                  required
                  fullWidth
                  id="new_last_name"
                  label="Last Name"
                  name="new_last_name"
                  autoComplete="last_name"
                  onChange={this.handleChange}
                />
                <TextField
                  variant="outlined"
                  margin="normal"
                  required
                  fullWidth
                  id="new_id"
                  label="ID"
                  name="new_id"
                  autoComplete="id"
                  onChange={this.handleChange}
                />
                <Button type="submit" fullWidth variant="contained" color="primary">
                  Add
                </Button>
              </form>
            </div>
          </React.Fragment>
        );
      }
    }
    
    export default App;
    
    body {
      margin: 0;
      padding: 0;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
        "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
        sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      font-size: 16px;
    }
    
    code {
      font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
        monospace;
    }
    
    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    
    ReactDOM.render(<App />, document.getElementById('root'));
    
    1. components
      import React, { Component, forwardRef } from "react";
      import { Container } from "@material-ui/core/";
      import MaterialTable from "material-table";
      import {
        AddBox,
        ArrowUpward,
        Check,
        ChevronLeft,
        ChevronRight,
        Clear,
        DeleteOutline,
        Edit,
        FilterList,
        FirstPage,
        LastPage,
        Print,
        Remove,
        SaveAlt,
        Search,
        ViewColumn,
      } from "@material-ui/icons/";
      
      export default class StudentList extends Component {
        state = {
          columns: [
            { title: "First Name", field: "first_name" },
            { title: "Last Name", field: "last_name" },
            { title: "ID", field: "id", type: "numeric" },
          ],
          data: [],
          loaded: false,
        };
      
        componentDidMount() {
          this.getStudents();
        }
      
        getStudents = () => {
          const url = window.location.href.slice(0, -1);
          fetch(url + ":3000/api/students")
            .then((res) => res.json())
            .then((students) => {
              if (students.name === "SequelizeDatabaseError") {
                console.log("Empty!");
              } else {
                this.setState({
                  data: [...students],
                });
              }
            });
        };
      
        clickUpdateStudent = (old, student) => {
          const url = window.location.href.slice(0, -1);
          var { first_name, last_name, id } = student;
          fetch(url + `:3000/api/students/update/${old.id}`, {
            method: "post",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ first_name, last_name, id }),
          }).then((res) => res.json());
        };
      
        clickDeleteStudent = (studentId) => {
          const url = window.location.href.slice(0, -1);
          fetch(url + `:3000/api/students/delete/${studentId}`, {
            method: "delete",
          })
            .then((res) => res.json())
            .catch((err) => console.log(err));
        };
      
        render() {
          const tableIcons = {
            Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
            Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
            Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
            Delete: forwardRef((props, ref) => (
              <DeleteOutline {...props} ref={ref} />
            )),
            Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
            Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
            Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
            FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
            LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
            NextPage: forwardRef((props, ref) => (
              <ChevronRight {...props} ref={ref} />
            )),
            PreviousPage: forwardRef((props, ref) => (
              <ChevronLeft {...props} ref={ref} />
            )),
            Print: forwardRef((props, ref) => <Print {...props} ref={ref} />),
            ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
            Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
            SortArrow: forwardRef((props, ref) => (
              <ArrowUpward {...props} ref={ref} />
            )),
            ThirdStateCheck: forwardRef((props, ref) => (
              <Remove {...props} ref={ref} />
            )),
            ViewColumn: forwardRef((props, ref) => (
              <ViewColumn {...props} ref={ref} />
            )),
          };
          return (
            <Container maxWidth="xl" disableGutters={true}>
              <React.Fragment>
                <MaterialTable
                  title="Records table"
                  columns={this.state.columns}
                  data={this.state.data}
                  editable={{
                    onRowUpdate: (newData, oldData) =>
                      new Promise((resolve, reject) => {
                        setTimeout(() => {
                          let data = [...this.state.data];
                          const index = data.indexOf(oldData);
                          data[index] = newData;
                          this.clickUpdateStudent(oldData, newData);
                          this.setState({
                            data: data,
                          });
                          resolve();
                        }, 1000);
                      }),
                    onRowDelete: (oldData) =>
                      new Promise((resolve, reject) => {
                        setTimeout(() => {
                          {
                            let data = this.state.data;
                            const index = data.indexOf(oldData);
                            const del_id = data[index].id;
                            this.clickDeleteStudent(del_id);
                            this.setState({
                              data: data.filter((student) => student.id !== del_id),
                            });
                            this.getStudents();
                          }
                          resolve();
                        }, 1000);
                      }),
                  }}
                  icons={tableIcons}
                  options={{
                    rowStyle: {
                      backgroundColor: "#FFFFFF",
                    },
                    headerStyle: {
                      backgroundColor: "#EEE",
                      fontWeight: "bold",
                      fontSize: 16,
                    },
                  }}
                />
              </React.Fragment>
            </Container>
          );
        }
      }
      

Next: , Up: SQL Injection in Action   [Index]