登录页面的本地身份验证

时间:2020-07-07 14:15:29

标签: javascript node.js mongodb passport.js

因此,我正在开发一个编码网站,在该网站上,用户需要登录,然后成功登录,他将被定向到另一个页面,需要在该页面上键入所询问问题的代码。

这就是我的登录页面的样子

<!DOCTYPE html>
<meta charset = "UTF-8" />
<head>
    <title>SIGN IN PAGE</title>
    
    
</head>
<body>
  
<div id="login-box">
    
  <div class="left">
      
    <h1>LOGIN</h1>

    <form id="new_form">
    <input type="text" name="name" id = "name" placeholder="Name" required/>
    <br/>
    <input style="text-decoration:none" type="text" name="email" placeholder="E-mail" id = "email" required/>
    <br/>
    <input type="password" name="password" placeholder="Password" id = "password" required/>
    <br/>
      
    <button type = "submit" id = "submitbtn" style="width: 120px; height: 30px; background:#16a085;"><!---<a href="/" style="text-decoration: none;">---> LOGIN</a></button>
  </form> 
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){
            $("#new_form").submit(function(){
                var name = $("#name").val();
                var email = $("#email").val();
                var password = $("#password").val();
                $.ajax({
                    url: "http://localhost:8080/login_info/",
                    type:"POST",
                    data: {"name": name,"email":email,"password":password},
                    success:function(response){
                      alert("Redirecting to main page");
                      
                        console.log(response);
                        try{
                            var resp = JSON.parse(response);
                            
                            if(resp.status=="ok"){
                                //alert("Data sent");
                                if(!name || !email || !password)
                                {
                                  alert("Please enter all the fields");
                                }
                                else{
                                window.location="http://localhost:8080";
                                }
                            }
                            else
                            {
                                alert("Something went wrong\nError:"+resp.msg);
                               
                            }
                        }catch(err){
                            alert("Invalid Response Got From Server");
                        }
                        //console.log(response);
                    },
                    error:function(err,xhr,msg){
                        console.log(msg);
                        
                    }
                });
                return false;
            })
        })


</script>

</body>
</html>

我的主编码页面看起来像:-

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>CODE TEST</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>

<body>
    <div class="container">
        <div class="question">
            <h2><strong>QUESTION 01:</strong></h2>
            Find the maximum number in an array of integers.
            <br/> For example, in the array [1, -3, 5], the maximum number is 5.
            <br/>
            <br/>
            <br/>
            <br/>
            <br/>
            <br/>
            <h2>OUTPUT</h2>
            <textarea rows="15" cols="60" id="results" style="background-color: black;color: white;"  readonly></textarea>
        </div>
        <div class="code-area">
            <select id="language">
                <option value="c" selected>C</option>
                <option value="c++">C++</option>
            </select>

            <textarea rows="20" class="input" id="code" name="codearea" style="background-color: black;color: white;" autofocus></textarea>
            <br/><br/>
            <button id="submitBtn">SUBMIT</button>
            <br/><br/>
            
        </div>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script>
        $(document).ready(function(){
            $("#submitBtn").click(function(){
                var code = $("#code").val();
                var lang = $("#language").val();
                $.ajax({
                    url: "http://localhost:8080/codetest/",
                    type:"POST",
                    data: {"code": code,"lang":lang},
                    success:function(response){
                        console.log(response);
                        try{
                            var resp = JSON.parse(response);
                            if(resp.status=="ok"){
                                alert("Compiled Successfully");
                                $("#results").val(resp.result);

                            }
                            else
                            {
                                alert("Error for the above code is \n:");
                                var error_message = resp.msg;
                                var str_pos = error_message.indexOf("input_code");
                                if (str_pos > -1)
                                {
                                    
                                    var replaced_string = error_message.replace(/input_code.c.......|Error.*/gm,'');
                                 
                                    $("#results").val(replaced_string);

                                }
                                else{
                                    alert("Not found");

                                }
                                
                            }
                        }catch(err){
                            alert("Invalid Response Got From Server");
                        }
                        //console.log(response);
                    },
                    error:function(err,xhr,msg){
                        console.log(msg);
                        $("#results").val(msg);
                        alert("Network Issue");
                    }
                });
            })
        })
    </script>
    <script>
        
    </script>
