---
# System prepended metadata

title: Ambiente NodeJs
tags: [Qintess]

---

# Ambiente NodeJs


 
### C:\Users\edson\projeto\backnode

### C:\Users\edson\projeto\frontreact

### Esteira 
 

### começo projeto até o test


```cmd=

npm init -y

#gera o package.json

```


### NVM install 

### Com certeza script do testes ...

```cmd=
mkdir C:\Users\edson\projetofinal\backnode\Model
mkdir  C:\Users\edson\projetofinal\backnode\DataBase
mkdir  C:\Users\edson\projetofinal\backnode\Tests


code .


```
### tree
```cmd=
C:.
├───DataBase
├───Model
└───Tests
```



### Como eu faço template
```cmd=
--java
mkdir mkdir C:\Users\edson\projeto\src\main

mkdir C:\Users\edson\projeto\src\test

```


![image](https://hackmd.io/_uploads/HyKpNyvUC.png)



### code .

```cmd=

server.js
ou
app.js

Model
 Users.js
 
Database
 Banco.js
 
 

server.js
app.js


```
 


### Fase do banco (repository _ Database _ DAO)

```cmd=
const mongoose = require('mongoose');

//aqui da erro
//deprecretade ... Pode ser atualizado ... versões 
//Lint (programa configura o grau do nível código)
//Lint 9.0  (Correr atrás como eles querem)

mongoose.connect('mongodb://localhost:27017/myDatabase', 
              {userNewUrlParser:true});
        
mongoose.connection.once('once', ()=>{ 
    console.log('Mongoose Conectado ao banco')
})

module.exports = mongoose;
```



 


### No Projeto
### Database.js
```nodejs=
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase', 
              {userNewUrlParser:true});
        
mongoose.connection.once('once', ()=>{ 
    console.log('Mongoose Conectado ao banco')
})

module.exports = mongoose;
```

### Model/Users.js
```nodejs=
const mongoose= require('mongoose');

const userSchema= new mongoose.Schema({
  name : {type : String },
  status:{type: String, default: 'ACTIVATE'},
  email:{type: String},
  password:{type: String},
  token : {type: String}
   
});

const Users =mongoose.model('users', userSchema)

module.exports = Users
```



## Server.js

```nodejs=

const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');  
const jwt = require('jsonwebtoken');
const Users = require('./Model/Users');
const PORT = 3015;

require('./DataBase/Banco')
 
const app =  express();
 
app.use(bodyParser.json());
 
app.post('/api/users/save', async (req, res)=>{
 try{
   let name= req.body.name;
   let password= req.body.password;
   let email = req.body.email;
   const hashPassword = await bcrypt.hash(password, 8);
    let users = new Users({
        name,
        email,
        password:hashPassword,
        status:'ACTIVATE',
        token:''
    });
   let respUser= await users.save();
   res.status(200).send({message:"Users Created",'users': respUser});
 }catch(error){
    res.status(500).send({message:"Users Created Error"})
 }

});



app.listen(PORT,()=>{
  console.log('listener port ${PORT}')
});

```
 

##  Executar

### npm start
### ou
### node server.js




### Programando 

```cmd=
app.post('/api/users/login', async (req, res)=>{
    try{
        // resgate
        //buscar no banco ...
        //criptografia (comparar)
        // token : jwt 
        // atualizar o status : 'LOGIN' e se 
        // gravar o token
        gerar message('user login'
    }catch(error){

    }
});

```



```login=

app.post('/api/users/login', async (req, res)=>{
    try{
       email = req.body.email;
       password = req.body.password;
       //buscando do banco (password) o users (criptogrado)
       const users = await Users.findOne({'email': email});
         
        //se estiver errado
        if (!users){
          throw new Error('error', 'Error no FindOne');
        }
      
        const isLogin = await bcrypt.compare(password, users.password );

         if (!isLogin){
            throw new Error('error', 'Error na Criptografia');
        }
    
        const tokenGenerated= jwt.sign(
            {userId: users._id, email: users.email  },
            chaveSecreta,
            {expiresIn: '1h'}
        )
        //ultima fase (atualizar os dados na collection)
        users.status='LOGIN'
        users.token=tokenGenerated
        let respUser= await users.save();
        res.status(200).send({message:"Users Login",
            'users': respUser});
         

    }catch(error){
        res.status(500).send({'message':error.message});
    }
});
```



### Rodando 
post /api/users/login

{
"email":"belem@gmail.com",
"password":"12345678"
}


 


### Versão Completa  Final 

```nodejs=
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');  
const jwt = require('jsonwebtoken');
const Users = require('./Model/Users');
const PORT = 3015;
const chaveSecreta = 'minha palavra secreta DEUS';
require('./DataBase/Banco')
 
const app =  express();
 
app.use(bodyParser.json());
 
app.post('/api/users/save', async (req, res)=>{
 try{
   let name= req.body.name;
   let password= req.body.password;
   let email = req.body.email;
   //validate ... (resgate ....)
   const hashPassword = await bcrypt.hash(password, 8);
    let users = new Users({
        name,
        email,
        password:hashPassword,
        status:'ACTIVATE',
        token:''
    });
   let respUser= await users.save();
   res.status(200).send({message:"Users Created"});
 }catch(error){
    res.status(500).send({message:"Users Created Error"})
 }

});
 
app.post('/api/users/login', async (req, res)=>{
    try{
       email = req.body.email;
       password = req.body.password;
       const users = await Users.findOne({'email': email});
        if (!users){
            throw new Error('Error no Login');
        }
        const isLogin = await bcrypt.compare(password, users.password );
         if (!isLogin){
            throw new Error('Error na Criptografia');
        }
        const tokenGenerated= jwt.sign(
            {userId: users._id, email: users.email  },
            chaveSecreta,
            {expiresIn: '1h'}
        )
        users.status='LOGIN'
        users.token=tokenGenerated;
        let respUser= await users.save();
        res.status(200).send({message:"Users Login","token":users.token});
         

    }catch(err){
        res.status(500).send({'message': err.message} );
    }
});


app.post('/api/users/logout', async (req, res)=>{
    try{
       const myToken= req.body.token;
       const payload=  jwt.verify(myToken, chaveSecreta);
       const users = await Users.findById(payload.userId);
       if (!users){
         throw new Error('Error de autenticacao de Token');
       }
        users.status='OFFLINE';
        users.token='';
        await users.save();
        res.status(200).send({'message':'User Logout'});
       }catch(err){
        res.status(500).send({'message': err.message} );
    }
});



app.listen(PORT,()=>{
  console.log(`listener port: ${PORT}`)
});
```

### Criar test ...
### front
### esteira ...


```cmd=
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase', 
              {useNewUrlParser:true});
        
mongoose.connection.once('open', ()=>{ 
    console.log('Mongoose Conectado ao banco')
})

module.exports = mongoose;
```




### Users.js


```nodejs=
const mongoose= require('mongoose');

const userSchema= new mongoose.Schema({
  name : {type : String },
  status:{type: String, default: 'ACTIVATE'},
  email:{type: String},
  password:{type: String},
  token : {type: String}
   
});

const Users =mongoose.model('users', userSchema)

module.exports = Users
```




## Gravação Funcionando 

![image](https://hackmd.io/_uploads/B13oZJwLC.png)

.
.
.

![image](https://hackmd.io/_uploads/BkY5-1w8A.png)

.
.
.
### Obs na Gravação o token não é gerado o padrão de senha é Bcryptjs
 

 
.
.

## Login gerando o Token (reparar na base de dados o token) e a mudança do status do usuario logado

![image](https://hackmd.io/_uploads/rJphlyDIR.png)


.
.
.

## Quando Logamos o Token é preenchido 

![image](https://hackmd.io/_uploads/SyVXzJwI0.png)



## Quando Executamos o Logout o Token é retirado e Status também altera



![image](https://hackmd.io/_uploads/r1AjzyPIR.png)


![image](https://hackmd.io/_uploads/ByHAGyPLR.png)

