MERN app doesn't function correctly on heroku netlify but works properly on localhost - authentication

I'm having a hard time trying to fix my login page
I've provided a very short youtube video on what is the problem that I encountered.
Youtube Link: https://youtu.be/lpyJo6tmiRs
It works properly on localhost but breaks when I deploy to herkou & netlify.
Register function also works properly
I provided everything here and also hidden some important info like mongodb user and passwords.
Website Link
https://incomparable-speculoos-abdd5f.netlify.app/
Login Page
import React, { useState, useEffect } from 'react'
import { useNavigate } from "react-router-dom"
import Axios from 'axios'
import './login.css'
import Register from '../register/register'
const Login = () => {
const navigate = useNavigate();
const [style, setStyle] = useState('hidden')
const [border, setBorder] = useState(false)
const [email, setEmail] = useState('')
const [password, setPass] = useState('')
const [errMsg, setErr] = useState('')
Axios.defaults.withCredentials = true;
const handleEmail = (e) => {
setEmail(e.target.value)
}
const handlePassword = (e) => {
setPass(e.target.value)
}
const show = () => [
setStyle('registerParent')
]
const hide = () => {
setStyle('hidden')
}
const reloadA = () => {
window.location.reload(false);
}
// FUNCTION WHEN LOGIN IS CLICKED
const login = () => {
Axios.post('https://votereact-app.herokuapp.com/login',
{email: email,
password: password,
}).then((response) => {
// CHECKS IF THERE IS A MESSAGE FROM THE BACKEND (MEANS THERE IS A PROBLEM IN THE LOGIN)
if (response.data.message) {
setErr(response.data.message)
setBorder(true)
} else {
// NAVIGATES TO /home ROUTE OF THERE IS NO MESSAGE (/route redirects to privateRoute)
setErr("Logged in")
setBorder(false)
navigate('/home', {replace: true})
}
})
}
return (
<>
<div className="loginParent">
<div className="loginContainer">
<h1 className="vote-login">VoteReact</h1>
<div className="loginBox">
<div className="inputs-parent">
<input type="text" style={{border: border ? '1px solid #e2252b' : '1px solid #1B74E4'}} placeholder="Email" className="email-input" onChange={handleEmail}></input>
<input type="password" style={{border: border ? '1px solid #e2252b' : '1px solid #1B74E4'}}placeholder="Password" className="password-input" onChange={handlePassword}></input>
<p className="errMsg">{errMsg}</p>
</div>
<button className="loginButton" onClick={login}>Log in</button> {/* LOGIN BUTTON */}
<p className="forgot">Forgot Password?</p>
<button className="signup" onClick={show}>Sign up</button>
</div>
</div>
</div>
<Register styleName={style.toString()} close={() => hide()} load={() =>reloadA()}/>
</>
)
}
export default Login
BACK END CODE
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose")
const app = express();
const bcrypt = require("bcryptjs")
const saltRounds = 10;
const bodyParser = require("body-parser")
const cookieParser = require("cookie-parser")
const session = require("express-session")
const voterModel = require('./modules/voters.js')
const presidentModel = require('./modules/president.js')
const viceModel = require('./modules/vice.js')
const treasurerModel = require('./modules/treasurer.js')
app.use(express.json());
require('dotenv').config();
app.use(cors({credentials: true, origin: 'https://incomparable-speculoos-abdd5f.netlify.app'}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(session({
key: "userId",
secret: "hidden",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 60000
}
}))
mongoose.connect("hidden",
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
// GET THE SESSION AND CHECK IF IT DOES EXIST OR NO
//IF YES THEN LOGGEDIN: TRUE ELSE, FALSE
// --- HERE IS WHERE I ENCOUNTER PROBLEM, IT SHOULD RETURN TRUE AFTER I LOG IN BUT STILL RETURNS FALSE ---
app.get('/login', async (req, res) => {
if (req.session.voter) {
res.send({loggedIn: true})
} else {
res.send({loggedIn: false})
}
})
app.post('/login', async (req, res) => {
const email = req.body.email;
const password = req.body.password;
// CHECKS IF USER EMAIL EXISTS
voterModel.find({email: email}, {"email":1}, async (err, result) => {
if (err) {
console.log(err)
} else {
if(result.length > 0) {
// COMPARES PASSWORD IF IT IS CORRECT
const user = await voterModel.findOne({email: email})
const pass = await user.comparePassword(password)
if (pass) {
// SAVE THE SESSION IF PASS IS CORRECT
req.session.voter = result
var oneWeek = 60 * 60 * 24; //1 week
req.session.voter.expires = new Date(Date.now() + oneWeek);
req.session.voter.maxAge = oneWeek;
console.log(req.session.voter)
res.send(result)
} else {
console.log("NOT LOGGED IN")
res.send({ message: 'Invalid email or password!'})
}
} else {
console.log("NOT LOGGED IN")
res.send({ message: 'Invalid email or password!'})
}
}
})
})
app.post('/register', async (req, res) => {
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;
// HASING PASSWORD
bcrypt.hash(password, saltRounds, async (err, hash) => {
if (err) {
console.log(err)
}
// INSERTING VALUES
const voters = await voterModel({email: email, username: username, password: hash, status: false})
// CHECKS IF EMAIL IS IN USE
const isNewEmail = await voterModel.isThisEmailInUse(email)
if (!isNewEmail) return res.send({ message: 'This email is already taken!'})
// SAVES THE INSERT DATA FOR VOTERS
await voters.save()
res.send({success: true})
})
})
app.post('/logout', (req, res) => {
if(req.session.voter) {
req.session.voter = null;
req.session.destroy();
}
})
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log('Running on port successfuly')
})
Private Route to Home
import React, { useState, useEffect } from 'react'
import { useNavigate } from "react-router-dom"
import Axios from 'axios'
import Home from "./home/home.js"
const PrivateRoute = () => {
Axios.defaults.withCredentials = true;
const navigate = useNavigate();
const [loggedIn, setLoggedIn] = useState(false);
useEffect(()=> {
// GET DATA FROM axios.get(/login) on backend
Axios.get("https://votereact-app.herokuapp.com/login").then((response) => {
if (response.data.loggedIn === true) {
setLoggedIn(true);
console.log(response)
} else {
navigate("/" , {replace: true})
console.log(response)
}
})
},[])
// WHILE CHECKING IF Logged in or not
if (!loggedIn) {
return (
<>
Loading...
</>
)
}
// Redirects to real home page if user is logged in
return (
<>
<Home/>
</>
)
}
export default PrivateRoute

