Best JavaScript code snippet using best
users.js
Source:users.js
...24 pagination.formatPagination(users, req.query.page, req.query.perPage),25 20026 );27 }).catch(err => {28 return auth.sendError(res, err.message, err.code);29 });30};31// Gets a specific user32exports.getUser = (req, res, next) => {33 logger.log('info', "[REQUEST : GET ONE USER] TRYING GET USER.", {tags: 'request,get'});34 UserModel.findByPk(req.params.userId).then(user => {35 UserModel.formatToClient(user);36 return auth.sendSuccess(res, user, 200);37 }).catch(err => {38 return auth.sendError(res, "User '" + req.params.userId + "' does not exist.", 404)39 });40};41// Edits the fields of a specific user42exports.editUser = (req, res, next) => {43 logger.log('info', "[REQUEST : EDIT ONE USER] TRYING EDIT USER.", {tags: 'request,post'});44 auth.isAuthenticated(req).then(user => {45 user.update({46 email: req.body.email,47 firstName: req.body.firstName,48 lastName: req.body.lastName,49 phoneNumber: req.body.phoneNumber50 }).then(() => {51 return auth.sendSuccess(res, { message: "User updated"}, 201);52 })53 .catch(err => {54 return auth.sendError(res, err, 500);55 });56 }).catch(err => {57 return auth.sendError(res, err.message, err.code);58 });59};60exports.createUser = (req, res, next) => {61 logger.log('info', "[REQUEST : CREATE ONE USER] TRYING CREATE USER.", {tags: 'request,post'});62 // Create the user63 UserModel.create(64 {65 id: req.body.id,66 email : req.body.email,67 password : req.body.password,68 firstName : req.body.firstName,69 lastName : req.body.lastName,70 phoneNumber : req.body.phoneNumber71 })72 .then(user => {73 TokenModel.create({74 userId : user.id,75 token: auth.generateToken()76 })77 .then(token => {78 return auth.sendSuccess(res, {token : token.token}, 201);79 })80 .catch(err => {81 return auth.sendError(res, err.errors[0].message, 400);82 });83 })84 .catch(err => {85 if (err.errors[0].path === "password")86 err.errors[0].message = "Missing field 'password'";87 if (err.errors[0].path === "PRIMARY")88 err.errors[0].message = "Id is already taken";89 if (err.errors[0].path === "email")90 err.errors[0].message = "Email is already taken";91 return auth.sendError(res, err.errors[0].message, 400);92 });93};94exports.deleteUser = (req, res, next) => {95 logger.log('info', "[REQUEST : DELETE ONE USER] TRYING DELETE USER.", {tags: 'request,delete'});96 auth.isAuthenticated(req).then(user => {97 return user.destroy();98 })99 .then(() => {100 return auth.sendSuccess(res, null, 200);101 })102 .catch(err => {103 return auth.sendError(res, err, 401);104 });105};106// Gets the pictures of a user107exports.getUserPictures = (req, res, next) => {108 UserModel.findByPk(req.params.userId).then(user => {109 if (user === null) {110 return auth.sendError(res, "User '" + req.params.userId + "' does not exist.", 404)111 } else {112 logger.log('info', "[REQUEST : GET USER PICTURES] TRYING GET USER PICTURES.", {tags: 'request,get'});113 PictureModel.findAll({114 where: {115 userId: req.params.userId116 },117 order: [118 ['created', 'DESC']119 ]120 }).then(pictures => {121 PictureModel.assignPicturesDetails(pictures).then(pictures => {122 return auth.sendSuccess(123 res,124 pagination.formatPagination(pictures, req.query.page, req.query.perPage),125 200126 );127 }).catch(err => {128 return auth.sendError(res, err, 500);129 });130 }).catch(err => {131 return auth.sendError(res, err, 500);132 });133 }134 }).catch(err => {135 return auth.sendError(res, "User '" + req.params.userId + "' does not exist.", 404)136 });137};138// Uploads a picture for a user139exports.addUserPicture = (req, res, next) => {140 logger.log('info', "[REQUEST : ADD ONE PICTURE USER] TRYING ADD PICTURE USER.", {tags: 'request,post'});141 auth.isAuthenticated(req).then(user => {142 var form = new multiparty.Form();143 form.parse(req, function(err, fields, files) {144 if (files && files.file && fields.description && fields.tags && fields.mentions) {145 const extension = path.extname(files.file[0].originalFilename);146 PictureModel.create({147 description : fields.description[0],148 extension : extension,149 userId : user.id,150 }).then(picture => {151 let tags = [];152 fields.tags.forEach(tag => {153 const nestedTags = tag.split(",");154 nestedTags.forEach(nestedTag => {155 tags.push({ value: nestedTag, pictureId: picture.id });156 });157 })158 TagModel.bulkCreate(tags).then(tags => {159 let mentions = [];160 fields.mentions.forEach(mention => {161 const nestedMentions = mention.split(",");162 nestedMentions.forEach(nestedMention => {163 mentions.push({ userId: nestedMention, pictureId: picture.id });164 });165 })166 MentionModel.bulkCreate(mentions).then(mentions => {167 files.file[0].originalFilename = picture.id + extension;168 const errCallback = (err) => {169 return auth.sendError(res, 'Cannot upload file', 500);170 }171 const succCallback = (url) => {172 return auth.sendSuccess(res, {id: picture.id}, 200);173 }174 service.addUserPicture(picture, files.file[0], fields, errCallback, succCallback);175 }).catch(err => {176 return auth.sendError(res, 'Cannot insert mentions', 500);177 })178 }).catch(err => {179 return auth.sendError(res, 'Cannot insert tags', 500);180 });181 }).catch(err => {182 return auth.sendError(res, err, 500);183 });184 } else {185 return auth.sendError(res, 'Missing fields', 400);186 }187 });188 }).catch(err => {189 return auth.sendError(res, err.message, err.code);190 });191};192// Gets a single picture193exports.getUserPicture = (req, res, next) => {194 logger.log('info', "[REQUEST : GET ONE PICTURE] TRYING GET ONE PICTURE.", {tags: 'request,get'});195 PictureModel.findByPk(req.params.pictureId).then(picture => {196 if (isNaN(req.params.pictureId)) {197 return auth.sendError(res, "Provided type for pictureId is invalid.", 400)198 }199 if (picture === null || picture.userId !== req.params.userId) {200 return auth.sendError(res, "Picture '" + req.params.pictureId + "' does not exist for user '" + req.params.userId + "'.", 404);201 } else {202 PictureModel.assignPictureDetails(picture).then(picture => {203 return auth.sendSuccess(res, picture, 200);204 }).catch(err => {205 return auth.sendError(res, err, 500);206 });207 }208 }).catch(err => {209 return auth.sendError(res, "Missing parameter", 400);210 })211};212// Edits the fields of a picture for a user213exports.editUserPicture = (req, res, next) => {214 logger.log('info', "[REQUEST : EDIT USER PICTURE] TRYING EDIT ONE PICTURE.", {tags: 'request,put'});215 auth.isAuthenticated(req).then(user => {216 if (isNaN(req.params.pictureId)) {217 return auth.sendError(res, "Provided type for pictureId is invalid.", 400)218 }219 PictureModel.findByPk(req.params.pictureId).then(picture => {220 if (req.params.userId !== picture.userId) {221 return auth.sendError(res, "Picture '" + req.params.pictureId + "' does not exist for user '" + req.params.userId + "'.", 404)222 }223 if (req.body.description === null ||req.body.tags === null || req.body.mentions === null) {224 return auth.sendError(res, "Missing parameter", 400)225 }226 PictureModel.update(227 {228 description : req.body.description229 },230 {231 where: {232 id: req.params.pictureId233 }234 }235 ).then(() => {236 let tags = [];237 req.body.tags.forEach(tag => {238 tags.push({ value: tag, pictureId: picture.id });239 })240 TagModel.destroy({241 where: {242 pictureId: picture.id243 }244 }).then(() => {245 TagModel.bulkCreate(tags).then(tags => {246 let mentions = [];247 req.body.mentions.forEach(mention => {248 mentions.push({ userId: mention, pictureId: picture.id });249 })250 MentionModel.destroy({251 where : {252 pictureId: picture.id253 }254 }).then(() => {255 MentionModel.bulkCreate(mentions).then(mentions => {256 PictureModel.formatToClient(picture, mentions, tags);257 return auth.sendSuccess(res, picture, 201);258 }).catch(err => {259 return auth.sendError(res, err, 500);260 })261 }).catch(err => {262 return auth.sendError(res, err, 500);263 });264 }).catch(err => {265 return auth.sendError(res, err, 500);266 });267 }).catch(err => {268 return auth.sendError(res, err, 500);269 });270 }).catch(err => {271 return auth.sendError(res, "Missing parameter", 400);272 })273 }).catch(err => {274 return auth.sendError(res, "Picture '" + req.params.pictureId + "' does not exist for user '" + req.params.userId + "'.", 404);275 })276 }).catch(err => {277 return auth.sendError(res, err.message, err.code);278 });279};280// Deletes a picture for a user281exports.deleteUserPicture = (req, res, next) => {282 logger.log('info', "[REQUEST : DELETE USER PICTURE] TRYING DELETE ONE PICTURE.", {tags: 'request,delete'});283 auth.isAuthenticated(req).then(user => {284 if (isNaN(req.params.pictureId)) {285 return auth.sendError(res, "Provided type for pictureId is invalid.", 400)286 }287 PictureModel.findByPk(req.params.pictureId).then(picture => {288 if (req.params.userId !== picture.userId) {289 return auth.sendError(res, "Picture '" + req.params.pictureId + "' does not exist for user '" + req.params.userId + "'.", 404)290 }291 const errCallback = (err) => {292 return auth.sendError(res, 'Unable to delete the specified file', 401);293 };294 const succCallback = () => {295 CommentModel.destroy({296 where: {297 pictureId: picture.id298 }299 });300 LikeModel.destroy({301 where: {302 pictureId: picture.id303 }304 });305 PictureModel.destroy({306 where: {307 id: picture.id308 }309 }).then(() => {310 return auth.sendSuccess(res, null, 204);311 })312 .catch(err => {313 return auth.sendError(res, err, 500);314 });315 };316 service.deleteUserPicture(picture, errCallback, succCallback);317 }).catch(err => {318 return auth.sendError(res, "Picture '" + req.params.pictureId + "' does not exist for user '" + req.params.userId + "'.", 404);319 })320 }).catch(err => {321 return auth.sendError(res, err.message, err.code);322 });323};324// Deletes all pictures for a user325exports.deleteUserPictures = (req, res, next) => {326 logger.log('info', "[REQUEST : DELETE USER PICTURES] TRYING DELETE ALL PICTURES.", {tags: 'request,delete'});327 auth.isAuthenticated(req).then(user => {328 PictureModel.findAll({329 where : {330 userId: user.id331 }332 }).then(pictures => {333 if (!auth.isDefined(pictures)) {334 throw "No pictures"335 }336 const errCallback = (err) => {337 return auth.sendError(res, 'Unable to delete files for user ' + user.id, 501);338 };339 const succCallback = () => {340 PictureModel.destroy({341 where: {342 userId: user.id343 }344 }).then(() => {345 return auth.sendSuccess(res, null, 204);346 })347 .catch(err => {348 return auth.sendError(res, err, 500);349 });350 };351 service.deleteUserPictures(pictures, errCallback, succCallback);352 }).catch(err => {353 return auth.sendError(res, "No pictures found for user '" + user.id + "'.", 204);354 })355 }).catch(err => {356 return auth.sendError(res, err.message, err.code);357 });358};359exports.deleteUserComment = (req, res, next) => {360 let socket = req.app.get('socket');361 auth.isAuthenticated(req).then(user => {362 CommentModel.find({363 where : {364 id: req.params.id,365 pictureId: req.params.pictureId366 }367 }).then(comment => {368 NotificationModel.destroy({369 where: {370 commentId: comment.id371 }372 });373 CommentModel.destroy({374 where: {375 id: comment.id,376 pictureId: comment.pictureId377 }378 }).then(() => {379 socket.emit('GET_COMMENTS', {data : comment.id, delete : true });380 socket.emit(comment.ownerId);381 return auth.sendSuccess(res, null, 204);382 })383 .catch(err => {384 return auth.sendError(res, err, 500);385 });386 }).catch(err => {387 return auth.sendError(res, "No pictures found for user '" + user.id + "'.", 204);388 })389 }).catch(err => {390 return auth.sendError(res, err.message, err.code);391 });392};393exports.addComment = (req, res, next) => {394 let socket = req.app.get('socket');395 auth.isAuthenticated(req).then(user => {396 CommentModel.create(397 {398 userId: user.id,399 pictureId: req.params.pictureId,400 message: req.body.message,401 ownerId: req.body.ownerId,402 })403 .then(comment => {404 socket.emit('GET_COMMENTS', {data: comment.id, delete: false});405 if (req.params.userId !== req.body.ownerId) {406 PictureModel.findOne({407 where: {408 id: req.params.pictureId409 }410 }).then(picture => {411 PictureModel.formatToClient(picture, [], []);412 NotificationModel.create({413 userId: req.body.ownerId,414 url: '/profil/' + req.body.ownerId + '?search=' + req.params.pictureId,415 message: req.params.userId + ' a commenté votre photo',416 isRead: false,417 pictureUrl : picture.dataValues.url["40"],418 userPictureUrl : user.pictureUrl,419 commentId : comment.id420 }421 ).then(response => { socket.emit(req.body.ownerId) });422 });423 }424 return auth.sendSuccess(res, {comment}, 200);425 })426 .catch(err => {427 return auth.sendError(res, err.errors[0].message, 400);428 });429 }).catch(err => {430 return auth.sendError(res, err.message, err.code);431 });432};433exports.getNotifications = (req, res, next) => {434 NotificationModel.findAll({ where: {435 userId: req.params.userId,436 },437 order: [438 ['id', 'DESC']439 ]}).then(notifications => {440 return auth.sendSuccess(res, {items : notifications}, 200);441 })442 .catch(err => {443 return auth.sendError(res, err, 400);444 });445};446exports.setReadNotifications = (req, res, next) => {447 auth.isAuthenticated(req).then(user => {448 NotificationModel.find({449 where: {450 userId: user.id,451 id: req.params.id452 }453 }).then(notification => {454 notification.update({isRead: 1}).then(function () {455 NotificationModel.findAll({ where: {456 userId: user.id457 }, order: [458 ['id', 'DESC']459 ]}).then(notifications => {460 return auth.sendSuccess(res, {items : notifications}, 200);461 })462 .catch(err => {463 return auth.sendError(res, err, 400);464 });465 });466 })467 .catch(err => {468 return auth.sendError(res, err, 400);469 });470 }).catch(err => {471 return auth.sendError(res, err.message, err.code);472 });473};474exports.addLike = (req, res, next) => {475 let socket = req.app.get('socket');476 auth.isAuthenticated(req).then(user => {477 LikeModel.create(478 {479 userId: user.id,480 pictureId: req.params.pictureId,481 ownerId: req.body.ownerId482 })483 .then(comment => {484 socket.emit('GET_LIKES', {data: comment.id, delete: false});485 if (req.params.userId !== req.body.ownerId) {486 PictureModel.findOne({487 where: {488 id: req.params.pictureId489 }490 }).then(picture => {491 PictureModel.formatToClient(picture, [], []);492 console.log(picture.dataValues);493 NotificationModel.create({494 userId: req.body.ownerId,495 url: '/profil/' + req.body.ownerId + '?search=' + req.params.pictureId,496 message: req.params.userId + ' a aimé votre photo',497 isRead: false,498 pictureUrl : picture.dataValues.url["40"],499 userPictureUrl : user.pictureUrl,500 likeId : comment.id501 }).then(response => { socket.emit(req.body.ownerId) });502 });503 }504 return auth.sendSuccess(res, {comment}, 200);505 })506 .catch(err => {507 return auth.sendError(res, err.errors[0].message, 400);508 });509 }).catch(err => {510 return auth.sendError(res, err.message, err.code);511 });512};513exports.deleteUserLike = (req, res, next) => {514 let socket = req.app.get('socket');515 auth.isAuthenticated(req).then(user => {516 LikeModel.find({517 where : {518 id: req.params.id,519 pictureId: req.params.pictureId520 }521 }).then(comment => {522 NotificationModel.destroy({523 where: {524 likeId: comment.id525 }526 });527 LikeModel.destroy({528 where: {529 id: comment.id,530 pictureId: comment.pictureId531 }532 }).then(() => {533 socket.emit('GET_LIKES', {data : comment.id, delete : true });534 socket.emit(comment.ownerId);535 return auth.sendSuccess(res, null, 204);536 })537 .catch(err => {538 return auth.sendError(res, err, 500);539 });540 }).catch(err => {541 return auth.sendError(res, "No pictures found for user '" + user.id + "'.", 404);542 })543 }).catch(err => {544 return auth.sendError(res, err.message, err.code);545 });...
authenticate.js
Source:authenticate.js
...14var invalid_token = [];1516router.post('/login', function(req, res, next) {17 if (req.body.username == undefined || req.body.username == '') {18 _global.sendError(res, null, 'Username is required');19 return;20 }21 if (req.body.password == undefined || req.body.password == '') {22 _global.sendError(res, null, 'Password is required');23 return;24 }25 var username = req.body.username;26 var password = req.body.password;27 pool_postgres.connect(function(error, connection, done) {28 if (error) {29 _global.sendError(res, error.message);30 done();31 return console.log(error);32 }3334 connection.query(format(`SELECT * FROM users WHERE email LIKE %L`, username + '@%'), function(error, result, fields) {35 if (error) {36 _global.sendError(res, error.message);37 done();38 return console.log(error);39 }40 //check user exist41 if (result.rowCount == 0) {42 _global.sendError(res, null, "Username not found");43 done();44 return console.log("Username is not existed");45 }46 for(var i = 0 ; i < result.rowCount ; i++){47 var password_hash = result.rows[i].password;48 if(password_hash != null && password_hash != ''){49 if (bcrypt.compareSync(password, password_hash)) {50 var token = jwt.sign(result.rows[i], _global.jwt_secret_key, { expiresIn: _global.jwt_expire_time });51 res.send({ result: 'success', token: token, user: result.rows[i] });52 done();53 return54 }55 }56 }57 _global.sendError(res, null, "Wrong password");58 done();59 return console.log("Wrong password");60 });61 });62});6364router.post('/logout', function(req, res, next) {65 var token = req.body.token;6667 res.send({result : 'success'});68});6970router.post('/forgot-password', function(req, res, next) {71 if (req.body.email == undefined || req.body.email == '') {72 _global.sendError(res, null, 'Email is required');73 return;74 }75 var email = req.body.email;76 pool_postgres.connect(function(error, connection, done) {77 if (error) {78 _global.sendError(res, error.message);79 done();80 return console.log(error);81 } else {82 connection.query(format(`SELECT * FROM users WHERE email = %L LIMIT 1`, email), function(error, result, fields) {83 if (error) {84 _global.sendError(res, error.message);85 done();86 return console.log(error);87 }88 //check email exist89 if (result.rowCount == 0) {90 _global.sendError(res, null, 'Email not found');91 done();92 return console.log('Email is not existed');93 }94 if (result.rows[0].password == null || result.rows[0].password == undefined) {95 _global.sendError(res, null, "Old password not found. Please use the register link in your email to set up your account.");96 done();97 return console.log("Old password not found. Please use the register link in your email to set up your account.");98 }99 var token = jwt.sign({ email: email }, _global.jwt_secret_key, { expiresIn: _global.jwt_reset_password_expire_time });100 var link = _global.host + '/forgot-password;token=' + token;101 _global.sendMail(102 '"Giáo vụ"',103 email,104 'Password reset request',105 'Hi,'+ student.name + '\r\n' + 106 'Hi,\r\n' + 107 'A password reset was requested for your account.To confirm this request, and set a new password for your account, please go to the following web address: \r\n\r\n' +108 link + 109 '\r\n(This link is valid for 30 minutes from the time this reset was first requested)\r\n' +110 'If this password reset was not requested by you, no action is needed.\r\n' +111 'If you need help, please contact the site administrator,\r\n' +112 'Admin User \r\n\r\n' +113 'admin@fit.hcmus.edu.vn'114 );115 res.send({ result: 'success' });116 done();117 });118 }119 });120});121122router.post('/reset-password-check', function(req, res, next) {123 if (req.body.token == undefined || req.body.token == '') {124 _global.sendError(res, null, 'Token is required');125 return;126 }127 var token = req.body.token;128 if (token) {129 jwt.verify(token, _global.jwt_secret_key, function(error, decoded) {130 if (error) {131 //return res.json(error);132 if (error.name == 'TokenExpiredError') {133 _global.sendError(res, null, 'The password reset link you used is more than 30 minutes old and has expired. Please initiate a new password reset.');134 return console.log('The password reset link you used is more than 30 minutes old and has expired. Please initiate a new password reset.');135 }136 _global.sendError(res, null, 'Invalid token');137 return console.log('Invalid token');138139 } else {140 res.send({ result: 'success' });141 done();142 }143 });144 }145});146147router.post('/reset-password', function(req, res, next) {148 var token = req.body.token || req.query.token || req.headers['x-access-token'];149 if (token) {150 jwt.verify(token, _global.jwt_secret_key, function(error, decoded) {151 if (error) {152 //return res.json(error);153 if (error.name == 'TokenExpiredError') {154 return res.status(401).send({155 success: false,156 message: error.message157 });158 }159 } else {160 if (req.body.password == undefined || req.body.password == '') {161 _global.sendError(res, null, 'Password is required');162 return;163 }164 if (req.body.confirm_password == undefined || req.body.confirm_password == '') {165 _global.sendError(res, null, 'Confirm Password is required');166 return;167 }168 var password = req.body.password;169 var confirm_password = req.body.confirm_password;170 if (password != confirm_password) {171 _global.sendError(res, null, 'Password and Confirm password must be the same');172 return;173 }174 var email = decoded.email;175 pool_postgres.connect(function(error, connection, done) {176 if (error) {177 _global.sendError(res, error.message);178 done();179 return console.log(error);180 }181 connection.query(format(`UPDATE users SET password = %L WHERE email = %L`, bcrypt.hashSync(password, 10),email), function(error, rows, fields) {182 if (error) {183 _global.sendError(res, error.message);184 done();185 return console.log(error);186 }187 res.send({ result: 'success'});188 done();189 });190 });191 }192 });193 } else {194 return res.status(401).send({195 success: false,196 message: 'No token provided.'197 });198 }199});200201router.post('/register-check', function(req, res, next) {202 if (req.body.token == undefined || req.body.token == '') {203 _global.sendError(res, null, 'Token is required');204 return;205 }206 var token = req.body.token;207 if (token) {208 jwt.verify(token, _global.jwt_secret_key, function(error, decoded) {209 if (error) {210 //return res.json(error);211 if (error.name == 'TokenExpiredError') {212 _global.sendError(res, null, 'The password reset link you used is more than 7 days old and has expired.');213 return console.log('The password reset link you used is more than 7 days old and has expired.');214 }215 _global.sendError(res, null, 'Invalid token');216 return console.log('Invalid token');217 } else {218 pool_postgres.connect(function(error, connection, done) {219 if (error) {220 _global.sendError(res, error.message);221 done();222 return console.log(error);223 }224 connection.query(format(`SELECT * FROM users WHERE email = %L LIMIT 1`, decoded.email), function(error, result, fields) {225 if (error) {226 _global.sendError(res, error.message);227 done();228 return console.log(error);229 }230 //check password exist231 if (result.rowCount == 0) {232 _global.sendError(res, null, "Account not found.");233 done();234 return console.log("Account not found.");235 }236 res.send({ result: 'success' , user : result.rows[0]});237 done();238 });239 });240 241 }242 });243 }244});245246router.post('/register', function(req, res, next) {247 var token = req.body.token || req.query.token || req.headers['x-access-token'];248 if (token) {249 jwt.verify(token, _global.jwt_secret_key, function(error, decoded) {250 if (error) {251 if (error.name == 'TokenExpiredError') {252 return res.status(401).send({253 success: false,254 message: error.message255 });256 }257 } else {258 if (req.body.phone == undefined || isNaN(req.body.phone)) {259 _global.sendError(res, null, "Invalid Phone Number");260 return;261 }262 if (req.body.password == undefined || req.body.password == '') {263 _global.sendError(res, null, 'Password is required');264 return;265 }266 if (req.body.first_name == undefined || req.body.first_name == '') {267 _global.sendError(res, null, "First name is required");268 return;269 }270 if (req.body.last_name == undefined || req.body.last_name == '') {271 _global.sendError(res, null, "Last name is required");272 return;273 }274 if (req.body.confirm_password == undefined || req.body.confirm_password == '') {275 _global.sendError(res, null, 'Confirm Password is required');276 return;277 }278 var first_name = req.body.first_name;279 var last_name = req.body.last_name;280 var phone = req.body.phone;281 var avatar = req.body.avatar;282 var password = req.body.password;283 var confirm_password = req.body.confirm_password;284 if (password != confirm_password) {285 _global.sendError(res, null, 'Password and Confirm password must be the same');286 return;287 }288 var email = decoded.email;289 pool_postgres.connect(function(error, connection, done) {290 if (error) {291 _global.sendError(res, error.message);292 done();293 return console.log(error);294 }295 connection.query(format(`UPDATE users SET first_name = %L, last_name = %L, phone = %L, avatar = %L, password = %L 296 WHERE email = %L`, first_name, last_name, phone, avatar, bcrypt.hashSync(password, 10),email), function(error, rows, fields) {297 if (error) {298 _global.sendError(res, error.message);299 done();300 return console.log(error);301 }302 res.send({ result: 'success'});303 done();304 });305 });306 }307 });308 } else {309 return res.status(401).send({310 success: false,311 message: 'No token provided.'312 });
...
userHandler.js
Source:userHandler.js
...27 };28 const result = await dynamodb.scan(Exsting).promise();29 console.log("items", result.Items);30 if (result.Items.length > 0) {31 return responsehelper.sendError(event, 400, "User already exsist.");32 }33 await UserModel.createUser(data);34 return responsehelper.sendSucess(event, "success", { email, password });35 } catch (e) {36 console.log(e);37 return responsehelper.sendError(38 event,39 500,40 "something wrong register user",41 { email, password }42 );43 }44 },45 userLogin: async (event) => {46 const dynamodb = new AWS.DynamoDB.DocumentClient();47 const { email, password } = JSON.parse(event.body);48 try {49 const data = {50 email,51 password,52 };53 const Exsting = {54 TableName: "userTables",55 FilterExpression: "email = :e",56 ExpressionAttributeValues: { ":e": data.email },57 };58 const result = await dynamodb.scan(Exsting).promise();59 if (result.Items.length == 0) {60 return responsehelper.sendError(event, 401, "User not exsist");61 }62 const id = result.Items.map((res) => res.id);63 const token = await jwt.sign({ id: id }, "process.env.JWT_Token");64 return responsehelper.sendSucess(event, "success", {65 token,66 user: {67 id: id,68 },69 });70 } catch (e) {71 return responsehelper.sendError(72 event,73 500,74 "something wrong login user",75 { email, password }76 );77 }78 },79 authLogin: async (event) => {80 const dynamodb = new AWS.DynamoDB.DocumentClient();81 const { email, password } = JSON.parse(event.body);82 try {83 const data = {84 email,85 password,86 };87 const Exsting = {88 TableName: "userTables",89 FilterExpression: "email = :e",90 ExpressionAttributeValues: { ":e": data.email },91 };92 const result = await dynamodb.scan(Exsting).promise();93 if (result.Items.length == 0) {94 return responsehelper.sendError(event, 400, "User not exsist");95 }96 const verifyPassword = result.Items.filter((res) => res.password === password);97 console.log("verify password is ",verifyPassword)98 if (verifyPassword.length == 0) {99 return responsehelper.sendError(event, 400, "invalid email or password");100 }101 102 103 const verifyed = result.Items.filter((res) => res.verifyed === true);104 if (verifyed.length == 0) {105 return responsehelper.sendError(event, 400, "user not verifyed");106 }107 const id = result.Items.map((res) => res.id);108 const token = await jwt.sign({ id: id }, "process.env.JWT_Token");109 return responsehelper.sendSucess(event, "success", {110 token,111 user: {112 id: id,113 },114 });115 } catch (e) {116 return responsehelper.sendError(117 event,118 500,119 "something wrong auth login user",120 { email, password }121 );122 }123 },124 verifyUser: async (event) => {125 const dynamodb = new AWS.DynamoDB.DocumentClient();126 const { id, email, password, verifycode } = JSON.parse(event.body);127 try {128 console.log(event.user);129 const data = {130 id: event.user,131 email,132 password,133 };134 const params = {135 TableName: "userTables",136 Key: { id: event.user },137 };138 const result = await dynamodb.scan(params).promise();139 if (result.Items.length == 0) {140 return responsehelper.sendError(event, 401, "User not exsist");141 }142 const item = await result.Items.find(143 (res) => res.verifycode === verifycode144 );145 console.log("item iss", item);146 if (!item) {147 return responsehelper.sendError(148 event,149 401,150 "Invalid verfication code "151 );152 }153 let UpdatedUser;154 let A = event.user;155 let uid = A[0];156 console.log("fetch id:", uid);157 const results = await dynamodb158 .update({159 TableName: "userTables",160 Key: { id: uid },161 UpdateExpression: "set verifyed= :verifyed",162 //ConditionExpression: 'attribute_exists(id)',163 ExpressionAttributeValues: {164 ":verifyed": true,165 },166 ReturnValues: "ALL_NEW",167 })168 .promise();169 UpdatedUser = results.Attributes;170 //await UserModel.createUser(uid)171 return responsehelper.sendSucess(172 event,173 "succss verfication",174 UpdatedUser175 );176 } catch (e) {177 console.log("error:", e);178 return responsehelper.sendError(179 event,180 500,181 "something wrong verifcation",182 e183 );184 }185 },186 deleteData: async (event) => {187 try {188 const { id } = event.pathParameters;189 await UserModel.deleteUser(id);190 return responsehelper.sendSucess(event, "user deleted successfully ");191 } catch (e) {192 console.log(e);193 return responsehelper.sendError(event, 500, "user not auth", e);194 }195 },196 forgotPassword: async (event) => {197 const { email } = JSON.parse(event.body);198 const dynamodb = new AWS.DynamoDB.DocumentClient();199 try {200 const Exsting = {201 TableName: "userTables",202 FilterExpression: "email = :e",203 ExpressionAttributeValues: { ":e": email },204 };205 const result = await dynamodb.scan(Exsting).promise();206 console.log("user", result.Items);207 if (result.Items.length == 0) {208 return responsehelper.sendError(event, 400, "User not exsist ");209 }210 const findid = result.Items.map((res) => res.id);211 const getid = findid[0];212 console.log("fetch id:", getid);213 await UserModel.forgotUser(getid);214 return responsehelper.sendSucess(event, "success ".getid);215 } catch (e) {216 console.log(e);217 return responsehelper.sendError(event, 500, "Something wrong", e);218 }219 },220 resetPassword: async (event) => {221 const { password, expireToken, forgottoken, email } = JSON.parse(222 event.body223 );224 const dynamodb = new AWS.DynamoDB.DocumentClient();225 try {226 let A = event.user;227 let uid = A[0];228 const data = {229 uid,230 password,231 expireToken,232 forgottoken,233 email,234 };235 const Exsting = {236 TableName: "userTables",237 FilterExpression: "forgottoken = :f",238 ExpressionAttributeValues: { ":f": data.forgottoken },239 };240 const result = await dynamodb.scan(Exsting).promise();241 console.log("user", result);242 if (result.Items.length === 0) {243 return responsehelper.sendError(event, 400, "invalid token ");244 }245 console.log("user: ", result);246 await UserModel.resetUser(data);247 return responsehelper.sendSucess(event, " password reset success ");248 } catch (e) {249 console.log(e);250 return responsehelper.sendError(event, 500, "Something wrong", e);251 }252 },253 fetchUsers: async (event) => {254 try {255 const result = await UserModel.fetchUser();256 return responsehelper.sendSucess(257 event,258 " password reset success ",259 result260 );261 } catch (e) {262 console.log(e);263 return responsehelper.sendError(event, 500, "Something wrong", e);264 }265 },266 fetchId: async (event) => {267 try {268 const result = await UserModel.fetchUserId();269 return responsehelper.sendSucess(event, " users ", result);270 } catch (e) {271 console.log(e);272 return responsehelper.sendError(event, 500, "Something wrong", e);273 }274 },275 validateID: async (event) => {276 const dynamodb = new AWS.DynamoDB.DocumentClient();277 try {278 const token =279 (await event.headers) &&280 (event.headers["Authorization"] || event.headers["Authorization"]);281 if (!token) {282 return responsehelper.sendError(event, 401, "invalid token ");283 }284 let verify = jwt.verify(token, "process.env.JWT_Token");285 if (!verify) {286 return responsehelper.sendError(event, 401, "invalid token ");287 }288 let A = event.user;289 let uid = A[0];290 console.log("userid", uid);291 const result = await dynamodb292 .get({ TableName: "userTables", Key: { id: uid } })293 .promise();294 console.log("my result", result);295 if (result.Item.verifyed === false) {296 return responsehelper.sendError(event, 401, "invalid verfication ");297 }298 return responsehelper.sendSucess(event, " validate success ", true);299 } catch (e) {300 console.log("err", e);301 return responsehelper.sendError(event, 500, "Something wrong", e);302 }303 },304 sendEmailApi: async (event) => {305 console.log("event", event);306 const { to, from, subject, text } = JSON.parse(event.body);307 if (!to || !from || !subject || !text) {308 return responsehelper.sendError(309 event,310 500,311 "to, from, subject and text are all required in the body"312 );313 }314 const params = {315 Destination: {316 ToAddresses: [to],317 },318 Message: {319 Body: {320 Text: { Data: text },321 },322 Subject: { Data: subject },323 },324 Source: from,325 };326 try {327 await SES.sendEmail(params).promise();328 return responsehelper.sendSucess(event, " email send success ");329 } catch (error) {330 console.log("error sending email ", error);331 return responsehelper.sendError(event, 400, "faild to send");332 }333 },334};...
Using AI Code Generation
1var BestPractice = require('./BestPractice');2var bestPractice = new BestPractice();3bestPractice.sendError('test4.js', 'this is a test error');4var BestPractice = require('./BestPractice');5var bestPractice = new BestPractice();6bestPractice.sendError('test5.js', 'this is a test error');7var BestPractice = require('./BestPractice');8var bestPractice = new BestPractice();9bestPractice.sendError('test6.js', 'this is a test error');10var BestPractice = require('./BestPractice');11var bestPractice = new BestPractice();12bestPractice.sendError('test7.js', 'this is a test error');13var BestPractice = require('./BestPractice');14var bestPractice = new BestPractice();15bestPractice.sendError('test8.js', 'this is a test error');16var BestPractice = require('./BestPractice');17var bestPractice = new BestPractice();18bestPractice.sendError('test9.js', 'this is a test error');19var BestPractice = require('./BestPractice');20var bestPractice = new BestPractice();21bestPractice.sendError('test10.js', 'this is a test error');22var BestPractice = require('./BestPractice');23var bestPractice = new BestPractice();24bestPractice.sendError('test11.js', 'this is a test error');25var BestPractice = require('./BestPractice');26var bestPractice = new BestPractice();27bestPractice.sendError('test12.js', 'this is a test error');28var BestPractice = require('./BestPractice');29var bestPractice = new BestPractice();30bestPractice.sendError('test13.js', 'this
Using AI Code Generation
1var BestPracticeError = require('./BestPracticeError');2var error = new BestPracticeError('Test error');3error.sendError();4var BestPracticeError = function(message) {5 this.message = message;6 this.name = 'BestPracticeError';7 this.sendError = function() {8 console.log('Sending error ' + this.message);9 }10}11BestPracticeError.prototype = new Error();12BestPracticeError.prototype.constructor = BestPracticeError;13module.exports = BestPracticeError;14var BestPracticeError = require('./BestPracticeError');15var error = new BestPracticeError('Test error');16error.sendError();17var BestPracticeError = function(message) {18 this.message = message;19 this.name = 'BestPracticeError';20}21BestPracticeError.prototype = new Error();22BestPracticeError.prototype.constructor = BestPracticeError;23BestPracticeError.prototype.sendError = function() {24 console.log('Sending error ' + this.message);25}26module.exports = BestPracticeError;27var BestPracticeError = require('./BestPracticeError');28var error = new BestPracticeError('Test error');29error.sendError();30var BestPracticeError = function(message) {31 this.message = message;32 this.name = 'BestPracticeError';33}34BestPracticeError.prototype = new Error();35BestPracticeError.prototype.constructor = BestPracticeError;
Using AI Code Generation
1var BestError = require('./BestError.js');2var error = new BestError('This is an error');3error.sendError();4var BestError = require('./BestError.js');5var error = new BestError('This is an error');6error.sendError('console');7var BestError = require('./BestError.js');8var error = new BestError('This is an error');9error.sendError('console', 'This is an error');10var BestError = require('./BestError.js');11var error = new BestError('This is an error');12error.sendError('console', 'This is an error', 'This is an error');13var BestError = require('./BestError.js');14var error = new BestError('This is an error');15error.sendError('console', 'This is an error', 'This is an error', 'This is an error');16var BestError = require('./BestError.js');17var error = new BestError('This is an error');18error.sendError('console', 'This is an error', 'This is an error', 'This is an error', 'This is an error');19var BestError = require('./BestError.js');20var error = new BestError('This is an error');21error.sendError('console', 'This is an error', 'This is an error', 'This is an error', 'This is an error', 'This is an error');22var BestError = require('./BestError.js');23var error = new BestError('This is an error');
Using AI Code Generation
1var BestPracticeError = require('./BestPracticeError');2var err = new BestPracticeError('test4', 'error in test4.js', 'error message');3err.sendError();4var util = require('util');5var EventEmitter = require('events').EventEmitter;6function BestPracticeError(fileName, methodName, message) {7 this.fileName = fileName;8 this.methodName = methodName;9 this.message = message;10}11util.inherits(BestPracticeError, EventEmitter);12BestPracticeError.prototype.sendError = function () {13 this.emit('error', this);14};15module.exports = BestPracticeError;
Using AI Code Generation
1var bestRestaurants = require('./bestRestaurants');2var br = new bestRestaurants.BestRestaurants();3br.sendError('This is an error');4console.log('test4.js is done');5var BestRestaurants = function() {6 this.sendError = function(msg) {7 console.log('Error: ' + msg);8 };9};10exports.BestRestaurants = BestRestaurants;
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!