</body>

</html>

和Node.js文件,该文件从两个页面获取输入并将其存储在mongodb中,还编译并抛出输入的代码的输出。

这是Node.js文件:-


const bodyParser = require('body-parser');
const cors = require('cors');
const exec = require('child_process').execSync;
const express = require('express');
var MongoClient = require('mongodb').MongoClient;


const expressSession = require('express-session')({
  secret: 'secret',
  resave: false,
  saveUninitialized: false
});



var url = "mongodb://localhost:27017/";



var PORT = process.env.PORT || 8080;
const mongoose = require('mongoose');
const passport = require('passport');
const fs = require('fs');
const path = require('path');

const router = express.Router();

const app = express();  
const CODE_FOLDER = "";

function login_info(req,res){
  
  let name = req.body["name"];
  let email = req.body["email"];
  let password = req.body["password"];

   MongoClient.connect(url,{ useNewUrlParser: true, useUnifiedTopology: true }, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var myobj = { name: name, email: email,password: password };
  dbo.collection("login_info").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log("document inserted");
    db.close();

    
  });
  return res.send(JSON.stringify({"status":"ok"}));
});
  
}


function testCode(req, res) {
  let code = req.body["code"];

  let option_selected = req.body["lang"];
  console.log(option_selected);

  if(option_selected == "c++")
  {

                      try {
                        fs.writeFileSync(path.join(__dirname, CODE_FOLDER, "input_code.cpp"), decodeURIComponent(code));
                        const proc = exec("g++ input_code.cpp -o input_code && ./input_code");
                        //const proc1 = exec("./a.out")
                        const results = proc.toString();

                        return res.send(JSON.stringify({"status":"ok","result":results}));
                      } 
                      catch (err) {
                        console.log("An error occurred");
                        console.log(err);
                        var error1 = err.toString();
                        console.log("Here is the error");
                        console.log(error1);
                        return res.send(JSON.stringify({"status":"FATAL_ERROR","msg":err.toString()}));
                      }
}
if(option_selected == "c")
{
                      try {
                        fs.writeFileSync(path.join(__dirname, CODE_FOLDER, "input_code.c"), code);
                        const proc = exec("gcc input_code.c -o input_code && ./input_code");
                        const results = proc.toString();

                        return res.send(JSON.stringify({"status":"ok","result":results}));
                      } 
                      catch (err) {
                        console.log("An error occurred");
                        console.log(err);

                        return res.send(JSON.stringify({"status":"FATAL_ERROR","msg":err.toString()}));
                      }
}

}

app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({extended : false}));
app.use(passport.initialize());
app.use(passport.session());

app.get('/',(req, res) => {
  res.sendFile(path.join(__dirname + '/page02.html'));
});

app.get('/login',(req,res)=>{
  res.sendFile(path.join(__dirname + '/page01.html'));
});

app.post('/codetest/', testCode);
app.post('/login_info/',login_info);



app.listen(PORT, () =>
  console.log(`Listening on port.`),);

所以我的登录页面的网址是:-http:// localhost:8080 / login

,主编码页面的网址是:-http:// localhost:8080

因此,现在任何用户都可以在不登录的情况下查看我的主编码页面,因此我需要防止这种情况的发生并显示一条消息,提示您必须登录。

有什么办法,我只能让用户在登录页面中输入自己的详细信息时才能看到编码页面。

预先感谢

1 个答案:

答案 0 :(得分:-1)

登录后,您必须生成身份验证令牌并将该令牌保存在cookie中。每当任何用户直接进入该页面时,只需检查cookie是否存在或未过期。如果一切正常,则允许访问该页面,否则重定向到登录页面。这就是检查流程。您可以将JWT用作身份验证令牌