import passport from 'passport'
import jwt from 'jsonwebtoken'
import _ from 'lodash'

import { load as configLoader } from '../../../../config/config'
import { UserSerializer } from '../../../models'


const config = configLoader()

export default class SessionController {
  static create(req, res) {
    passport.authenticate('local', async function(err, user, msg) {
      if (err) {
        res.status(401).jsonp({ err: err.message })
        return
      }

      if (user === false) {
        if (!msg) {
          msg = 'Internal server error'
        }

        res.status(401).jsonp({ err: msg })
        return
      }

      const secret = config.secret
      const authToken = jwt.sign({ userId: user.id }, secret)

      const json = await new UserSerializer(user).promiseToJSON()
      res.jsonp(_.extend(json, { authToken }))
    })(req, res)
  }
}

import passport from 'passport'
import jwt from 'jsonwebtoken'
import _ from 'lodash'

import { load as configLoader } from '../../../../config/config'
import { UserSerializer } from '../../../models'


const config = configLoader()

export default class SessionController {
  static create(req, res) {
    passport.authenticate('local', async function(err, user, msg) {
      if (err) {
        res.status(401).jsonp({ err: err.message })
        return
      }

      if (user === false) {
        if (!msg) {
          msg = { message: 'Internal server error' }
        }

        res.status(401).jsonp({ err: msg.message })
        return
      }

      const secret = config.secret
      const authToken = jwt.sign({ userId: user.id }, secret)

      const json = await new UserSerializer(user).promiseToJSON()
      res.jsonp(_.extend(json, { authToken }))
    })(req, res)
  }
}

Fix response format for failed sign-in attempt
Fix response format for failed sign-in attempt

The format of response for "Missing credentials" is:
{ "err": { message: "Missing credentials" } }

The format we have everywhere else is:
{ "err": "Error details" }

This change makes the former response consistent with the latter format.