Related

How to access request data in layouts and pages in Qwik City

I'm creating an application Qwik and Qwik City.
I want to show something in my layout, only if it's the home page.
This is my layout.jsx:
const Layout = component$((props) => {
// console.log(props); // I don't see anything related to request
const isHomePage = true; // how can I know I'm inside the home page?
return <>
{isHomePage && <TopBar />}
</>
})
import { component$, Slot } from "#builder.io/qwik";
import { loader$, useLocation } from "#builder.io/qwik-city";
export const useUser = loader$(async ({ fail }) => {
try {
const res = await fetch("https://api.github.com/users/harshmangalam");
const user = await res.json();
return {
user,
};
} catch (error) {
return fail(500, {
error: "Something went wrong",
});
}
});
export default component$(() => {
const user = useUser();
const {
url: { pathname },
} = useLocation();
const isHomePage = pathname === "/";
return (
<div>
{isHomePage && <pre>{JSON.stringify(user.value, null, 4)}</pre>}
<Slot />
</div>
);
});

{message: "Auth failed", success: false} message : "Auth failed" success : false

I'm following a Udemy MERN stack course and I am quite a beginner ,I've got stuck in middle of a problem. There is no point in completing it before solving this problem. The problem is with the concept of authorization and concept of protected roles, so when the user is logged in to the interface we have to check whether is user is authorized or not. I followed the instructer end to end exactly according to the instruction and his code.
Using jsonwebtoken, verifiationn is conducted on the basis of encrypted token. whos key is stored in .env file
The output of the network dev tool in the browser :
enter image description here
I have no idea what causes this.
server.js
const express = require("express");
const app = express();
require("dotenv").config();
const dbConfig = require("./config/dbConfig.js");
app.use(express.json());
const userRoute = require("./routes/userRoute");
app.use("/api/user", userRoute);
const port = process.env.PORT || 5000;
console.log(process.env.MONGO_URL);
app.listen(port, () => console.log(`Node server started at port ${port}`));
.env
MONGO_URL = 'mongodb+srv://users:root#cluster0.vnoq4f8.mongodb.net/ngodatabase';
JWT_SECRET = 'ngo_project';
Home.js
import React, { useEffect } from "react";
import axios from "axios";
function Home() {
const getData = async () => {
try {
const response = await axios.post(
"/api/user/get-user-info-by-id",
{},
{
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
}, // headers
}
);
console.log(response.data);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
getData();
}, []);
return <div>Home</div>;
}
export default Home;
authmiddleware.js
const jwt = require("jsonwebtoken");
module.exports = async (req, res, next) => {
try {
const token = req.headers["authorization"].split(" ")[1];
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
return res.status(401).send({
message: "Auth failed",
success: false,
});
} else {
req.body.userId = decoded.id;
next();
}
});
} catch (error) {
return res.status(401).send({
message: "Auth failed",
success: false,
});
}
};
userRoute.js
const express = require("express");
const router = express.Router();
const User = require("../models/userModel");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const authmiddleware = require("../middlewares/authmiddleware");
router.post("/register", async (req, res) => {
try {
const userExist = await User.findOne({ email: req.body.email });
if (userExist) {
return res
.status(200)
.send({ message: "User already exists", success: false });
}
const password = req.body.password;
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
req.body.password = hashedPassword;
const newuser = new User(req.body);
await newuser.save();
res
.status(200)
.send({ message: "User created successfully", success: true });
} catch (error) {
console.log(error);
res
.status(500)
.send({ message: "Error creating user", success: false, error });
}
});
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
if (!user) {
return res
.status(200)
.send({ message: "User does not exist", success: false });
}
const isMatch = await bcrypt.compare(req.body.password, user.password);
if (!isMatch) {
return res
.status(200)
.send({ message: "Password is incorrect", success: false });
} else {
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: "1d",
});
res
.status(200)
.send({ message: "login successful", success: true, data: token });
}
} catch (error) {
console.log(error);
res
.status(500)
.send({ message: "Error logging in", success: false, error });
}
});
router.post("/get-user-info-by-id", authmiddleware, async (req, res) => {
try {
const user = await User.findOne({ _id: req.body.userId });
if (!user) {
return res
.status(200)
.send({ message: "User does not exist", success: false });
} else {
res.status(200).send({
success: true,
data: {
name: user.name,
email: user.email,
},
});
}
} catch (error) {
res.status(500).send({
message: "Error getting user information",
success: false,
error,
});
}
});
module.exports = router;
package.json
jsonwebtoken in package
Login.js
import { Button, Form, Input } from "antd";
import React from "react";
import toast from "react-hot-toast";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
function Login() {
const navigate = useNavigate();
const onFinish = async (values) => {
try {
const response = await axios.post("/api/user/login", values);
if (response.data.success) {
toast.success(response.data.message);
toast("Redirecting to home page");
localStorage.setItem("token", response.data.data);
navigate("/");
} else {
toast.error(response.data.message);
}
} catch (error) {
toast.error("Something went wrong");
}
};
return (
<div className="authentication">
<div className="authentication-form card p-4">
<h1 className="card-title">Welcome Back</h1>
<Form layout="vertical" onFinish={onFinish}>
<Form.Item label="Email" name="email">
<Input placeholder="Email"></Input>
</Form.Item>
<Form.Item label="Password" name="password">
<Input placeholder="Password" type="password"></Input>
</Form.Item>
<Button className="primary-button my-2" htmlType="submit">
LOGIN
</Button>
<Link to="/register" className="anchor mt-2">
CLICK HERE TO REGISTER
</Link>
</Form>
</div>
</div>
);
}
export default Login;
Register.js
import { Button, Form, Input } from "antd";
import React from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
import toast from "react-hot-toast";
function Register() {
const navigate = useNavigate();
const onFinish = async (values) => {
try {
const response = await axios.post("/api/user/register", values);
if (response.data.success) {
toast.success(response.data.message);
toast("Redirecting to login page");
navigate("/login");
} else {
toast.error(response.data.message);
}
} catch (error) {
toast.error("Something went wrong");
}
};
return (
<div className="authentication">
<div className="authentication-form card p-4">
<h1 className="card-title">Nice to meet you</h1>
<Form layout="vertical" onFinish={onFinish}>
<Form.Item label="Name" name="name">
<Input type="text" placeholder="Name" name="name"></Input>
</Form.Item>
<Form.Item label="Email" name="email">
<Input type="email" placeholder="Email" name="email"></Input>
</Form.Item>
<Form.Item label="Password" name="password">
<Input
placeholder="Password"
name="password"
type="password"
></Input>
</Form.Item>
<Button
className="primary-button my-2"
htmlType="submit"
name="submit"
>
REGISTER
</Button>
<Link to="/Login" className="anchor mt-2">
CLICK HERE TO LOGIN
</Link>
</Form>
</div>
</div>
);
}
export default Register;
did you check if you already have the token in your storage ?
check using inspectElement, or try to print the token in authmiddleware.js
like:
const jwt = require("jsonwebtoken");
module.exports = async (req, res, next) => {
try {
const token = req.headers["authorization"].split(" ")[1];
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
console.log(token); //this line will print the token that given in your request
return res.status(401).send({
message: "Auth failed",
success: false,
});
} else {
req.body.userId = decoded.id;
next();
}
});
} catch (error) {
return res.status(401).send({
message: "Auth failed",
success: false,
});
}
};

