Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Back end tasks #25

Merged
merged 6 commits into from
Dec 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions server/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,29 @@ NODE_ENV=
PORT=

# DB Config Variables
DB=
DB_URI=
DB_HOST=
DB_PORT=
DB_USER=
DB_PASS=
DB_DATABASE=

PORT=5000

# Token Config Variables
JWT_SECRET=
JWT_EXPIRES_IN=

########## Example ##########
# NODE_ENV=development
# PORT=3000
# NODE_ENV=development or production
# PORT=5000

# DB=online or local
# DB_URI=**************
# DB_HOST=localhost
# DB_PORT=5432
# DB_USER=postgres
# DB_PASS=********
# DB_DATABASE=scoutsManagementSystem
# PORT=5000

# To get a random string for JWT_SECRET
# Run This in terminal => node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
Expand Down
2 changes: 1 addition & 1 deletion server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import alertRouter from "./routes/alert.route.js"
import { notFound, errorHandler } from './middlewares/error.middleware.js'
import cookieParser from 'cookie-parser'
const app = express()
const PORT = process.env.PORT || 3000
const PORT = process.env.PORT || 5000

db.connect()
.then(() => {
Expand Down
278 changes: 145 additions & 133 deletions server/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,140 +1,152 @@
import bcrypt from "bcryptjs";
import db from "../database/db.js";
import { jsonToArray } from "../utils/convert.js";
import generateToken from "../utils/generateToken.js";
import bcrypt from 'bcryptjs'
import db from '../database/db.js'
import generateToken from '../utils/generateToken.js'

const authController = {
// @desc Create a new captain
// @route POST /api/auth/signup
// @access Public
signup: async (req, res) => {
try {
// get email and password from request body
const email = req.body["email"];
const password = req.body["password"];

// Check if email already exists
const captain = await db.query(
`SELECT "email", "password"
// @desc Create a new captain
// @route POST /api/auth/signup
// @access Public
signup: async (req, res) => {
try {
// get info from request body
const {
firstName,
middleName,
lastName,
phoneNumber,
email,
password,
gender,
} = req.body

// Check if email already exists
const captain = await db.query(
`SELECT "email", "password"
FROM "Captain"
WHERE "email" = $1;`,
[email]
);
if (captain.rows.length) {
return res.status(400).json({ error: "Email is taken!!" });
}

// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);

// Create a new Captain
req.body = { ...req.body, password: hashedPassword };
const params = jsonToArray(req.body);
const result = await db.query(
`INSERT INTO "Captain"("firstName", "middleName", "lastName", "phoneNumber", "email", "password", "gender", "type")
[email]
)
if (captain.rows.length) {
return res.status(400).json({ error: 'Email is taken!!' })
}

// Hash the password
const hashedPassword = await bcrypt.hash(password, 10)

// Create a new Captain
const result = await db.query(
`INSERT INTO "Captain"("firstName", "middleName", "lastName", "phoneNumber", "email", "password", "gender", "type")
VALUES($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *;`,

params.concat(["regular"])
);
const newCaptain = result.rows[0];

// Generate a JWT token
generateToken(res, newCaptain.captainId);

// Send the response
res.status(201).json({
message: "Captain created successfully",
data: newCaptain,
});
} catch (error) {
console.log(error);
res.status(500).json({
error: "An error occurred while creating a new captain!!",
});
}
},

// @desc Login a captain
// @route POST /api/auth/login
// @access Public
login: async (req, res) => {
try {
// Deconstruct the request body
const { email, password } = req.body;

// Check if email already exists
const result = await db.query(
`SELECT *
[
firstName,
middleName,
lastName,
phoneNumber,
email,
hashedPassword,
gender,
'regular',
]
)
const newCaptain = result.rows[0]

// Generate a JWT token
generateToken(res, newCaptain.captainId)

// Send the response
res.status(201).json({
message: 'Captain created successfully',
body: newCaptain,
})
} catch (error) {
console.log(error)
res.status(500).json({
error: 'An error occurred while creating a new captain!!',
})
}
},

// @desc Login a captain
// @route POST /api/auth/login
// @access Public
login: async (req, res) => {
try {
// Deconstruct the request body
const { email, password } = req.body

// Check if email already exists
const result = await db.query(
`SELECT *
FROM "Captain"
WHERE "email" = $1;`,
[email]
);
if (!result.rows.length) {
return res.status(400).json({
error: "Invalid email",
});
}

// Get Captain's data
const captain = result.rows[0];

// Check if the password is correct
const isCorrect = await bcrypt.compare(password, captain.password);
if (!isCorrect) {
return res.status(400).json({
error: "Invalid password",
});
}

// Generate a JWT token
generateToken(res, captain.captainId);

// Send the response
res.status(200).json({
message: "Logged in successfully",
data: captain,
});
} catch (error) {
console.log(error);
res.status(500).json({
error: "An error occurred while logging you in",
});
}
},

// @desc Logout a captain
// @route GET /api/auth/logout
// @access Private
logout: async (req, res) => {
try {
// Clear the cookie
res.clearCookie("token");

// Send the response
res.status(200).json({
message: "Logged out successfully",
});
} catch (error) {
console.log(error);
res.status(500).json({
error: "An error occurred while logging out",
});
}
},

// @desc Auth logged-in captain
// @route GET /api/auth/me
// @access Private
me: (req, res) => {
try {
res.status(200).json({ user: req.captain });
} catch (error) {
console.log(error);
res.status(500).json({
error: "An error occurred while fetching data.",
});
}
},
};

export default authController;
[email]
)
if (!result.rows.length) {
return res.status(400).json({
error: 'Invalid email',
})
}

// Get Captain's data
const captain = result.rows[0]

// Check if the password is correct
const isCorrect = await bcrypt.compare(password, captain.password)
if (!isCorrect) {
return res.status(400).json({
error: 'Invalid password',
})
}

// Generate a JWT token
generateToken(res, captain.captainId)

// Send the response
res.status(200).json({
message: 'Logged in successfully',
body: captain,
})
} catch (error) {
console.log(error)
res.status(500).json({
error: 'An error occurred while logging you in',
})
}
},

// @desc Logout a captain
// @route POST /api/auth/logout
// @access Private
logout: async (req, res) => {
try {
// Clear the cookie
res.clearCookie('token')

// Send the response
res.status(200).json({
message: 'Logged out successfully',
})
} catch (error) {
console.log(error)
res.status(500).json({
error: 'An error occurred while logging out',
})
}
},

// @desc Auth logged-in captain
// @route GET /api/auth/me
// @access Private
me: (req, res) => {
try {
res.status(200).json({ user: req.captain })
} catch (error) {
console.log(error)
res.status(500).json({
error: 'An error occurred while fetching data.',
})
}
},
}

export default authController
17 changes: 17 additions & 0 deletions server/controllers/finance.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import db from '../database/db.js'

const financeController = {
// @desc Get a budget
// @route GET /api/finance/budget
// @access Private
getBudget: async (req, res) => {
try {
// get subsciptions
return res.status(200)
} catch (err) {
return res.status(500).json({ message: err.message })
}
},
}

export default financeController
20 changes: 20 additions & 0 deletions server/controllers/stats.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import db from '../database/db.js'

const statsController = {
// @desc Get all absence rates
// @route GET /api/stats
// @access Private
getAbsenceRate: async (req, res) => {
try {
if (req.user.type === 'general') {
return res.status(200)
} else {
return res.status(200)
}
} catch (err) {
return res.status(500).json({ message: err.message })
}
},
}

export default statsController
Loading