Skip to content

Commit d024685

Browse files
authored
Merge pull request #32 from adityacosmos24/main
feat: user registration login and jwt generation
2 parents 2703c2b + 44ddccb commit d024685

File tree

10 files changed

+295
-158
lines changed

10 files changed

+295
-158
lines changed

package-lock.json

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/app.js

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
import express from "express";
2-
import cors from "cors"
3-
import cookieparser from "cookie-parser"
4-
import authRoutes from "./routes/authRoutes.js"
1+
import express from 'express';
2+
import cors from 'cors';
3+
import cookieparser from 'cookie-parser';
4+
import authRoutes from './routes/authRoutes.js';
55

6-
const app = express()
6+
const app = express();
77

88
app.use(cors({
9-
origin: process.env.CORS_URL,
10-
credentials: true
11-
}))
9+
origin: process.env.CORS_URL,
10+
credentials: true
11+
}));
1212

13-
app.use(express.json({ limit: "16kb" }))
14-
app.use(express.urlencoded({ extended: true, limit: "16kb" }))
15-
app.use(express.static("public"))
16-
app.use(cookieparser())
13+
app.use(express.json({ limit: '16kb' }));
14+
app.use(express.urlencoded({ extended: true, limit: '16kb' }));
15+
app.use(express.static('public'));
16+
app.use(cookieparser());
1717

1818
// Routes
19-
app.use("/api/auth", authRoutes)
19+
app.use('/api/auth', authRoutes);
2020

21-
export { app }
21+
export { app };

src/controllers/authController.js

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,33 @@
1-
import { loginUser } from "../services/authService.js";
1+
import { registerUserService,loginUserService } from '../services/authService.js';
22

3-
export const login = async (req, res) => {
3+
export const registerUser = async (req, res) => {
44
try {
5-
const { email, password } = req.body;
6-
7-
if (!email?.trim() || !password?.trim()) {
8-
return res.status(400).json({ success: false, message: "Email and password are required" });
9-
}
5+
const userData = await registerUserService(req.body);
6+
return res.status(201).json({
7+
success: true,
8+
message: 'User registered successfully',
9+
user: userData
10+
});
11+
} catch (error) {
12+
console.error('Error in registerUser:', error.message);
13+
res.status(400).json({ success: false, message: error.message });
14+
}
15+
};
1016

11-
const { token, refreshToken } = await loginUser(email, password);
17+
export const loginUser = async (req, res) => {
18+
try {
19+
const { email, password } = req.body;
20+
const result = await loginUserService({ email, password });
1221

1322
return res.status(200).json({
1423
success: true,
15-
message: "Login successful",
16-
token,
17-
refreshToken,
18-
});
19-
} catch (err) {
20-
return res.status(401).json({
21-
success: false,
22-
message: err.message || "Authentication failed",
24+
message: 'Login successful',
25+
token: result.accessToken,
26+
user: result.user,
2327
});
28+
} catch (error) {
29+
console.error('Error in loginUser:', error);
30+
const status = error.statusCode || 400;
31+
return res.status(status).json({ success: false, message: error.message || 'Login failed' });
2432
}
25-
};
33+
};

src/index.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
// Entry point for RBAC authentication system
22

3-
import connectDB from "./config/dbconnection.js";
4-
import {app} from "./app.js"
3+
import connectDB from './config/dbconnection.js';
4+
import {app} from './app.js';
55
import dotenv from 'dotenv';
66

77
dotenv.config();
88

99

10-
connectDB()
11-
.then(
12-
app.listen(process.env.PORT || 5000 ,()=>{
13-
console.log(`Server is running at port : ${process.env.PORT}`);
14-
})
15-
)
16-
.catch((err)=>{
17-
console.log("database connection faield",err);
18-
})
10+
connectDB().then(
11+
app.listen(process.env.PORT || 5000 ,()=>
12+
{
13+
console.log(`Server is running at port : ${process.env.PORT}`);
14+
})
15+
).catch((err)=>
16+
{
17+
console.log('database connection faield',err);
18+
});

src/models/Permission.model.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import mongoose from "mongoose";
1+
import mongoose from 'mongoose';
22

33
const permissionSchema = new mongoose.Schema({
4-
name: {
5-
type: String,
6-
required: true,
7-
unique: true
8-
},
9-
description: {
10-
type: String
11-
}
4+
name: {
5+
type: String,
6+
required: true,
7+
unique: true,
8+
},
9+
description: {
10+
type: String,
11+
},
1212
});
1313

14-
export default mongoose.model("Permission", permissionSchema);
14+
export default mongoose.model('Permission', permissionSchema);

src/models/Role.model.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import mongoose from "mongoose";
1+
import mongoose from 'mongoose';
22