Secure random number generation is not supported by this browser

I am trying to establish a peer-to-peer video connection between a web frontend and a react-native android smart tv app. I want to display the user's webcam video on the smart tv. I am using an express server for signaling:
const app = require("express")();
const server = require("http").createServer(app);
const cors = require("cors");
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: [ "GET", "POST" ]
}
});
app.use(cors());
const PORT = process.env.PORT || 8082;
//here we define the behaviour of the API Endpoints
app.get('/', (req, res) => {
res.send('Runnin');
});
app.post('/',(req,res) => {
const body = req.body;
res.send(body);
});
io.on("connection", (socket) => {
socket.emit("me", socket.id);
console.log(socket.id);
socket.on("disconnect", () => {
socket.broadcast.emit("callEnded")
});
socket.on("callUser", ({ userToCall, signalData, from, name }) => {
io.to(userToCall).emit("callUser", { signal: signalData, from, name });
});
socket.on("answerCall", (data) => {
io.to(data.to).emit("callAccepted", data.signal)
});
});
server.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
The signaling is working but as I am trying to display the video the following error is displayed:
[Link to screenshot of the error][1]
Code of the react-native Callscreen component:
import React, { useEffect, useState, useCallback, useContext } from 'react';
import { View, StyleSheet, Alert, Button, Text } from 'react-native';
import { RTCView } from 'react-native-webrtc';
import { SocketContext } from './Context';
import Callnotification from './Callnotifcation';
function CallScreen(props) {
const { callAccepted, userVideo, callEnded, me } = useContext(SocketContext);
return (
<>
{callAccepted && !callEnded && (
<View style={styles.root}>
<View style={[styles.videos, styles.remoteVideos]}>
<Text>Video of the caller</Text>
<RTCView streamURL={JSON.stringify(userVideo)} style={styles.remoteVideo} />
</View>
</View>
)
}
<View style={styles.root}>
<Callnotification />
<Text>{JSON.stringify(me)}</Text>
</View>
</>
);
}
Code of the Context.js connecting the react-native app to the signaling server:
import React, { createContext, useState, useRef, useEffect } from 'react';
import { io } from 'socket.io-client';
import Peer from 'simple-peer';
const SocketContext = createContext();
const socket = io('http://10.0.2.2:8082'); // use this to access via android emulator
//const socket = io('http://192.168.178.106:8082'); //use this to access via SmartTv Fire Tv Stick
const ContextProvider = ({ children }) => {
const [callAccepted, setCallAccepted] = useState(false);
const [callEnded, setCallEnded] = useState(false);
const [stream, setStream] = useState();
const [name, setName] = useState('');
const [call, setCall] = useState({});
const [me, setMe] = useState('');
const userVideo = useRef();
const connectionRef = useRef();
useEffect(() => {
socket.on('me', (id) => setMe(id));
socket.on('callUser', ({ from, name: callerName, signal }) => {
setCall({ isReceivingCall: true, from, name: callerName, signal });
});
}, []);
const answerCall = () => {
setCallAccepted(true);
const peer = new Peer({ initiator: false, trickle: false, stream });
peer.on('signal', (data) => {
socket.emit('answerCall', { signal: data, to: call.from });
});
peer.on('stream', (currentStream) => {
userVideo.current.srcObject = currentStream;
});
peer.signal(call.signal);
connectionRef.current = peer;
};
/* const callUser = (id) => {
const peer = new Peer({ initiator: true, trickle: false, stream });
peer.on('signal', (data) => {
socket.emit('callUser', { userToCall: id, signalData: data, from: me, name });
});
peer.on('stream', (currentStream) => {
userVideo.current.srcObject = currentStream;
});
socket.on('callAccepted', (signal) => {
setCallAccepted(true);
peer.signal(signal);
});
connectionRef.current = peer;
};*/
const leaveCall = () => {
setCallEnded(true);
connectionRef.current.destroy();
};
return (
<SocketContext.Provider value={{
call,
callAccepted,
setCallAccepted,
userVideo,
stream,
name,
setName,
callEnded,
me,
leaveCall,
answerCall,
}}
>
{children}
</SocketContext.Provider>
);
};
export { ContextProvider, SocketContext };
Code of the Context.js connecting the web react frontend to the signaling server:
import React, { createContext, useState, useRef, useEffect } from 'react';
import { io } from 'socket.io-client';
import Peer from 'simple-peer';
const SocketContext = createContext();
// const socket = io('http://localhost:5000');
const socket = io('http://localhost:8082');
const ContextProvider = ({ children }) => {
const [callAccepted, setCallAccepted] = useState(false);
const [callEnded, setCallEnded] = useState(false);
const [stream, setStream] = useState();
const [name, setName] = useState('');
const [call, setCall] = useState({});
const [me, setMe] = useState('');
const myVideo = useRef();
const userVideo = useRef();
const connectionRef = useRef();
useEffect(() => {
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then((currentStream) => {
setStream(currentStream);
myVideo.current.srcObject = currentStream;
});
socket.on('me', (id) => setMe(id));
socket.on('callUser', ({ from, name: callerName, signal }) => {
setCall({ isReceivingCall: true, from, name: callerName, signal });
});
}, []);
const answerCall = () => {
setCallAccepted(true);
const peer = new Peer({ initiator: false, trickle: false, stream });
peer.on('signal', (data) => {
socket.emit('answerCall', { signal: data, to: call.from });
});
peer.on('stream', (currentStream) => {
userVideo.current.srcObject = currentStream;
});
peer.signal(call.signal);
connectionRef.current = peer;
};
const callUser = (id) => {
const peer = new Peer({ initiator: true, trickle: false, stream });
peer.on('signal', (data) => {
socket.emit('callUser', { userToCall: id, signalData: data, from: me, name });
});
peer.on('stream', (currentStream) => {
userVideo.current.srcObject = currentStream;
});
socket.on('callAccepted', (signal) => {
setCallAccepted(true);
peer.signal(signal);
});
connectionRef.current = peer;
};
const leaveCall = () => {
setCallEnded(true);
connectionRef.current.destroy();
window.location.reload();
};
return (
<SocketContext.Provider value={{
call,
callAccepted,
myVideo,
userVideo,
stream,
name,
setName,
callEnded,
me,
callUser,
leaveCall,
answerCall,
}}
>
{children}
</SocketContext.Provider>
);
};
export { ContextProvider, SocketContext };
In my opinion the error lies in the RTCView of the Callscreen but i have no idea how to fix it. Your help is very much appreciated!
Thank you very much!
[1]: https://i.stack.imgur.com/YBh9P.jpg
The library that you are using is probably using the SubtleCrypto.generateKey function to generate shared secrets. This API is "only available in a secure context", which means that it can only be used if the page is served over HTTPS.
Serve your page over HTTPS, and the error should go away.

