How to show different content to each user of my web app? MERN stack

0

I'm trying to make a voting app where you can only vote once, for this I collect the ip of the users who vote and then compare these saved ip with the one of who is using the app (to know if I already perform your vote) and so show him one thing or another. The problem is that once a user makes a vote this already blocks the possibility of voting for everyone else who enters. What I want to achieve is to only block the possibility of voting for those who already have their ip in the database and not the rest. That each user can see the content of the app regardless of what another different user does.

This is the backend code that is responsible for obtaining the ip of each user and all users who have already voted:

const express = require("express");
const router = express.Router();
const ipify = require("ipify");
const mongoose = require("mongoose");
const internalIp = require("internal-ip");

const ipModel = require("../../models/Ip");

// @route   GET api/ip
// @desc    obtener todas las ip de la db
// @access  public
router.get("/", (req, res) => {
  ipModel
    .find()
    .then(ip => {
      res.status(200).json(ip);
    })
    .catch(err => res.status(404).json(err));
});

// @route   POST api/ip
// @desc    Guardar la ip en la db
// @access  public
router.post("/", (req, res) => {
  internalIp
    .v4()
    .then(miip => {
      ipModel
        .findOne({ ip: miip })
        .then(laip => {
          if (laip) {
            return res
              .status(400)
              .json({ ip: "Su voto se ha realizado exitosamente" });
          } else {
            const newIp = new ipModel({
              ip: miip
            });
            newIp.save().then(ip => res.json(newIp));
          }
        })
        .catch(err => res.status(404).json(err));
    })
    .catch(err => res.json(err));
});

// @route   GET api/ip/miip
// @desc    Guardar la ip en la db
// @access  public
router.get("/miip", (req, res) => {
  internalIp
    .v4()
    .then(miip => {
      res.status(200).json(miip);
    })
    .catch(err => res.json(err));
});

module.exports = router;

And here the code of the component that is responsible for the logic of the votes in the front end:

import React, { Component } from "react";
import { Redirect } from "react-router-dom";
import { Container, ListGroup, ListGroupItem, Button } from "reactstrap";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import axios from "axios";

class Votos extends Component {
  constructor() {
    super();
    this.state = {
      carrozas: [],
      ipRegistradas: [],
      miIp: null,
      goToVotos: true
    };
    this.votar = this.votar.bind(this);
  }

  componentDidMount() {
    axios
      .get("/api/ip")
      .then(ips => {
        this.setState(prevState => ({
          ipRegistradas: [...prevState.ipRegistradas, ...ips.data]
        }));
      })
      .catch(err => console.log(err));

    axios
      .get("/api/carrozas")
      .then(carrozasdb => {
        this.setState(prevState => ({
          carrozas: [...prevState.carrozas, ...carrozasdb.data]
        }));
      })
      .catch(err => console.log(err));

    axios
      .get("/api/ip/miip")
      .then(miip => {
        this.setState({
          miIp: miip.data
        });
      })
      .catch(err => console.log(err));
  }

  shouldRedirect() {
    for (var i = 0; i < this.state.ipRegistradas.length; i++) {
      if (this.state.ipRegistradas[i].ip === this.state.miIp) {
        this.setState({
          goToVotos: false
        });
      }
    }
  }

  votar(nom) {
    axios.post("/api/votos", { nombre: nom });
    axios.post("/api/ip");
  }

  render() {
    const { carrozas } = this.state;
    this.shouldRedirect();

    if (this.state.goToVotos === true) {
      return (
        <Container>
          <h3
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            Votá la mejor carroza...
          </h3>
          <ListGroup>
            <TransitionGroup className="carrozas">
              {carrozas.map(({ _id, nombre, curso }) => (
                <CSSTransition key={_id} timeout={500} classNames="fade">
                  <ListGroupItem
                    style={{
                      display: "flex",
                      justifyContent: "spaceAround"
                    }}
                  >
                    <Button
                      className="votar-btn"
                      color="primary"
                      size="sm"
                      onClick={() => {
                        this.votar(nombre);
                        this.props.history.push("/votoexitoso");
                      }}
                    >
                      Votar
                    </Button>
                    "{nombre}"
                    <p
                      style={{
                        marginLeft: "5rem"
                      }}
                    >
                      {curso}
                    </p>
                  </ListGroupItem>
                </CSSTransition>
              ))}
            </TransitionGroup>
          </ListGroup>
        </Container>
      );
    } else {
      return <Redirect to="votoexitoso" />;
    }
  }
}

export default Votos;
    
asked by facundo rotger 22.08.2018 в 19:58
source

0 answers