Skip to content

Commit

Permalink
Merge pull request #4 from HelloSniperMonkey/main
Browse files Browse the repository at this point in the history
added authorisation using jwt and also added api endpoint for login
  • Loading branch information
kushalag02 authored Dec 26, 2024
2 parents 1decc09 + 20805c6 commit 444f055
Show file tree
Hide file tree
Showing 14 changed files with 775 additions and 481 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ out
# Nuxt.js build / generate output
.nuxt
dist
/public

# Gatsby files
.cache/
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@
- Open the `.env` file and enter the MongoDB URL (Soumyajyoti has it)
```
URL="mongodb+srv://username:password@mongoatlascluster"
JWT_SECRET="..."
```
- you can add any string as jwt secret but it would be prefferd if you make a new js file and put
```
console.log(require('crypto').randomBytes(64).toString('hex'))
```
the output that comes out is cryptoghapically secure and is preffred as the new JWT_SECRET key

- Run locally
```bash
npm run serve
Expand Down
8 changes: 6 additions & 2 deletions models/Mentor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ const mentorSchema = new Schema({
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
phoneno: {
type: String,
required: true,
Expand All @@ -31,12 +35,12 @@ const mentorSchema = new Schema({
gitlabProfile: {
type: String,
required: false,
unique: true,
sparse: true,
},
otherProfile: {
type: String,
required: false,
unique: true,
sparse: true,
},
projectList: {
type: Array<String>,

Check failure on line 46 in models/Mentor.ts

View workflow job for this annotation

GitHub Actions / Lint code base

Don't use `String` as a type. Use string instead
Expand Down
10 changes: 7 additions & 3 deletions models/Student.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ const studentSchema = new Schema({
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
institute: {
type: String,
required: true,
Expand All @@ -26,7 +30,7 @@ const studentSchema = new Schema({
profilePage: {
type: String,
required: false,
unique: true,
sparse: true,
},
githubProfile: {
type: String,
Expand All @@ -36,12 +40,12 @@ const studentSchema = new Schema({
gitlabProfile: {
type: String,
required: false,
unique: true,
sparse: true,
},
otherProfile: {
type: String,
required: false,
unique: true,
sparse: true,
},
firstTime: {
type: Boolean,
Expand Down
38 changes: 36 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@
"@types/body-parser": "^1.19.2",
"@types/express-validator": "^3.0.0",
"body-parser": "^1.20.2",
"express": "^4.18.2",
"cookie-parser": "^1.4.7",
"express": "^4.21.2",
"express-validator": "^7.0.1",
"mongodb": "^5.6.0",
"mongoose": "^7.2.3",
"rimraf": "^4.1.2"
},
"devDependencies": {
"@types/express": "^4.17.17",
"@types/cookie-parser": "^1.4.8",
"@types/express": "^4.17.21",
"@types/mongodb": "^4.0.7",
"@types/mongoose": "^5.11.97",
"@types/node": "^18.14.2",
Expand Down
14 changes: 13 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
import dotenv from 'dotenv'
import bodyParser from 'body-parser'
import express, { Application } from 'express'
import express, { Application , Request, Response } from 'express'

Check warning on line 3 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint code base

'Request' is defined but never used

Check warning on line 3 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint code base

'Response' is defined but never used
import mongoose, { ConnectOptions } from 'mongoose'
import cookieParser from 'cookie-parser';
import { authorization } from './service/auth';

dotenv.config()

const app: Application = express()
const port = process.env.PORT || 3000
const dbURI = process.env.URL || null

app.use(cookieParser());

app.get('/auth', authorization ,(req ,res)=>{
console.log(req.headers.authorization);
res.status(200).send('Authenticated by index')
});

if (dbURI) {
mongoose
.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true } as ConnectOptions)
Expand All @@ -21,6 +30,7 @@ if (dbURI) {
/* eslint-disable */
app.use('/api/register/', require('./routes/register'))
app.use('/api/add-project/', require('./routes/addProject'))
app.use('/login/', require('./routes/login'))

app.listen(port, () => {
console.log(`Server is listening on port ${port}`)
Expand All @@ -30,3 +40,5 @@ if (dbURI) {
console.error('Error connecting to MongoDB:', err)
})
}

app.use(express.static('public'));
43 changes: 43 additions & 0 deletions src/routes/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import express, { Request, Response } from 'express';
const Student = require('../../models/Student')

Check failure on line 2 in src/routes/login.ts

View workflow job for this annotation

GitHub Actions / Lint code base

Require statement not part of import statement
const Mentor = require('../../models/Mentor')

Check failure on line 3 in src/routes/login.ts

View workflow job for this annotation

GitHub Actions / Lint code base

Require statement not part of import statement
const { generateToken } = require('../utils/jwt');

Check failure on line 4 in src/routes/login.ts

View workflow job for this annotation

GitHub Actions / Lint code base

Require statement not part of import statement
const router = express.Router();

router.post('/students', (req: Request, res: Response) => {
const { email, password } = req.body;
Student.findOne({ email: email })
.then((user: typeof Student) => {
if (!user) {
return res.status(404).json({ message: 'Student not found' });
}
if (user.password !== password) {
return res.status(401).json({ message: 'Invalid password' });
}
const token = generateToken({ email: user.email });
res.cookie("token", token);
res.status(200).json({ message: 'Login successful' });
}).catch((err: any) => {
res.status(500).json({ error: err.message });

Check warning on line 21 in src/routes/login.ts

View workflow job for this annotation

GitHub Actions / Lint code base

Unexpected any. Specify a different type
});
});

router.post('/mentors', (req, res) => {
const { email, password } = req.body;
Mentor.findOne({ email: email })
.then((user: typeof Student) => {
if (!user) {
return res.status(404).json({ message: 'Mentor not found' });
}
if (user.password !== password) {
return res.status(401).json({ message: 'Invalid password' });
}
const token = generateToken({ email: user.email });
res.cookie("token", token);
res.status(200).json({ message: 'Login successful' });
}).catch((err: any) => {
res.status(500).json({ error: err.message });
});

Check warning on line 40 in src/routes/login.ts

View workflow job for this annotation

GitHub Actions / Lint code base

Unexpected any. Specify a different type
});

module.exports = router
Empty file removed src/routes/mentor.ts
Empty file.
17 changes: 10 additions & 7 deletions src/routes/register.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
/* eslint-disable */
import { Request, Response } from 'express';
const express = require('express')
const Student = require('../../models/Student')
const Mentor = require('../../models/Mentor')
const router = express.Router()
import { body, validationResult } from 'express-validator'
import { generateToken } from '../utils/jwt';

// @route POST /api/register/student
// @desc Register student
Expand All @@ -30,6 +32,7 @@ router.post(
firstname: any
lastname: any
email: any
password: any
institute: any
phoneno: number
profilePage: any
Expand All @@ -39,13 +42,7 @@ router.post(
firstTime: any
}
},
res: {
status: (arg0: number) => {
(): any
new (): any
json: { (arg0: { error?: any; message?: any }): void; new (): any }
}
}
res: Response
) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
Expand All @@ -57,6 +54,7 @@ router.post(
firstname,
lastname,
email,
password,
institute,
phoneno,
profilePage,
Expand All @@ -69,6 +67,7 @@ router.post(
firstname,
lastname,
email,
password,
institute,
phoneno,
profilePage,
Expand All @@ -77,7 +76,11 @@ router.post(
otherProfile,
firstTime,
})
const token = generateToken({ email: email });
console.log(token);
await user.save()

res.cookie('token', token);
res.status(200).json({ message: 'User created successfully' })
} catch (err: any) {
res.status(500).json({ error: err.message })
Expand Down
Empty file removed src/routes/student.ts
Empty file.
21 changes: 21 additions & 0 deletions src/service/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Request, Response, NextFunction } from 'express';
import { verifyToken } from '../utils/jwt';

export const authorization = (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Authentication required' });
}

const decoded = verifyToken(token);
if(!decoded) {
return res.status(401).json({ message: 'Invalid token' });
} else {
console.log('Authenticated by auth service');
}
next();
} catch (error) {
res.status(401).json({ message: 'Invalid token' });
}
};
20 changes: 20 additions & 0 deletions src/utils/jwt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import jwt from 'jsonwebtoken';

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

export interface JWTPayload {
email: string;
}

export const generateToken = (payload: JWTPayload): string => {
return jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' });
};

export const verifyToken = (token: string): boolean => {
try {
jwt.verify(token, JWT_SECRET);
return true;
} catch (error) {
return false;
}
};
Loading

0 comments on commit 444f055

Please sign in to comment.