BackendStack21 / restana

Restana is a lightweight and fast Node.js framework for building RESTful APIs.
MIT License
467 stars 27 forks source link

How should i implement cusrf in restana #104

Closed junaidy-johm closed 4 years ago

junaidy-johm commented 4 years ago

This my code in server side

const service = require('restana')({
    disableResponseEvent: true
})
const cookieParser = require('cookie-parser')

const bodyParser = require('body-parser')
const parseForm = bodyParser.urlencoded({extended:false})
const csrf = require('csurf')

const csrfProtection = csrf({cookie: true})
//const invalid = require('./middlewares/invalidCsrf')
const cors = require('cors')
service.use(cookieParser())

service.use(cors({
    credentials: true, 
    origin: true,    
}))
service.use(bodyParser.json())
service.use(csrfProtection)

service.get('/form_login', (req, res) => {    
    res.send({csrfToken: req.csrfToken()})    
})

service.post('/process_login',parseForm, (req, res)=>{
    console.log(req)
    res.send({message: 'THIS IS GREAT'})
})
service.start(3000).then(() => console.log('USER service listening on 3000 port!'))

This my code in client side

import React, {useState, useContext, useEffect} from 'react';
import {Link, useHistory} from 'react-router-dom'
import M from 'materialize-css'

import axios from 'axios';

const Signin = ()=>{

    const [password, setPassword] = useState("")
    const [email, setEmail] = useState("")
    const [_csrf, set_Csrf] = useState("")

    useEffect(()=>{

            axios.get('http://localhost:3000/form_login', {
              })
              .then( (response) => {
                  console.log(response.data.csrfToken)
                set_Csrf(response.data.csrfToken)

              })
              .catch( (error) => {
                console.log(error);
              });

        // fetch("http://localhost:8080/service/form_login",{
        //     method:"get",
        //     //credentials: 'include',
        //     headers:{
        //         "Content-Type":"application/json",

        //     },

        // }).then(res=>res.json())
        // .then(response=>{
        //     set_Csrf(response.data.csrfToken)
        // }).catch(err=>{
        //     console.log(err)
        // })

    },[])

    const  PostData = async()=>{
        if(!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)){
            M.toast({html: "email tidak valid",classes:"#c62828 red darken-3"})
            return
        }

        //console.log(_csrf)
        //return;

       await fetch("http://localhost:3000/process_login",{

            credentials: 'same-origin',
            headers:{
                "Content-Type":"application/json",
                // "x-csrftoken": _csrf,
                // "x-csrf-token": _csrf,
                // "xsrf-token": _csrf,
                // "csrf-token": _csrf,
                "X-XSRF-TOKEN": _csrf
            },
            method:"POST",
            body:JSON.stringify({                
                password,
                email,
                _csrf
            })
        }).then(res=>res.json())
        .then(data=>{
           console.log("data: "+data.message)
           if(data.error){
            M.toast({html: data.error,classes:"#c62828 red darken-3"})
           }else{
               //localStorage.setItem("jwt",data.token)
               //localStorage.setItem("user",JSON.stringify(data.user))
            //    dispatch({type:"USER",payload:data.user})
            //    M.toast({html:"signedin success",classes:"#43a047 green darken-1"})
            //    history.push('/')
            }
        }).catch(err=>{
            console.log(err)
        })

    //     const data = {
    //         email: email,
    //         password: password,
    //         csrfToken: _csrf
    //     }
    //    await axios.post('http://localhost:8080/service/process_login', {
    //         data, 
    //         headers:{
    //                     "Content-Type":"application/json",
    //                     "x-csrftoken": _csrf,
    //                     "CSRF-Token": _csrf

    //                 },

    //     })
    //     .then( (response) => {
    //         console.log(response.data.csrfToken)
    //       set_Csrf(response.data.csrfToken)

    //     })
    //     .catch( (error) => {
    //       console.log(error);
    //     });
    }

    return (
        <div className="mycard">
          <div className="card auth-card input-field">
            <h2>InstaStock</h2>
            <input 
                type="text"
                value={_csrf} 
                onChange={(e)=>set_Csrf(e.target.value)}
                />

            <input
            type="text"
            placeholder="email"
            value = {email}
            onChange={(e)=>setEmail(e.target.value)}
            />

            <input
            type="password"
            placeholder="password"
            value = {password}
            onChange={(e)=>setPassword(e.target.value)}
            />

            <button className="btn waves-effect waves-light #42a5f5 blue lighten-1"
            onClick={()=>PostData()}
            >
                Login
            </button>
            <h5>
                <Link to="/signup">Dont have an account ?</Link>
            </h5>
            <h6>
                <Link to="/reset">Forgot password ?</Link>
            </h6>

        </div>
      </div>
    )
}

export default Signin

and the result is

code: 403
message: "invalid csrf token"

What should I do?