How to use updateUser method in qawolf

Best JavaScript code snippet using qawolf

agentprofile.component.ts

Source:agentprofile.component.ts Github

copy

Full Screen

1import { Component, OnInit } from '@angular/core';2import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';3import { Router, ActivatedRoute, NavigationEnd } from "@angular/router";4import { EgazeService } from '../../services/egaze.service';5import { SessionstorageService } from '../../services/sessionstorage.service';6import{ AppConstants} from '../../services/constants'7@Component({8 selector: 'app-agentprofile',9 templateUrl: './agentprofile.component.html',10 styleUrls: ['./agentprofile.component.css']11})12export class AgentprofileComponent implements OnInit {13 isEditDisabled: boolean = false;14 userchangepwdflag: boolean = false;15 userEditprofileFlag: boolean = false;16 errorMsg: any;17 updateuserForm: FormGroup;18 submitted: boolean = false;19 isLoading: boolean = false;20 isLoaderdiv: boolean = false;21 updateuserProfilestatus: any;22 updateuserProfile: any;23 user: any;24 updateuserNewpwdForm: FormGroup;25 profilechndResultMsg: any;26 resultMsg: any;27 email: any;28 mobileNo: any;29 showText: boolean;30 showIconEye: boolean = false;31 hideIconEye: boolean = false;32 showText1: boolean;33 showIconEye1: boolean = false;34 hideIconEye1: boolean = false;35 showText2: boolean;36 showIconEye2: boolean = false;37 hideIconEye2: boolean = false;38 constructor(private formBuilder: FormBuilder, private EgazeService: EgazeService, private sessionstorageService: SessionstorageService, ) {39 // this.user = JSON.parse(this.sessionstorageService.getUserDetails() + "");40 debugger;41 // this.getsaveprofile();42 this.showText = false;43 this.showIconEye = false;44 this.hideIconEye = true;45 this.showText1 = false;46 this.showIconEye1 = false;47 this.hideIconEye1 = true;48 this.showText2 = false;49 this.showIconEye2 = false;50 this.hideIconEye2 = true;51 }52 passwordConfirming(c: AbstractControl): any {53 if (!c.parent || !c) return;54 const pwd = c.parent.get('newpwd');55 const cpwd = c.parent.get('confirmpwd')56 if (!pwd || !cpwd) return;57 if (pwd.value !== cpwd.value) {58 return { notSame: true };59 }60 }61 pswdstrong(control: AbstractControl): any {62 // alert(control.value)63 let hasNumber = /\d/.test(control.value);64 let hasUpper = /[A-Z]/.test(control.value);65 let hasLower = /[a-z]/.test(control.value);66 //console.log('Num, Upp, Low', hasNumber, hasUpper, hasLower);67 const valid = hasNumber && hasUpper && hasLower;68 if (!valid) {69 // return what´s not valid70 return { pwdstrong: true };71 }72 return ;73 }74 ngOnInit() {75 var emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;76 this.isEditDisabled = false;77 this.userchangepwdflag = true;78 this.userEditprofileFlag = false;79 this.updateuserProfilestatus = '';80 this.profilechndResultMsg = '';81 this.updateuserForm = this.formBuilder.group({82 firstName: ['', [Validators.required, Validators.minLength(2)]],83 middleName: [''],84 lastName: ['', [Validators.required, Validators.minLength(2)]],85 // email: [null],86 // mobileNumber: [null],87 address1: ['', Validators.minLength(6)],88 address2: ['', Validators.minLength(6)],89 address3: [''],90 city: [''],91 state: [''],92 zipCode: ['', Validators.minLength(4)],93 country: [''],94 description: ['']95 });96 this.updateuserNewpwdForm = this.formBuilder.group({97 oldpwd: ['', [Validators.required, Validators.minLength(4),this.pswdstrong]],98 newpwd: ['', [Validators.required, Validators.minLength(4),this.pswdstrong]],99 confirmpwd: ['', [Validators.required, Validators.minLength(4), this.passwordConfirming,this.pswdstrong]],100 });101 debugger;102 this.user = JSON.parse(this.sessionstorageService.getUserDetails() + "");103 this.getsaveprofile();104 }105 get feditP() { return this.updateuserForm.controls }106 get fpwdP() { return this.updateuserNewpwdForm.controls }107 profileeditFun() {108 if(!this.isEditDisabled)109 this.isEditDisabled = true;110 else111 this.isEditDisabled = false;112 this.userchangepwdflag = true;113 this.userEditprofileFlag = false;114 this.errorMsg = '';115 }116 profileChangepwdFun() {117 if(this.isEditDisabled)118 this.isEditDisabled = false;119 else120 this.isEditDisabled = true;121 this.isEditDisabled = !this.isEditDisabled;122 this.submitted = false;123this.updateuserProfilestatus="";124 this.userchangepwdflag = false;125 this.userEditprofileFlag = true;126 this.errorMsg = '';127 }128 updateuserFun(updateuserobj) {129 this.submitted = true;130 this.errorMsg = '';131 132 if (this.updateuserForm.valid) {133 this.isLoading = true;134 this.EgazeService.updateprofile(updateuserobj.value, this.user.loginId,this.email,this.mobileNo).subscribe(result => {135 this.isLoading = false;136 if (typeof result === "object") {137 this.isLoading = false;138 // setTimeout(function () {139 // window.location.reload(true);140 // }, 2000);141 const element = document.querySelector("#destination")142 if (element) element.scrollIntoView({ behavior: 'smooth', block: 'start' })143 window.scroll(0, 0);144 this.updateuserProfilestatus = "Profile updated Successfully";145 this.isEditDisabled = false;146 }147 }, error => {148 this.isLoading = false;149 this.errorMsg = 'Server error has occurred. Please try later.';150 });151 }152 }153 getsaveprofile() {154 this.isLoading=true;155 this.EgazeService.getprofile(this.user.loginId).subscribe(result => {156 this.updateuserProfile = result;157 if (result) {158 this.isLoading=false;159 this.email=this.updateuserProfile.email;160 this.mobileNo=this.updateuserProfile.mobileNo;161 this.updateuserForm.setValue({162 firstName: this.updateuserProfile.firstName,163 middleName: this.updateuserProfile.middleName,164 lastName: this.updateuserProfile.lastName,165 //email: this.updateuserProfile.email,166 //mobileNumber: this.updateuserProfile.mobileNo,167 address1: this.updateuserProfile.address1,168 address2: this.updateuserProfile.address2,169 address3: this.updateuserProfile.address3,170 city: this.updateuserProfile.city,171 state: this.updateuserProfile.state,172 zipCode: this.updateuserProfile.zip,173 country: this.updateuserProfile.country,174 description: this.updateuserProfile.description175 });176 }177 console.log('this.updateProfile', JSON.stringify(this.updateuserProfile));178 }, error => {179 });180 }181 profileChangepwdSubmit(updateuserNewpwdForm) {182 this.submitted = true;183 this.errorMsg = '';184 //debugger;185 if (this.updateuserNewpwdForm.valid) {186 if(this.updateuserNewpwdForm.value.oldpwd === this.updateuserNewpwdForm.value.newpwd){187 this.resultMsg = "Old password and new password can not be same";188 }else{189 this.isLoading = true;190 this.EgazeService.profilechndpwd(updateuserNewpwdForm.value, this.user.email).subscribe(191 result => {192 this.isLoading = false;193 console.log(result);194 if (result === 'SUCCESS') {195 const element = document.querySelector("#profilechndpwd")196 if (element) element.scrollIntoView({ behavior: 'smooth', block: 'start' })197 this.updateuserNewpwdForm.reset();198 this.submitted = false;199 this.profilechndResultMsg = "Password changed Successfully .Redirecting to login... !";200 setTimeout(() => {201 this.sessionstorageService.removeUserDetails("user");202 window.location.href=AppConstants.loginURL;203 }, 3000);204 205 206 this.resultMsg = "";207 }208 if (result === 'Incorrect Old Password') {209 debugger;210 this.resultMsg = "Sorry you entered wrong old password";211 this.profilechndResultMsg = "";212 }213 },214 error => {215 // alert(JSON.stringify(error));216 this.isLoading = false;217 this.resultMsg = "Sorry you entered wrong old password";218 }219 );220 }221 }222 }223 showTextPwd(updateuserNewpwdForm) {224 if (this.updateuserNewpwdForm.value.oldpwd) {225 this.showText = !this.showText;226 this.showIconEye = !this.showIconEye;227 this.hideIconEye = !this.hideIconEye;228 }229 }230 showTextPwd1(updateuserNewpwdForm) {231 if (this.updateuserNewpwdForm.value.newpwd) {232 this.showText1 = !this.showText1;233 this.showIconEye1 = !this.showIconEye1;234 this.hideIconEye1 = !this.hideIconEye1;235 }236 }237 showTextPwd2(updateuserNewpwdForm) {238 if (this.updateuserNewpwdForm.value.confirmpwd) {239 this.showText2 = !this.showText2;240 this.showIconEye2 = !this.showIconEye2;241 this.hideIconEye2 = !this.hideIconEye2;242 }243 }244 mouseoverpwd() {245 this.showText = false;246 this.showIconEye = false;247 this.hideIconEye = true;248 }249 mouseoverpwd1() {250 this.showText1 = false;251 this.showIconEye1 = false;252 this.hideIconEye1 = true;253 }254 mouseoverpwd2() {255 this.showText2 = false;256 this.showIconEye2 = false;257 this.hideIconEye2 = true;258 }259 isCharts(event) {260 if ((event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || event.charCode == 8)261 return true;262 else {263 return false;264 }265 }...