axios doesn't send post for Stripe

I have a problem with axios Post. I work on adding Stripe payment to my page, but i send me axios error 404.
Maybe somebody can help me, I stuck on it for week already and cant just solve it.
Here is the code:
import React from 'react'
import StripeCheckout from 'react-stripe-checkout';
import { useState, useEffect } from "react";
import { useNavigate } from 'react-router-dom';
import axios from "axios";
const Pay = () => {
const [stripeToken, setStripeToken] = useState(null)
const navigate = useNavigate()
const onToken = (token) => {
setStripeToken(token);
}
useEffect(() => {
const makeRequest = async () => {
try {
const res = await axios.post(
"http//:localhost:5001/api/checkout/payment",
{
tokenId: stripeToken.id,
amount: 6000,
});
console.log(res.data)
} catch (err) {
console.log(err)
}
};
stripeToken && makeRequest()
}, [stripeToken]);
return (
<div className='pay__div'>
{stripeToken ? (<span>Processing</span>) : (
<StripeCheckout
name="Kate store"
image=""
billingAddress
shippingAddress
description="Yout total is $60"
amount={2000}
token={onToken}
stripeKey={KEY}
>
<button>Pay</button>
</StripeCheckout>
)}
</div>
)
}
export default Pay
Thank you for your time.
Also here are stripe.js index.js pages from backend
stripe.js
const router = require("express").Router();
const stripe = require("stripe")(process.env.STRIPE_KEY);
router.post("/payment", (req, res) => {
stripe.charges.create({
sourse: req.body.tokenId,
amount: req.body.amount,
currency: "usd"
},
(stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).json(stripeErr);
} else {
res.status(200).json(stripeRes);
}
});
});
module.exports = router;
And index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const productRoute = require("./routes/product");
const cartRoute = require("./routes/cart");
const orderRoute = require("./routes/order");
const stripeRoute = require("./routes/stripe");
const cors = require("cors");
dotenv.config();
mongoose.connect(process.env.MONGO_URL)
.then(() => console.log("DB Connected Successfull!"))
.catch((err) => {
console.log(err);
})
app.use(cors());
app.use(express.json());
app.use("/api/user", userRoute);
app.use("/api/auth", authRoute);
app.use("/api/product", productRoute);
app.use("/api/cart", cartRoute);
app.use("/api/order", orderRoute);
app.use("/api/checkout", stripeRoute);
app.listen(process.env.PORT || 5001, () => {
console.log("Backend is running")
})
Had the same problem. Moved dotenv.config(); before const stripeRoute = require("./routes/stripe"); in index.js and worked.

