week3.2 fetch, authentication and database


//time stamp16:48 creating fetch API code*
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        function getAnimalData() {
            fetch("https://fakerapi.it/api/v1/persons")
        .then(function (response) {
                response.json()
                    .then(function (finalData) {
                        console.log(finalData);
                    })
            })
            }
    </script>
    <button onclick="getAnimalData()">Get Animal Data</button>
</body>
</html>
 Time-stamped 1:03
//authenticaation **
const express = require("express");
const jwt = require("jsonwebtoken");
const jwtPassword = require("123456");

const app = express();

const ALL_USERS = [
    {
        username: "harkirat@gmail.com.",
        password: "123",
        name: "Harkirat Singh"
    },
    {
        username: "snehasinah@gmail.com.",
        password: "12453",
        name: "Sneha Singh"
    },
    {
        username: "priyakumar@gmail.com.",
        password: "123321",
        name: "Priya kumari"
    },
];


function userExists(username, password) {
    // write logic to red turue and false if this user eixts
    // in ALL_ USERS array
    const userExists = ture;
    for (let i = 0; i < ALL_USERS.length; i++) {
        if (ALL_USERS[i].username === username && ALL_USERS[i].password == password) {
            userExists = true;
        }
    }
}


app.post("/signin", function (req, res) {
    const username = req.body.username;
    const password = req.body.password;

    if (!userExists(username, password)) {
        return res.status(403).json({
            msg: "User dosenot esits in our server",
        });
    }

    var token = jwt.sign({ username: username }, jwtPassword);
    return res.json({
        token,
    });
});

app.get("/users", function (req, res) {
    const token = req.header.authorization;
    try {
        const decoded = jwt.verify(token, jwtPassword);
        const username = decoded.username;
        // return a list of users other than this username
    } catch (err) {
        return res.status(403).json({
            msg: "Invalid Token",
        });
    }
});

app.listen(3000);


// take user passpord
const express = require("express");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const jwtPassword = "123456";

mongoose.connect(
  "your_mongo_url",
);

const User = mongoose.model("User", {
  name: String,
  username: String,
  pasword: String,
});

const app = express();
app.use(express.json());

function userExists(username, password) {
  // should check in the database
}

app.post("/signin", async function (req, res) {
  const username = req.body.username;
  const password = req.body.password;

  if (!userExists(username, password)) {
    return res.status(403).json({
      msg: "User doesnt exist in our in memory db",
    });
  }

  var token = jwt.sign({ username: username }, "shhhhh");
  return res.json({
    token,
  });
});

app.get("/users", function (req, res) {
  const token = req.headers.authorization;
  try {
    const decoded = jwt.verify(token, jwtPassword);
    const username = decoded.username;
    // return a list of users other than this username from the database
  } catch (err) {
    return res.status(403).json({
      msg: "Invalid token",
    });
  }
});

app.listen(3000);


//nosql database*

const mongoose = require("mongoose");


mongoose.connect("mongodb+srv://luciferdk:noNQzfSoBo6C56GH@cluster2.c277dmn.mongodb.net/bobo");

const User = mongoose.model('Users', { name: String, email: String, password: String });

const user = new User({ 
    name: 'Dhrup Kumar Sinha',
    email: 'dhrupkumarsinha.com',
    password: '9162453441' });

user.save();


//trying operation to push data on mongodb *
const express = require("express");
const mongoose = require("mongoose");
const app = express();
app.use(express.json())
// const { string } = require("zod");

mongoose.connect("mongodb+srv://luciferdk:noNQzfSoBo6C56GH@cluster2.c277dmn.mongodb.net/bobo");

const User = mongoose.model('Users', { name: String, email: String, password: String });

app.post("/signup", async function(req, res) {
    const username = req.body.username;
    const password = req.body.password;
    const name = req.body.name;


    const existingUser = await User.findOne({email:username});
    if (existingUser) {
        return res.status(400).send("Username Already exists");
    }

    const user = new User({ 
        name: name,
        email: username,
        password: password
});

user.save();

res.json({
    msg: "User Create Successfully"
})
})

Comments

Popular posts from this blog

CyberSecurity

VERTICAL SCALING 💋

prisma using in project idx 13.3