authentication with express, beginner

40
April 22, 2021, at 00:50 AM

App.js

//Importações
const express = require('express')
const app = express()
const path = require('path')
const db = require('./util/db')
var port = 3000
var bodyParser = require('body-parser')
const { reduce } = require('async')
var jsonParser = bodyParser.json()
app.use(express.static(path.join(__dirname, 'public'))); 
app.use(bodyParser())
//set provavelmente onde pega ar rotas (estudar)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/', (req, res, next)=>{
    res.status(200).send('home')
})
app.get('/login', (req, res)=>{
    res.status(200).render('login')
})
app.post('/login', (req, res)=>{
    db.query(`SELECT user_login, user_senha FROM dados_login`, (error, resultado)=>{
        if(error) return console.log(error)
            resultado.forEach(busca =>{
            if(busca.user_login == req.body.login && busca.user_senha == req.body.senha){
                res.json('OK')
            }else{
                return res.status(200).send('Not exist!')
            }
        })
    })
})

app.get('/listaUsuarios', (req, res)=>{
    db.query('SELECT user.user_id, user.name, user.firstname, user.phone, user.foragido, money.bank, money.wallet FROM vrp_user_identities user JOIN vrp_user_moneys money ON user.user_id = money.user_id', [], (error, resultado)=>{
        if(error){
            res.status(200).send(error)
        }
            if(error){
                res.status(200).send(error)
            }
            res.render('listaUsuarios', {listagem: resultado})
        })
})
app.get('/preenchimento/:id', (req, res)=>{
    db.query('SELECT user.user_id, user.name, user.firstname, user.phone, user.foragido, money.bank, money.wallet FROM vrp_user_identities user JOIN vrp_user_moneys money ON user.user_id = money.user_id WHERE user.user_id = ?', [req.params.id], (error, resultado)=>{
        if(error){
            res.status(200).send(error)
        }
        res.status(200).render('preenchimento', {listagemUsuario: resultado[0], status: 'OK'})
    })
})
app.post('/preenchimento/:id', (req, res)=>{
        db.query('UPDATE vrp_user_identities SET name = ?, firstname = ?, phone= ? WHERE user_id = ?', [req.body.nome, req.body.sobrenome, req.body.telefone, req.params.id], (errorUser, resultadoUser)=>{
            if(errorUser){
                res.status(200).send(errorUser)
            }
            db.query('UPDATE vrp_user_moneys SET wallet = ?, bank = ? WHERE user_id = ?',[req.body.carteira, req.body.banco, parseInt(req.params.id)], (errorDinheiro, resultadoDinheiro)=>{
                if(errorDinheiro){
                    console.log(errorDinheiro)
                }else{
                    res.status(200).redirect('/listaUsuarios')
                }
            })
        })
})
app.listen(port, () => {
    console.log(`http://localhost:${port}`)
  })

login.ejs

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <meta charset="UTF-8">
    <title>Home </title>
    <style>
        html,
        body {
            height: 100%;
        }
        body {
            display: flex;
            align-items: center;
        }
        #formlogin {
            background-color: blue;
            color: white;
            padding: 20px;
            border: 1px solid black;
            box-shadow: 3px 3px black;
            border-radius: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="justify-content-center align-items-center row">
            <div class="col-4">
                <form id="formlogin" method="post" action="/login">
                    <div class="text-center mb-2">
                        <h2>Tela de login</h2>
                    </div>
                    <div class="form-group">
                        <input id="login" type="text" placeholder="Informe seu Login" class="form-control" required />
                    </div>
                    <div class="form-group">
                        <input id="senha" type="password" placeholder="Informe sua senha" class="form-control" required />
                    </div>
                    <button id="btnlogar" class="btn btn-success btn-block btn-lg"
                        onclick="enviarDados()">Logar</button>
                </form>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
        integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
        integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
        crossorigin="anonymous"></script>
    <script>
        function enviarDados() {
            if ($('#login').val() == '' || $('#senha').val() == '') return
            $.ajax({
                type: 'POST',
                url: '/login',
                data: {
                    login: $('#login').val(),
                    senha: $('#senha').val()
                }, success: (resultado)=>{
                    if(resultado == 'OK'){
                        alert(resultado)
                        window.location.href = '/listaUsuarios'
                    }else{
                        return alert('Error!')
                    }
                    
                }
            })
        }
    </script>
</body>
</html>

Guys .. I'm new and I'm using this for testing purposes.

I know that the ideal is to work with tokens etc.

What I need is that ... The user will only be able to access the other links if he is authenticated!

The / login screen even works! However, if the user goes straight to the URL and adds the address, the system does not block it.

How can I make the system block if the user tries to access a link without going through login authentication? I tried using app.use () but being a layman, I didn't quite understand how I can fit into my project. Could you help me please?

Note: I'm a beginner

READ ALSO
Selecting second child div while hovering on first child div in makeStyles Material UI

Selecting second child div while hovering on first child div in makeStyles Material UI

I have a parent div and two child divs, I want to apply CSS to the second child div when I hover on the first child divThis is the structure of the render method

61
I want to split data from array()inside a html container and put it in a foreach loop with html [closed]

I want to split data from array()inside a html container and put it in a foreach loop with html [closed]

Want to improve this question? Add details and clarify the problem by editing this post

50
CSS animations not working with certain properties [duplicate]

CSS animations not working with certain properties [duplicate]

This might totally be a very stupid question, but I'm self-taught and I have a lot of questions

77
At what level in bridge pattern the inheritance to be broken into composition

At what level in bridge pattern the inheritance to be broken into composition

I have gone through theoretical concept of bridge pattern https://springframeworkguru/gang-of-four-design-patterns/bridge-pattern/

53