Skip to content

Commit

Permalink
backed for admin has done , added login create admin fxn
Browse files Browse the repository at this point in the history
  • Loading branch information
ShivanshPlays committed Nov 10, 2024
1 parent 94a0c51 commit 9c4ecbc
Show file tree
Hide file tree
Showing 4 changed files with 135 additions and 1 deletion.
87 changes: 87 additions & 0 deletions server/Controllers/adminController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const Admin = require("../Models/Admin");
const bcrypt = require("bcrypt");
var jwt = require("jsonwebtoken");
const nodemailer = require("nodemailer");
const crypto = require("crypto");
require('dotenv').config(); // Load environment variables from .env file
const { body, validationResult } = require("express-validator");
const login= async (req, res) => {
let success = false;
console.log("see");

// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

const { email, password } = req.body;

try {
let user = await Admin.findOne({ email });

// If user does not exist
if (!user) {
return res.status(400).json({
success,
error: "Please try to login with correct credentials",
});
}

// Compare provided password with stored password
const passwordCompare = await bcrypt.compare(password, user.password);

if (!passwordCompare) {
return res.status(400).json({
success,
error: "Please try to login with correct credentials",
});
}

// Create JWT payload
const data = {
user: {
id: user.id,
},
};

// Sign the JWT
const authtoken = jwt.sign(data, process.env.JWT_SECRET);
// Send token in response to be stored in localStorage on the client
return res.status(200).json({ success: true, authtoken });
} catch (error) {
console.error(error.message);
return res.status(500).send("Internal Server Error");
}
}
const createAdmin=async (req, res) => {
const { name, email, password } = req.body;

try {
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);

// Create a new user (save in your database)
const user = new Admin({ name, email, password: hashedPassword });

await user.save();
return res.status(201).json({ success: true, message: "Admin created successfully"})
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
const logout=async (req,res)=>{
// Optionally, you can clear the cookie if you're using cookies for sessions
res.clearCookie('connect.sid'); // Replace 'connect.sid' with your session cookie name

// Send a success response
return res.status(200).json({ message: 'Successfully logged out.' });

}
const dashboard= null;


module.exports = {
login,
createAdmin,
};
30 changes: 30 additions & 0 deletions server/Models/Admin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const mongoose = require("mongoose");
const { Schema } = mongoose;

const AdminSchema = new Schema(
{
imageUrl: {
type: String,
required: false
},
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true,
match: [/\S+@\S+\.\S+/, 'Please enter a valid email address'],
},
password: {
type: String,
required: true,
minlength: 8 // Minimum length for password
},
},
{ timestamps: true }
);

const Admin = mongoose.model('Admin', AdminSchema);
module.exports = Admin;
2 changes: 1 addition & 1 deletion server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ app.use("/api/contact", require("./routes/contact"));
app.use("/api/blog", require("./routes/blog"));
app.use("/api/visitor", require("./routes/visitor"));
app.use("/api/showcaseProjects", require("./routes/projectsRoute"));

app.use("/api/admin", require("./routes/adminRoute"))
// Socket.io connection handling
const users = {};

Expand Down
17 changes: 17 additions & 0 deletions server/routes/adminRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const express = require("express");
var jwt = require("jsonwebtoken");
const {login,createAdmin}= require("../Controllers/adminController")
const User = require("../Models/Admin.js");
const bcrypt = require("bcrypt");
const router = express.Router();
require("dotenv").config();
const { body, validationResult } = require("express-validator");
const { OAuth2Client } = require("google-auth-library");
const rateLimit = require("express-rate-limit");
require('dotenv').config(); // Load environment variables from .env file


router.post("/login",login)
router.post("/create",createAdmin)

module.exports = router;

0 comments on commit 9c4ecbc

Please sign in to comment.