-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #7 from hariscs/auth
Validation And Auth
- Loading branch information
Showing
21 changed files
with
868 additions
and
80 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
NODE_ENV=development | ||
PORT=5000 | ||
MONGO_URI=YOUR_MONGO_URI | ||
MONGO_URI=YOUR_MONGO_URI | ||
JWT_SECRET=YOUR_JWT_SECRET |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
import { Request, Response } from 'express' | ||
import { USER_SCHEMA } from '@/models/user_model' | ||
import { isValidObjectId } from 'mongoose' | ||
import { log } from 'console' | ||
import { generate_token } from 'utils/generate_token' | ||
|
||
//* @desc Register user | ||
//* route POST /api/user | ||
//? @access Public | ||
export async function register_user( | ||
req: Request, | ||
res: Response | ||
): Promise<void> { | ||
try { | ||
const user_data = req.body | ||
// check if user email already exists | ||
const { email } = req.body | ||
const existing_user = await USER_SCHEMA.findOne({ email }) | ||
if (existing_user) { | ||
res.status(409).json({ error: 'User email already exists' }) | ||
return | ||
} | ||
|
||
//* post user | ||
const user = await USER_SCHEMA.create(user_data) | ||
generate_token(res, user._id.toString()) | ||
res.status(201).json(user) | ||
} catch (error) { | ||
log('Error posting user:', error) | ||
res.status(500).json({ error: 'Internal server error' }) | ||
} | ||
} | ||
|
||
//* @desc Login user | ||
//* route GET /api/user | ||
//! @access Public | ||
export async function login_user(req: Request, res: Response): Promise<void> { | ||
try { | ||
//* get user by email and password | ||
const { email, password } = req.body | ||
const user = await USER_SCHEMA.findOne({ email }) | ||
|
||
// check if user exists and password is correct | ||
if (!user || !(await user.match_password(password))) { | ||
res.status(401).json({ error: 'Incorrect email or password' }) | ||
return | ||
} | ||
generate_token(res, user._id.toString()) | ||
res.status(200).json(user) | ||
} catch (error) { | ||
log('Error fetching user:', error) | ||
res.status(500).json({ error: 'Internal server error' }) | ||
} | ||
} | ||
|
||
//* @desc Logout user | ||
//* route POST /api/user/logout | ||
// ? @access Public | ||
export async function logout_user(_: Request, res: Response): Promise<void> { | ||
try { | ||
res.clearCookie('token').status(200).json({ message: 'User logged out' }) | ||
} catch (error) { | ||
log('Error logging out user:', error) | ||
res.status(500).json({ error: 'Internal server error' }) | ||
} | ||
} | ||
|
||
//* @desc Update user | ||
//* route PATCH /api/user/:id | ||
//! @access Private | ||
export async function update_user(req: Request, res: Response): Promise<void> { | ||
try { | ||
const { id } = req.params | ||
//* check if id is valid | ||
if (!isValidObjectId(id)) { | ||
res.status(400).json({ error: 'Invalid id' }) | ||
return | ||
} | ||
//* check if user exists | ||
const user = await USER_SCHEMA.findById(id) | ||
if (!user) { | ||
res.status(404).json({ error: 'user not found' }) | ||
return | ||
} | ||
|
||
//* check if user email already exists | ||
const { email } = req.body | ||
const existing_user = await USER_SCHEMA.findOne({ email }) | ||
if (existing_user && existing_user._id.toString() !== id) { | ||
res.status(409).json({ error: 'Email already exists' }) | ||
return | ||
} | ||
|
||
//* update user | ||
const updated_user = await USER_SCHEMA.findByIdAndUpdate(id, req.body, { | ||
new: true, | ||
}) | ||
res.status(200).json(updated_user) | ||
} catch (error) { | ||
log('Error updating user:', error) | ||
res.status(500).json({ error: 'Internal server error' }) | ||
} | ||
} | ||
|
||
//* @desc Get User | ||
//* route GET /api/user/profile | ||
//! @access Private | ||
export async function get_user(req: Request, res: Response): Promise<void> { | ||
try { | ||
const user = { | ||
name: req.user?.name, | ||
email: req.user?.email, | ||
_id: req.user?._id, | ||
} | ||
res.status(200).json(user) | ||
} catch (error) { | ||
log('Error fetching user:', error) | ||
res.status(500).json({ error: 'Internal server error' }) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,20 @@ | ||
import { log } from '@repo/logger' | ||
import { createServer } from './server' | ||
import job_route from '@routes/job_route' | ||
import { job_route, user_route } from '@/routes' | ||
import { connect_db } from 'config/db' | ||
|
||
const port = process.env.PORT || 5001 | ||
const server = createServer() | ||
|
||
server.use('/api/v1/jobs', job_route) | ||
server.use('/api/v1/user', user_route) | ||
|
||
server.listen(port, () => { | ||
log(`api running on ${port}`) | ||
}) | ||
connect_db() | ||
.then(() => { | ||
server.listen(port, () => { | ||
log(`db connected & api running on ${port}`) | ||
}) | ||
}) | ||
.catch((error) => { | ||
log('Error connecting to db:', error) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import { Request as ExpressRequest, Response, NextFunction } from 'express' | ||
import jwt, { JwtPayload } from 'jsonwebtoken' | ||
import { USER_SCHEMA } from '@/models/user_model' | ||
import { log } from 'console' | ||
|
||
interface User { | ||
name?: string | ||
email: string | ||
password: string | ||
} | ||
|
||
interface Request extends ExpressRequest { | ||
user?: User | ||
} | ||
|
||
export async function protect_route( | ||
req: Request, | ||
res: Response, | ||
next: NextFunction | ||
) { | ||
try { | ||
const token = req.cookies.token | ||
if (!token) { | ||
res.status(401).json({ error: 'Unauthorized' }) | ||
return | ||
} | ||
const secret = process.env.JWT_SECRET | ||
if (!secret) { | ||
res.status(500).json({ error: 'JWT secret is undefined' }) | ||
return | ||
} | ||
const decoded = jwt.verify(token, secret) as JwtPayload | ||
req.user = (await USER_SCHEMA.findById(decoded.user_id).select( | ||
'-password' | ||
)) as User | ||
|
||
next() | ||
} catch (error) { | ||
res.status(500).json({ error: 'Internal server error' }) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { Request, Response, NextFunction } from 'express' | ||
import { z } from 'zod' | ||
|
||
export function validate_schema(schema: z.AnyZodObject) { | ||
return (req: Request, res: Response, next: NextFunction) => { | ||
try { | ||
schema.parse(req.body) | ||
next() | ||
} catch (error) { | ||
if (error instanceof z.ZodError) { | ||
const error_messages = error.errors.map((issue) => ({ | ||
message: `${issue.path.join('.')} - ${issue.message}`, | ||
})) | ||
res.status(400).json({ error: 'Invalid data', error_messages }) | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import mongoose, { Document, Schema } from 'mongoose' | ||
import bcrypt from 'bcrypt' | ||
|
||
interface IUserSchema extends Document { | ||
name?: string | ||
email: string | ||
password: string | ||
match_password: (password: string) => Promise<boolean> | ||
} | ||
|
||
const user_schema = new Schema( | ||
{ | ||
name: { type: String }, | ||
email: { type: String, required: true, unique: true }, | ||
password: { type: String, required: true }, | ||
}, | ||
{ | ||
timestamps: true, | ||
} | ||
) | ||
|
||
user_schema.pre('save', async function (next) { | ||
const user = this | ||
if (!user.isModified('password')) { | ||
next() | ||
return | ||
} | ||
const salt = await bcrypt.genSalt(10) | ||
this.password = await bcrypt.hash(this.password, salt) | ||
next() | ||
}) | ||
|
||
user_schema.methods.match_password = async function (entered_password: string) { | ||
return await bcrypt.compare(entered_password, this.password) | ||
} | ||
|
||
export const USER_SCHEMA = mongoose.model<IUserSchema>('User', user_schema) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export { default as job_route } from './job_route' | ||
export { default as user_route } from './user_route' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.