Skip to content

Commit

Permalink
user create and login api
Browse files Browse the repository at this point in the history
  • Loading branch information
tusheer committed Feb 27, 2022
1 parent 1bfa3df commit fb8fc00
Show file tree
Hide file tree
Showing 14 changed files with 859 additions and 181 deletions.
12 changes: 8 additions & 4 deletions server/common/handler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import mongoose from 'mongoose';

const save = async (item, modelName) => {
const model = new mongoose.models[modelName](item);
const savedItem = await model.save();
const save = async (item, model) => {
const _model = new model(item);
const savedItem = await _model.save();
return savedItem;
};

Expand Down Expand Up @@ -35,6 +35,10 @@ const getAll = async (modelName, { skip, limit }: { skip: number; limit: number
}
return model;
};
const findOne = async (modelName, request) => {
let model = await mongoose.models[modelName].findOne(request);
return model;
};

const getWithPagination = async (modelName, { page, limit }: { page: number; limit: number }) => {
const mongoModel = mongoose.models[modelName] as any;
Expand All @@ -56,4 +60,4 @@ const getWithPagination = async (modelName, { page, limit }: { page: number; lim
return model;
};

export { save, update, deleteById, getById, getAll, getWithPagination };
export { save, update, deleteById, getById, getAll, getWithPagination, findOne };
66 changes: 66 additions & 0 deletions server/controllers/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import express from 'express';
import { handleValidation } from '../../middlewares/index';
import { createUser, checkUser, searchOne, createUserValidate } from '../../services/auth';
import dotenv from 'dotenv';
import jwt from 'jsonwebtoken';

const router = express.Router();
dotenv.config();

const createToken = (id, email) =>
jwt.sign({ id: id, email: email, exp: Math.floor(Date.now() / 1000) + parseInt(process.env.JWT_EXPIRES_IN) }, process.env.JWT_SECRET);

const createUserHandler = async (req, res, next) => {
try {
const user = req.body;
const userData = await createUser(user);
if (userData) {
res.status(201).send({
status: 'ok',
message: 'User created successfully',
result: userData,
authToken: createToken(userData._id, userData.email),
});
} else {
throw new Error('User already exist')
}
} catch (error) {
next(error);
}
};

const loginHandler = async (req, res) => {
if (req.body.email && req.body.password) {
let user = await checkUser(req.body.email, req.body.password);
if (user) {
res.status(200).send({
status: 'ok',
result: {
...user,
},
authToken: createToken(user._id, user.email),
});
return;
}
}

res.status(400).send({
message: 'Invalid email or password ',
});
return;
};

const checkUserEmailHandler = async (req, res) => {
const user = await searchOne({ username: req.body.username.toLowerCase() });
if (user) {
res.status(400).send({ status: 'unavailable', message: 'Username is taken' });
return;
}
return res.status(200).send({ status: 'available', message: 'Username is available' });
};

router.post('/register', handleValidation(createUserValidate), createUserHandler);
router.post('/login', loginHandler);
// router.post('/check-username', handleValidation(validateUsername), checkUserEmailHandler);

export default router;
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import express from 'express';
import { save, update, deleteById, getById, search, count, get } from '../../services/member';
import { save, update, deleteById, getById, get, validate } from '../../services/member';
import { NotFound } from '../../common/errors';
import validate from '../../services/member/validation';
import { avatarUpload, handleValidation } from '../../middlewares/index';
import { authenticateRequest, avatarUpload, handleValidation } from '../../middlewares/index';
const router = express.Router();

const getByIdHandler = async (req, res, next) => {
try {
const id = req.params.id;
const item = await getById(id);
if (item) {
res.status(200).send(item);
res.status(200).send({
success: true,
result: item,
});
} else {
throw new NotFound('Product not found by the id: ' + id);
}
Expand All @@ -35,35 +37,11 @@ const postHandler = async (req, res, next) => {
};
}
const member = await save(newMember);
res.status(201).send(member);
} catch (error) {
return next(error, req, res);
}
};

const searchHandler = async (req, res, next) => {
try {
if (!req.body.pageSize) {
req.body.pageSize = 10;
}
if (!req.body.current) {
req.body.current = 1;
}
const result = await search(req.body);
const response = { success: true, ...result };
res.status(200).send(response);
// const response = { success: false, errorMessage: 'Super duper error handling mechanism', ...result };
// res.status(400).send(response);
} catch (error) {
return next(error, req, res);
}
};

const countHandler = async (req, res, next) => {
try {
const result = await count(req.body);
const response = { success: true, ...result };
res.status(200).send(response);
res.status(201).send({
success: true,
message: 'Create successfully',
result: member,
});
} catch (error) {
return next(error, req, res);
}
Expand Down Expand Up @@ -99,12 +77,10 @@ const getHandler = async (req, res, next) => {
}
};

router.get('/', getHandler);
router.get('/:id', getByIdHandler);
router.post('/', avatarUpload, handleValidation(validate), postHandler);
router.put('/', putHandler);
router.post('/search', searchHandler);
router.post('/count', countHandler);
router.delete('/:id', deleteHandler);
router.get('/', authenticateRequest, getHandler);
router.get('/:id', authenticateRequest, getByIdHandler);
router.post('/', authenticateRequest, avatarUpload, handleValidation(validate), postHandler);
router.put('/', authenticateRequest, putHandler);
router.delete('/:id', authenticateRequest, deleteHandler);

export default router;
8 changes: 6 additions & 2 deletions server/core/mongo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import mongoose from 'mongoose';
import dontenv from 'dotenv';
dontenv.config();

const isMongoDbUrl = Boolean(process.env.IS_MONGODB_CLOUD_URL);
const uri = isMongoDbUrl === false ? process.env.MONGODB_CLOUD_URL : `mongodb://${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`;
const isMongoDbUrl = JSON.parse(process.env.IS_MONGODB_CLOUD_URL ? process.env.IS_MONGODB_CLOUD_URL : 'false');
const uri =
isMongoDbUrl === true
? process.env.MONGODB_CLOUD_URL
: `mongodb://${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`;
console.log(uri , isMongoDbUrl)
const connectWithDb = async (): Promise<void> => {
console.log(`Connecting to mongoDB...`);
await mongoose.connect(uri);
Expand Down
3 changes: 2 additions & 1 deletion server/middlewares/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import jwt from 'jsonwebtoken';
import { GeneralError, BadRequest } from '../common/errors';
import uploader from '../common/fileupload';
import dotenv from 'dotenv';
dotenv.config();

const handleError = async (err, req, res, next) => {
if (res?.headersSent) {
Expand Down Expand Up @@ -52,7 +54,6 @@ const handleValidation = (validate) => {
const authenticateRequest = async (req, res, next) => {
let auth = req.headers['authorization'];
if (auth) {
auth = auth.replace('Bearer ', '');
jwt.verify(auth, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
res.status(401).send({
Expand Down
30 changes: 30 additions & 0 deletions server/models/User/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Schema, model } from 'mongoose';

export interface IUser {
firstName: string;
lastName: string;
email: string;
password: string;
isDelete?: boolean;
}

// schema

const UserSceme = new Schema<IUser>(
{
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, require: true , unique : true },
password : {type : String},
isDelete: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);


const User = model<IUser>('User', UserSceme);

export default User;
4 changes: 2 additions & 2 deletions server/models/member/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,6 @@ const schema = new Schema<IMember>(
);

schema.plugin(mongoosePaginate);
const Product = model<IMember>('Member', schema);
const Member = model<IMember>('Member', schema);

export default Product;
export default Member;
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// const { authenticateRequest } = require("../../common/middlewares");
import memberControler from '../../controllers/member';
import memberControler from '../../controllers/members';
import request from '../../common/request';
export default request((app) => {
app.use('/api/member', memberControler);
app.use('/api/members', memberControler);
});
5 changes: 5 additions & 0 deletions server/modules/user/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import userControler from '../../controllers/auth';
import request from '../../common/request';
export default request((app) => {
app.use('/api/user', userControler);
});
Loading

0 comments on commit fb8fc00

Please sign in to comment.