0% found this document useful (0 votes)
4 views

user authentication quizquest

Uploaded by

hasini.thota.04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

user authentication quizquest

Uploaded by

hasini.thota.04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

FRONTEND

C:\Users\hasin\Desktop\prog\MERN\quiz\FINAL\userauth\frontend\users-auth\src

app.js

import { Routes, Route } from 'react-router-dom'


import './App.css';
import Navbar from './components/Navbar'
import Home from './components/pages/Home'
import Login from './components/pages/Login'
import SignUp from './components/pages/Signup'
import Account from './components/pages/Account'

function App() {
const isUserSignedIn = !!localStorage.getItem('token')

return (
<div className="App">
<Navbar />
<Routes>
<Route path='/' element={<Home />} />
<Route path='/login' element={<Login />} />
<Route path='/signup' element={<SignUp />} />
{isUserSignedIn && <Route path='/account' element={<Account />} />}
</Routes>
</div>
);
}

export default App;

const express = require('express')


const mongoose = require('mongoose')
const cors = require('cors')
const bodyParser = require('body-parser')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const User = require('./models/userSchema')

const SECRET_KEY = 'super-secret-key'

// connect to express app


const app = express()

// connect to mongoDB
const dbURI = 'mongodb+srv://hasini21bce8857:Honey@[email protected]/
UserDB?retryWrites=true&w=majority'
mongoose
.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
app.listen(4001, () => {
console.log('Server connected to port 4001 and MongoDb')
})
})
.catch((error) => {
console.log('Unable to connect to Server and/or MongoDB', error)
})

// middleware
app.use(bodyParser.json())
app.use(cors())

BACKEND
C:\Users\hasin\Desktop\prog\MERN\quiz\FINAL\userauth\server
server.js

//Routes

// REGISTER
//POST REGISTER
app.post('/register', async (req, res) => {
try {
const { email, username, password } = req.body
const hashedPassword = await bcrypt.hash(password, 10)
const newUser = new User({ email, username, password: hashedPassword })
await newUser.save()
res.status(201).json({ message: 'User created successfully' })
} catch (error) {
res.status(500).json({ error: 'Error signing up' })
}
})

//GET Registered Users


app.get('/register', async (req, res) => {
try {
const users = await User.find()
res.status(201).json(users)
} catch (error) {
res.status(500).json({ error: 'Unable to get users' })
}
})

//LOGIN

app.post('/login', async (req, res) => {


try {
const { username, password } = req.body
const user = await User.findOne({ username })
if (!user) {
return res.status(401).json({ error: 'Invalid credentials'})
}
const isPasswordValid = await bcrypt.compare(password, user.password)
if(!isPasswordValid) {
return res.status(401).json({ error: 'Invalid credentials' })
}
const token = jwt.sign({ userId: user._id }, SECRET_KEY, { expiresIn: '1hr' })
res.json({ message: 'Login successful' })
} catch (error) {
res.status(500).json({ error: 'Error logging in' })
}
})

C:\Users\hasin\Desktop\prog\MERN\quiz\FINAL\userauth\server\models
userSchema.js

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({


email: { type: String, required: true },
username: { type: String, required: true, unique: true },
password: { type: String, required: true }
})

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

module.exports = User

You might also like