You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.1 KiB

const Admin = require('../models/admin')
const boom = require("boom");
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const fastify = require("fastify");
exports.adminSignUp = async (request, reply) => {
try {
const { email, password } = request.body
// Check if an admin with the same email address already exists
const existingAdmin = await Admin.findOne({ email })
if (existingAdmin) {
return reply.status(400).send({ message: 'Email already registered' })
}
// Hash the password using bcrypt
const hashedPassword = await bcrypt.hash(password, 10)
// Create a new admin object with the hashed password
const admin = new Admin({ email, password: hashedPassword })
// Save the new admin to the database
await admin.save()
// Generate a JWT token for the new admin
// const token = jwt.sign({ email: admin.email }, 'secret')
// // Return the token to the client
// return { token }
reply.send({message : "Admin Account Created Sucessfully"})
} catch (err) {
reply.status(500).send({ message: err.message })
}
}
exports.adminLogin = async (request, reply) => {
try {
const { email, password } = request.body
// Check if an admin with the email address exists
const admin = await Admin.findOne({ email })
if (!admin) {
return reply.status(401).send({ message: 'Invalid email or password' })
}
// Compare the password entered by the user with the hashed password stored in the database
const isPasswordValid = await bcrypt.compare(password, admin.password)
if (!isPasswordValid) {
return reply.status(401).send({ message: 'Invalid email or password' })
}
// Generate a JWT token for the authenticated admin
const token = jwt.sign({ email: admin.email }, 'secret')
// Return the token to the client
return { token }
} catch (err) {
reply.status(500).send({ message: err.message })
}
}