const { Middleware } = require('libflitter')
const samlp = require('samlp')

class SAMLRequestMiddleware extends Middleware {
    static get services() {
        return [...super.services, 'output', 'models']
    }

    async test(req, res, next, args = null) {
        const ServiceProvider = this.models.get('saml:ServiceProvider')

        samlp.parseRequest(req, async (err, data) => {
            if ( err )
                return res.error(400, { message: 'Unable to parse SAML request data.' })

            if ( data ) {
                // Verify that the issuer is known
                const sp = await ServiceProvider.findOne({entity_id: data.issuer, active: true})
                if (!sp)
                    return res.error(401, {
                        message: 'Unable to continue. The SAML issuer is unknown.'
                    })

                req.saml_request = {
                    relay_state: req.query.RelayState || req.body.RelayState,
                    id: data.id,
                    issuer: data.issuer,
                    destination: data.destination,
                    acs_url: data.assertionConsumerServiceURL,
                    force_authn: data.forceAuthn === 'true',
                    service_provider: sp,
                }

                req.session.auth.message = `Please sign-in to continue to ${sp.name}.`

                this.output.info('Parsed SAML request')
                this.output.debug(req.saml_request)
            } else {
                this.output.info(`Incoming request does not have an associated SAMLRequest`)
            }

            return next()
        })
    }
}

module.exports = exports = SAMLRequestMiddleware