node.js login not working with azure sql database

So I have an azure sql database and I got the register to work and add fields to the sql database just fine using node.js and react as my front end. I'm trying to get my login to work and I set it up the same and same on the frontend just like my register, but it keeps returning wrong username or password when it is correct. Could anyone help and tell me what I'm doing wrong?
const express = require("express");
const cors = require("cors");
const app = express();
app.use(express.json({
type: ['application/json', 'text/plain']
}));
app.use(cors());
const { Connection, Request, TYPES } = require("tedious");
// Create connection to database
const config = {
authentication: {
options: {
userName: "username", // update me
password: "password" // update me
},
type: "default"
},
server: "server.database.windows.net", // update me
options: {
database: "server", //update me
encrypt: true
}
};
const connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on("connect", err => {
if (err) {
console.error(err.message);
} else {
console.log("Server Running and Connected")
}
});
app.post("/register", (req, res)=> {
var sql = "INSERT dbo.userinfo(first_name, last_name, user_name, password, email) VALUES (#firstname, #lastname, #username, #password, #email)"
// Read all rows from table
const request = new Request(sql,
(err, result) => {
if (err) {
console.error(err.message);
} else {
console.log('worked');
}
}
);
request.addParameter('firstname', TYPES.NVarChar, req.body.firstname)
request.addParameter('lastname', TYPES.NVarChar, req.body.lastname)
request.addParameter('username', TYPES.NVarChar, req.body.username)
request.addParameter('password', TYPES.NVarChar,req.body.password)
request.addParameter('email', TYPES.NVarChar, req.body.email)
connection.execSql(request);
})
app.post('/login', (req, res)=>{
var sql = "SELECT * FROM dbo.userinfo WHERE user_name = #username AND password = #password"
const request = new Request(sql,
(err, result) => {
if (err) {
res.send({err: err})
}
if(result > 0){
res.send(result)
console.log("passed")
}
else{
res.send({message: "Wrong username/password combination"})
}
}
);
request.addParameter('username', TYPES.NVarChar, req.body.usernamelog)
request.addParameter('password', TYPES.NVarChar,req.body.passwordlog)
connection.execSql(request);
})
connection.connect();
app.listen(1433, () => {
console.log("running server");
});
FrontEnd
import React, {useState} from 'react';
import Axios from 'axios'
import { StyleSheet, Text, View, SafeAreaView, Modal, Button, TextInput } from 'react-native';
const App = () => {
const [modalVisible, setModalVisible] = useState(false);
const [modalVisible2, setModalVisible2] = useState(false);
const [firstnamereg, setfirstname] = useState('')
const [lastnamereg, setlastname] = useState('')
const [emailreg, setemail] = useState('')
const [usernamereg, setusername] = useState('')
const [passwordreg, setpassword] = useState('')
const [usernamelog, setusernamelog] = useState('')
const [passwordlog, setpasswordlog] = useState('')
const register = () => {
Axios.post('http://localhost:1433/register', {
firstname: firstnamereg,
lastname: lastnamereg,
username: usernamereg,
password: passwordreg,
email: emailreg,
}).then((response) => {
console.log(response);
});
};
const login = () => {
Axios.post('http://localhost:1433/login', {
username: usernamelog,
password: passwordlog,
}).then((response) => {
console.log(response);
});
};
<View>
<Text style={[styles.title]}>
Login to Account
</Text>
<TextInput
style={styles.input}
placeholder="Username"
keyboardType="string"
onChangeText={setusernamelog}
/>
<TextInput
style={styles.input}
placeholder="Password"
keyboardType="string"
onChangeText={setpasswordlog}
/>
<Button
title='Login'
onPress={login}
/>
enter image description here
I think you can simply check with the result parameter, instead of result.length
Example
app.post('/login', (req, res)=>{
var sql = "SELECT * FROM dbo.userinfo WHERE user_name = #username AND password = #password"
const request = new Request(sql,
(err, result) => {
if (err) {
res.send({err: err})
}
if(result > 0){
res.send(result)
console.log("passed")
}
else{
res.send({message: "Wrong username/password combination"})
}
}
);
request.addParameter('username', TYPES.NVarChar, req.body.username)
request.addParameter('password', TYPES.NVarChar,req.body.password)
connection.execSql(request);
})
Edit: Since in your frontend, you are passing the values as username and password in your post request. So in your backend, you must access it through req.body.username and req.body.password.