const UserError = require('vn-loopback/util/user-error'); const authCode = require('../../models/authCode'); module.exports = Self => { Self.remoteMethod('recoverPasswordSMS', { description: 'Send SMS to the user', accepts: [ { arg: 'id', type: 'string', description: 'The user id', required: true }, { arg: 'phone', type: 'string', description: 'The phone user\'s recovery', required: true }, { arg: 'otp', type: 'string', description: 'Code tovalidate operation' } ], returns: { type: 'Object', root: true }, http: { path: `/recoverPasswordSMS`, verb: 'POST' } }); Self.recoverPasswordSMS = async function(id, phone, otp, options) { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); const user = await Self.findOne({ fields: ['id', 'recoveryPhone', 'email', 'name'], where: {id, recoveryPhone: phone} }); if (!user) throw new UserError('Credentials not valid'); try { if (otp) { await Self.validateCode(user.name, otp); return { token: await user.accessTokens.create({}) }; } const code = await authCode(user, myOptions); if (process.env.NODE_ENV === 'production') await Self.app.models.Sms.send({req: {accessToken: {userId: id}}}, +phone, code); return {otp: true}; } catch (err) { if (err.code === 'EMAIL_NOT_FOUND') return; else throw err; } }; };