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

database setup #10

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion api.rest
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ POST http://localhost:5500/api/send-otp HTTP/1.1
content-Type: application/json

{
"phone": "+919888888888"
"phone": "+919889699052"
}

16 changes: 15 additions & 1 deletion backend/.env
Original file line number Diff line number Diff line change
@@ -1 +1,15 @@
require('dotenv').config();
require('dotenv').config();

HASH_SECRET=5f88ed6dcc54f59d49b84dcb50f29616eea2130b4a7bd4155476b642f44684838dbb79c1707945386cb975e99678127b8ac6af8ff2e4a0dd975ee1f8d2e3d88b

SMS_SID=AC033683f5f62de0f89a4a744bea62c1dc

SMS_AUTH_TOKEN=17505f00037f7c0ba13afab9e316fa55

SMS_FROM_NUMBER="+15075333601"

DB_URL=mongodb+srv://Ashna:[email protected]/All-aboard?retryWrites=true&w=majority

JWT_ACCESS_TOKEN_SECRET=4dc71846bca36cf7cc9d5757467e58277a2e9bab3c71bc2548979c5ac522c25adaed464fa2819ce603b826677f4c95ce4bd0d44fc64b97ba494950183acbf498

JWT_REFRESH_TOKEN_SECRET=59c6643872b7610ca568eb7e09e7ae3eab9c86f30cc9513eead66337380c93de41a6078687b03bfee7b9a12d50822fca8d23175bbf8d7bce85fee2fdf43c7481'
77 changes: 77 additions & 0 deletions backend/controllers/auth-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
const otpService = require('../services/otp-service');
const hashService = require('../services/hash-service');
const userService = require('../services/user-service');
const tokenService = require('../services/token-service');
const UserDto = require('../dtos/user-dto');

class AuthController {
async sendOtp(req, res) {
const { phone } = req.body;
if (!phone) {
res.status(400).json({ message: 'Phone field is required!' });
}

const otp = await otpService.generateOtp();

const ttl = 1000 * 60 * 2; // 2 min
const expires = Date.now() + ttl;
const data = `${phone}.${otp}.${expires}`;
const hash = hashService.hashOtp(data);

// send OTP
try {
// await otpService.sendBySms(phone, otp);
res.json({
hash: `${hash}.${expires}`,
phone,
otp,
});
} catch (err) {
console.log(err);
res.status(500).json({ message: 'Failed to send message!' });
}
}

async verifyOtp(req, res) {
const { otp, hash, phone } = req.body;
if (!otp || !hash || !phone) {
res.status(400).json({ message: 'All fields are required!' });
}

const [hashedOtp, expires] = hash.split('.');
if (Date.now() > +expires) {
res.status(400).json({ message: 'OTP expired!' });
}

const data = `${phone}.${otp}.${expires}`;
const isValid = otpService.verifyOtp(hashedOtp, data);
if (!isValid) {
res.status(400).json({ message: 'Invalid OTP' });
}

let user;
try {
user = await userService.findUser({ phone });
if (!user) {
user = await userService.createUser({ phone });
}
} catch (err) {
console.log(err);
res.status(500).json({ message: 'Db error' });
}

const { accessToken, refreshToken } = tokenService.generateTokens({
_id: user._id,
activated: false,
});

res.cookie('refreshToken', refreshToken, {
maxAge: 1000 * 60 * 60 * 24 * 30,
httpOnly: true,
});
const userDto = new UserDto(user);
res.json({ accessToken, user: userDto });
}
}

module.exports = new AuthController();
17 changes: 17 additions & 0 deletions backend/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const mongoose = require('mongoose');
function DbConnect() {
const DB_URL = process.env.DB_URL;
// Database connection
mongoose.connect(DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('DB connected...');
});
}

module.exports = DbConnect;
14 changes: 14 additions & 0 deletions backend/models/user-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema(
{
phone: { type: String, required: true },
activated: { type: Boolean, required: false, default: false },
},
{
timestamps: true,
}
);

module.exports = mongoose.model('User', userSchema, 'users');
Loading