33
const roleSchema = new mongoose.Schema({
44
name: {
@@ -9,9 +9,9 @@ const roleSchema = new mongoose.Schema({
99
permissions: [
1010
{
1111
type: mongoose.Schema.Types.ObjectId,
12-
ref: "Permission"
12+
ref: 'Permission'
1313
}
1414
]
1515
});
1616

17-
export default mongoose.model("Role", roleSchema);
17+
export default mongoose.model('Role', roleSchema);

src/models/user.model.js

Lines changed: 87 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,98 +1,100 @@
1-
import mongoose, { Schema } from "mongoose";
2-
import jwt from "jsonwebtoken"
3-
import bcrypt from "bcryptjs"
1+
import mongoose, { Schema } from 'mongoose';
2+
import jwt from 'jsonwebtoken';
3+
import bcrypt from 'bcryptjs';
44

5-
const userschema = new Schema({
6-
username: {
7-
type: String,
8-
required: true,
9-
unique: true,
10-
lowercase: true,
11-
trim: true,
12-
index: true
13-
},
14-
email: {
15-
type: String,
16-
required: true,
17-
unique: true,
18-
lowercase: true,
19-
trim: true,
20-
},
21-
fullname: {
22-
type: String,
23-
required: true,
24-
trim: true,
25-
index: true
26-
},
27-
password: {
28-
type: String,
29-
required: [true, "Password is required"]
30-
},
31-
refreshToken: {
32-
type: String
33-
},
34-
role: {
35-
type: mongoose.Schema.Types.ObjectId,
36-
ref: "Role",
37-
default: null
38-
}
39-
}, {
40-
timestamps: true
41-
})
42-
43-
userschema.pre("save", async function (next) {
44-
if (!this.isModified("password")) return next();
5+
const userschema=new Schema({
6+
username:{
7+
type:String,
8+
required:true,
9+
unique:true,
10+
lowercase:true,
11+
trim:true,
12+
index:true
13+
},
14+
email:{
15+
type:String,
16+
required:true,
17+
unique:true,
18+
lowercase:true,
19+
trim:true,
20+
},
21+
fullname:{
22+
type:String,
23+
required:true,
24+
trim:true,
25+
index:true
26+
},
27+
password:{
28+
type:String,
29+
required:[true,'Password is required']
30+
},
31+
refreshToken:{
32+
type:String
33+
},
34+
role: {
35+
type: mongoose.Schema.Types.ObjectId,
36+
ref: 'Role',
37+
default: null
38+
}
39+
},{
40+
timestamps:true
41+
});
4542

46-
this.password = await bcrypt.hash(this.password, 10)
47-
next()
48-
})
43+
userschema.pre('save', async function (next){
44+
if(!this.isModified('password'))return next();
4945

50-
userschema.methods.isPasswordCorrect = async function (password) {
51-
return await bcrypt.compare(password, this.password)
52-
}
46+
this.password=await bcrypt.hash(this.password,10);
47+
next();
48+
});
5349

54-
userschema.methods.generateAccessToken = function () {
55-
try {
56-
if (!process.env.JWT_SECRET) {
57-
throw new Error("Environment variables for token generation are missing");
58-
}
50+
userschema.methods.isPasswordCorrect=async function(password){
51+
return await bcrypt.compare(password,this.password);
52+
};
5953

60-
return jwt.sign(
61-
{
62-
_id: this._id,
63-
email: this.email,
64-
username: this.username,
65-
fullname: this.fullname,
66-
},
67-
process.env.JWT_SECRET,
68-
{
69-
expiresIn: '1d',
70-
}
71-
);
72-
} catch (error) {
73-
throw new Error("Failed to generate access token");
54+
userschema.methods.genrateAccessToken = function () {
55+
try {
56+
if (!process.env.JWT_SECRET ) {
57+
throw new Error('Environment variables for token generation are missing');
7458
}
59+
60+
return jwt.sign(
61+
{
62+
id: this._id,
63+
email: this.email,
64+
username: this.username,
65+
fullname: this.fullname,
66+
},
67+
process.env.JWT_SECRET,
68+
{
69+
expiresIn: '1d',
70+
}
71+
);
72+
}
73+
catch (error) {
74+
throw new Error('Failed to generate access token');
75+
}
7576
};
7677

7778
userschema.methods.refreshAccessToken = function () {
78-
try {
79-
if (!process.env.REFRESH_TOKEN_SECRET || !process.env.REFRESH_TOKEN_EXPIRY) {
80-
throw new Error("Environment variables for refresh token generation are missing");
81-
}
82-
83-
return jwt.sign(
84-
{
85-
_id: this._id,
86-
},
87-
process.env.REFRESH_TOKEN_SECRET,
88-
{
89-
expiresIn: '10d',
90-
}
91-
);
92-
} catch (error) {
93-
throw new Error("Failed to generate refresh token");
79+
try {
80+
if (!process.env.REFRESH_TOKEN_SECRET || !process.env.REFRESH_TOKEN_EXPIRY) {
81+
throw new Error('Environment variables for refresh token generation are missing');
9482
}
83+
84+
return jwt.sign(
85+
{
86+
_id: this._id,
87+
},
88+
process.env.REFRESH_TOKEN_SECRET,
89+
{
90+
expiresIn: '10d',
91+
}
92+
);
93+
}
94+
catch (error) {
95+
throw new Error('Failed to generate refresh token');
96+
}
9597
};
9698

9799

98-
export const User = mongoose.model("User", userschema)
100+
export const User=mongoose.model('User',userschema);

src/routes/authRoutes.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
import express from "express";
2-
import { login } from "../controllers/authController.js";
1+
import express from 'express';
2+
import { registerUser,loginUser } from '../controllers/authController.js';
33

44
const router = express.Router();
55

6-
router.post("/login", login);
6+
router.post('/register', registerUser);
7+
router.post('/login', loginUser);
78

89
export default router;

0 commit comments

Comments
 (0)