RocketChat / Rocket.Chat.js.SDK

Utility for apps and bots to interact with Rocket.Chat via DDP and/or API
MIT License
136 stars 94 forks source link

Support for reauthenticating when 2fa fails #120

Open 4e554c4c opened 3 years ago

4e554c4c commented 3 years ago

I wrote the following to give this functionality in my bot

import { driver, methodCache, api, settings } from  '@rocket.chat/sdk'
import * as crypto from 'crypto'
api.post_2fa = async (endpoint, data, auth = undefined, ignore = undefined) => {
  return await api.post(endpoint, data, auth, ignore).then((val) => {
    if (val === undefined) {
      // assume our error was TOTP-based (no way to tell because if success=false, undefined is returned)
      // here we mess with the global auth headers
      const old_auth = api.authHeaders 
      api.authHeaders = Object.assign({
        'X-2fa-code': crypto.createHash('sha256').update(settings.password).digest('hex'),
        'X-2fa-method': 'password'
      }, old_auth)
      try {
        return api.post(endpoint, data, auth, ignore)
      } finally {
        api.authHeaders = old_auth
      }
    }
    return val
  })
}