Full Screen

Full Screen

UpdateUser.js

Source:UpdateUser.js Github

copy

Full Screen

...181 if (UpdateUser.lookupCompleteCallback) {182 UpdateUser.lookupCompleteCallback(UpdateUser.UpdatedUser);183 }184 else {185 UpdateUser.updateUser(UpdateUser.UpdatedUser);186 }187}188UpdateUser.updateUser = function(updatedUser) {189 if (UpdateUser.updateUserEntry == true) {190 UpdateUser.updateUserEntries();191 }192 else if (UpdateUser.updateTransports == true) {193 UpdateUser.updateUserTransports();194 }195 else {196 UpdateUser.updateUserInfo();197 }198}199var userEntriesCounter = new Array();200UpdateUser.updateUserEntries = function() {201 $(UpdateUser.UpdatedUser.UserEntries).each(function(i, entry) {202 if (entry != null) {203 userEntriesCounter[userEntriesCounter.length] = entry.EntryKey;204 CRManager.WebClient.createUpdateUserEntry(UpdateUser.UpdatedUser.UserName, $.toJSON(entry), UpdateUser.updateUserEntrySuccess, entry.EntryKey);205 }206 });207}208UpdateUser.updateUserEntrySuccess = function(data, callId) {209 var tempArray = new Array();210 $(userEntriesCounter).each(function(index, item) {211 if (item != callId) {212 tempArray[tempArray.length] = item;213 }214 });215 userEntriesCounter = tempArray;216 if (userEntriesCounter.length == 0) {217 UpdateUser.updateUserTransports();218 }219}220var transportUpdateCounter = new Array();221UpdateUser.updateUserTransports = function() {222 var transportUpdated = false;223 transportUpdateCounter = new Array();224 if (UpdateUser.updateTransports == true) {225 $(UpdateUser.UpdatedUser.Transports).each(function(i, transport) {226 var origAddress = "";227 $(UpdateUser.SelectedUser.Transports).each(function(j, oTransport) {228 if (transport.Transport.Name == oTransport.Transport.Name) {229 origAddress = oTransport.Address;230 }231 });232 if (origAddress != transport.Address) {233 transportUpdated = true;234 transportUpdateCounter[transportUpdateCounter.length] = transport.Transport.Name;235 CRManager.WebClient.updateUserTransport(236 UpdateUser.UpdatedUser.UserName,237 transport.Transport.Name,238 origAddress,239 transport.Address,240 UpdateUser.updateUserTransportsSuccess,241 UpdateUser.updateUserTransportsError,242 transport.Transport.Name243 );244 }245 });246 }247 else {248 UpdateUser.updateUserInfo();249 }250 if (transportUpdated == false) {251 UpdateUser.updateUserInfo();252 }253}254UpdateUser.updateUserTransportsError = function(data, callId) {255 var tempArray = new Array();256 $(transportUpdateCounter).each(function(i, item) {257 if (item != callId) {258 tempArray[tempArray.length] = item;259 }260 });261 transportUpdateCounter = tempArray;262 if (transportUpdateCounter.length == 0) {263 UpdateUser.updateUserInfo();264 }265}266UpdateUser.updateUserTransportsSuccess = function(data, callId) {267 var tempArray = new Array();268 $(transportUpdateCounter).each(function(i, item) {269 if (item != callId) {270 tempArray[tempArray.length] = item;271 }272 });273 transportUpdateCounter = tempArray;274 if (transportUpdateCounter.length == 0) {275 UpdateUser.updateUserInfo();276 }277}278UpdateUser.updateUserInfo = function() {279 CRManager.WebClient.updateUser($.toJSON(UpdateUser.UpdatedUser), UpdateUser.updateUserInfoSuccess);280}281UpdateUser.updateUserInfoSuccess = function(data) {282 if (UpdateUser.updateCompleteCallback) {283 UpdateUser.updateCompleteCallback(data);284 }285}286UpdateUser.defaultErrorCallback = function(data) {287 if (data) {288 if (data.responseText) {289 alert(data.responseText);290 }291 else if (data.message) {292 alert(data.message);293 }...

Full Screen

Full Screen

SigninDao.ts

Source:SigninDao.ts Github

copy

Full Screen

1import mongoose = require('mongoose');2import { UserSchema } from '../models/User';3import { Roleschema } from '../models/Role';4import * as jwt from 'jsonwebtoken';5import * as asyncLoop from 'node-async-loop';6var jwtDecode = require('jwt-decode');7import { CustomLogger } from '../config/Logger'8const signinmodel = mongoose.model('User', UserSchema);9const rolemodel = mongoose.model('role', Roleschema);10export class SigninDao {11 private userrole: any;12 private rolevalue: any;13 private signuprole: any;14 private userDetails: any;15 private mailboolean: boolean;16 public signindao(userData, callback) {17 new CustomLogger().showLogger('info', 'Enter into SigninDao.ts: signindao');18 rolemodel.find().then(result => {19 asyncLoop(result, (roles, next) => {20 if (roles.role === 'Standarduser') {21 this.signuprole = roles._id;22 }23 next();24 }, (err) => {25 if (err) {26 return err;27 }28 })29 this.userDetails = {30 'firstname': userData.firstname,31 'lastname': userData.lastname,32 'password': userData.password,33 'email': userData.email,34 'username': userData.email,35 'role': this.signuprole,36 'Idtoken': '',37 'installrToken': userData.installrToken38 };39 signinmodel.find().then(data => {40 if (data.length !== 0) {41 asyncLoop(data, (users, next) => {42 if (users.email === this.userDetails.email) {43 this.mailboolean = true;44 } else {45 this.mailboolean = false;46 }47 next();48 }, (error) => {49 if (error) {50 return error;51 }52 });53 if (this.mailboolean === true) {54 var mailresponse = 'Email is already exists';55 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: signindao');56 callback(mailresponse);57 } else {58 let logincreds = new signinmodel(this.userDetails);59 logincreds.save().then((result) => {60 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: signindao');61 callback(result);62 }).catch((error) => {63 callback(error);64 })65 }66 } else {67 let logincreds = new signinmodel(this.userDetails);68 logincreds.save().then((result) => {69 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: signindao');70 callback(result);71 }).catch((error) => {72 callback(error);73 })74 }75 });76 })77 }78 public logindao(logindetails, callback) {79 new CustomLogger().showLogger('info', 'Enter into SigninDao.ts: logindao');80 signinmodel.findOneAndUpdate({ email: logindetails.email, password: logindetails.password }, { $set: { loggedinDate: new Date() } }, function (err, response) {81 if (err) {82 callback(err);83 }84 if (response === null) {85 response = 'Incorrect Username or Password';86 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: logindao');87 callback(response);88 } else {89 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: logindao');90 callback(response);91 }92 })93 }94 public logoutdao(userid, callback) {95 new CustomLogger().showLogger('info', 'Enter into SigninDao.ts: logoutdao');96 signinmodel.findByIdAndUpdate(userid, { $set: { loggedoutDate: new Date() } }, function (err, result) {97 if (err) {98 callback(err);99 }100 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: logoutdao');101 callback(result);102 })103 }104 public googledao(googledata, callback) {105 new CustomLogger().showLogger('info', 'Enter into SigninDao.ts: googledao');106 rolemodel.find().then((result) => {107 asyncLoop(result, (roles, next) => {108 if (roles.role === 'Standarduser') {109 this.userrole = roles._id;110 this.rolevalue = roles.role;111 }112 next();113 }, (err) => {114 if (err) {115 return err;116 }117 })118 // @ts-ignore119 let token = jwtDecode(googledata.idtoken);120 const userobject = {121 'firstname': token.given_name,122 'lastname': token.family_name,123 'username': token.email,124 'email': token.email,125 'role': this.userrole,126 'signintype': 'google'127 };128 let googlelogin = new signinmodel(userobject);129 googlelogin.save().then((result) => {130 var payload = {131 username: result.username,132 firstname: result.firstname,133 lastname: result.lastname,134 email: result.email,135 id: result._id,136 role: this.rolevalue137 }138 var idtoken = jwt.sign(payload, 'geppettosecret', {139 expiresIn: 86400140 });141 signinmodel.findByIdAndUpdate(result._id, { $set: { Idtoken: idtoken } }, function (err, response) {142 if (err) {143 callback(err);144 }145 response.Idtoken = idtoken;146 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: googledao');147 callback(response);148 });149 });150 });151 }152 public getalluserdao(callback) {153 new CustomLogger().showLogger('info', 'Enter into SigninDao.ts: getalluserdao');154 signinmodel.find().populate({155 path: 'role', model: rolemodel156 }).then(result => {157 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: getalluserdao');158 callback(result);159 }).catch((error => {160 callback(error);161 }))162 }163 public getbyiduserdao(userId, callback) {164 new CustomLogger().showLogger('info', 'Enter into SigninDao.ts: getbyiduserdao');165 signinmodel.findById(userId).populate({166 path: 'role', model: rolemodel167 }).then(result => {168 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: getbyiduserdao');169 callback(result);170 }).catch((error => {171 callback(error);172 }))173 }174 public getrolesdao(callback) {175 new CustomLogger().showLogger('info', 'Enter into SigninDao.ts: getrolesdao');176 rolemodel.find().then(result => {177 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: getrolesdao');178 callback(result);179 }).catch((error) => {180 callback(error);181 })182 }183 public updateuserdao(updateuser, callback) {184 new CustomLogger().showLogger('info', 'Enter into SigninDao.ts: updateuserdao');185 var payload = {186 username: updateuser.email,187 firstname: updateuser.firstname,188 lastname: updateuser.lastname,189 email: updateuser.email,190 id: updateuser.id,191 role: updateuser.role.role,192 installrToken: updateuser.installrToken193 }194 var idtoken = jwt.sign(payload, 'geppettosecret', {195 expiresIn: 86400196 });197 signinmodel.findByIdAndUpdate(updateuser.id, { $set: { username: updateuser.username, firstname: updateuser.firstname, lastname: updateuser.lastname, email: updateuser.email, role: updateuser.role._id, Idtoken: idtoken, installrToken: updateuser.installrToken } }, (err, response) => {198 if (err) {199 callback(err);200 }201 var updaterespone = {202 username: updateuser.email,203 firstname: updateuser.firstname,204 lastname: updateuser.lastname,205 email: updateuser.email,206 id: updateuser.id,207 role: updateuser.role._id,208 Idtoken: idtoken,209 installrToken: updateuser.installrToken210 }211 new CustomLogger().showLogger('info', 'Exit from SigninDao.ts: updateuserdao');212 callback(updaterespone);213 })214 }...

Full Screen

Full Screen

profile.service.ts

Source:profile.service.ts Github

copy

Full Screen

1import Profile from './../models/profile.model';2import PutProfile from './../models/profileOperations.model'3import User from './../models/user.model';4import db from './../database/connection';5import bCrypt from 'bcrypt';6import UF from './../models/uf.model';7import { convertFromUser } from './../utils/convertModelToJSON';8export async function readProfile(user: User) {9 return new Promise(async (resolve) => {10 let profile: Profile = await convertFromUser(user);11 resolve(profile);12 });13}14export async function updateProfile(user: User, updateUser: PutProfile) {15 return new Promise(async (resolve, reject) => {16 try {17 if (updateUser.user != '' && updateUser.user != undefined)18 user.nm_user = updateUser.user as string;19 if (updateUser.username != '' && updateUser.username != undefined)20 user.nm_username = updateUser.username as string;21 if (updateUser.biography != '' && updateUser.biography != undefined)22 user.ds_biography = updateUser.biography as string;23 if ((updateUser.status == 1 || updateUser.status == 2) && updateUser.status != undefined)24 user.cd_status_user = updateUser.status as number;25 if (updateUser.phone != '' && updateUser.phone != undefined)26 user.cd_phone_number = updateUser.phone as string;27 if (updateUser.email != '' && updateUser.email != undefined)28 user.nm_email_user = updateUser.email as string;29 if (updateUser.city != '' && updateUser.city != undefined) {30 if (updateUser.city.name != '' && updateUser.city.name != undefined) {31 const city =32 await db('tb_city as c')33 .select()34 .where('c.nm_city', '=', updateUser.city.name);35 /* Verifica se a cidade ja existe no banco */36 if (!city[0]) {37 if (updateUser.city.uf != '' && updateUser.city.uf != undefined) {38 // Procura a UF que o user pretende alterar39 const uf: Array<UF> =40 await db('tb_uf as u')41 .select()42 .where('u.sg_uf', '=', updateUser.city.uf.toUpperCase());43 if (!uf[0])44 reject({ message: 'UF inválida', status: 400 });45 else {46 /* Se a UF for valida vai inserir a cidade no banco */47 const insertedCityIds =48 await db('tb_city as c')49 .insert({50 nm_city: updateUser.city.name.toLowerCase().trimLeft().trimRight(),51 cd_uf: uf[0].cd_uf52 })53 .returning('c.cd_city');54 user.cd_city = insertedCityIds[0];55 }56 } else {57 reject({ message: 'Para alterar para uma cidade desconhecida por nós você deve informar qual é a UF dela.' });58 }59 } else {60 user.cd_city = city[0].cd_city;61 }62 }63 }64 if (updateUser.city?.uf != undefined && !updateUser.city.name)65 reject({ message: 'Para alterar sua UF é necessário informar sua cidade' });66 } catch (e) {67 reject({ message: 'Houve um erro ao atualizar suas informações. Tente novamente mais tarde. \nObs.: Indicamos renovar o token de autenticação' })68 }69 await db('tb_user')70 .where('tb_user.cd_user', '=', user.cd_user)71 .update(user)72 .catch(err => {73 reject({ message: 'Erro ao atualizar suas informações. Tente novamente mais tarde.' });74 console.error(err);75 });76 let response = await convertFromUser(user);77 resolve(response);78 });79}80export async function putPassword(putPassword: { password: string, newPassword: string }, user: User) {81 return new Promise(async (resolve, reject) => {82 // Busco no banco o hash da senha do usuario83 const userPasswordEncrypted = await db('tb_user')84 .select('tb_user.cd_password_hash')85 .where('tb_user.cd_user', '=', user.cd_user);86 // Verifico se a senha que ele enviou corresponde com a hash do banco87 await bCrypt.compare(putPassword.password, userPasswordEncrypted[0].cd_password_hash, async (err, same) => {88 // Caso não seja89 if (!same)90 reject({ message: 'Senha atual incorreta!' });91 // Caso seja92 else {93 // Criptografo a nova senha do usuário94 await bCrypt.hash(putPassword.newPassword, await bCrypt.genSalt(), async (error, encrypted) => {95 // Verifico se nao houve nenhum erro ao criptografar96 if (error) {97 reject({ message: 'Houve um erro inesperado ao criptografar a nova senha. Tente novamente mais tarde.', error });98 console.log(error)99 } else {100 // Caso não tenha erros, armazeno no banco a nova senha do usuário101 await db('tb_user')102 .update({ cd_password_hash: encrypted })103 .where('tb_user.cd_user', '=', user.cd_user)104 .then(() => resolve({ message: 'Senha atualizada com sucesso!' }))105 .catch(error => {106 reject({ message: 'Houve um erro inesperado ao atualizar sua senha. tente novamente mais tarde', error })107 console.error(error);108 });109 }110 });111 }112 });113 });...

Full Screen

Full Screen

UpdateUser.spec.js

Source:UpdateUser.spec.js Github

copy

Full Screen

1const { expect } = require('chai');2const UpdateUser = require('src/app/user/UpdateUser');3describe('App :: User :: UpdateUser', () => {4 var updateUser;5 context('when user exists', () => {6 context('when data is valid', () => {7 before(() => {8 const MockUsersRepository = {9 update: (id, data) => Promise.resolve(data),10 };11 updateUser = new UpdateUser({12 usersRepository: MockUsersRepository,13 });14 });15 it('updates the user and emits SUCCESS', (done) => {16 const userData = { name: 'Updated User' };17 updateUser.on(updateUser.outputs.SUCCESS, (response) => {18 expect(response.name).to.equal('Updated User');19 done();20 });21 updateUser.execute(123, userData);22 });23 });24 context('when data is invalid', () => {25 before(() => {26 const MockUsersRepository = {27 update: () => Promise.reject(Error('ValidationError')),28 };29 updateUser = new UpdateUser({30 usersRepository: MockUsersRepository,31 });32 });33 it('emits VALIDATION_ERROR with the error', (done) => {34 const userData = { name: 'New User' };35 updateUser.on(updateUser.outputs.VALIDATION_ERROR, (response) => {36 expect(response.message).to.equal('ValidationError');37 done();38 });39 updateUser.execute(321, userData);40 });41 });42 });43 context('when the user does not exist', () => {44 before(() => {45 const MockUsersRepository = {46 update: () => Promise.reject(new Error('NotFoundError')),47 };48 updateUser = new UpdateUser({49 usersRepository: MockUsersRepository,50 });51 });52 it('emits NOT_FOUND with the error', (done) => {53 const userData = { name: 'New User' };54 updateUser.on(updateUser.outputs.NOT_FOUND, (response) => {55 expect(response.message).to.equal('NotFoundError');56 done();57 });58 updateUser.execute(123, userData);59 });60 });61 context('when there is an internal error', () => {62 before(() => {63 const MockUsersRepository = {64 update: () => Promise.reject(new Error('Some Error')),65 };66 updateUser = new UpdateUser({67 usersRepository: MockUsersRepository,68 });69 });70 it('emits ERROR with the error', (done) => {71 const userData = { name: 'New User' };72 updateUser.on(updateUser.outputs.ERROR, (response) => {73 expect(response.message).to.equal('Some Error');74 done();75 });76 updateUser.execute(321, userData);77 });78 });...

Full Screen

Full Screen

mapUser.js

Source:mapUser.js Github

copy

Full Screen

12function mapUser(originalUser, updateUser){3 if(updateUser.name)4 originalUser.name= updateUser.name;5 if(updateUser.email) 6 originalUser.email= updateUser.email;7 if(updateUser.username) 8 originalUser.username= updateUser.username;9 if(updateUser.password) 10 originalUser.password= updateUser.password;11 if(updateUser.gender)12 originalUser.gender= updateUser.gender;13 if(updateUser.address)14 originalUser.address= updateUser.address;15 if(updateUser.dob)16 originalUser.dob= updateUser.dob;17 if(updateUser.phone)18 originalUser.phone= updateUser.phone;19 if(updateUser.role)20 originalUser.role= updateUser.role; 2122 return originalUser; 23}24 ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { updateUser } = require("qawolf");2const { chromium } = require("playwright");3async function test() {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run qawolf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful