const { Controller } = require('libflitter')

class TrustController extends Controller {
    static get services() {
        return [...super.services, 'Vue']
    }

    /*
     * Prompts the user to re-authenticate.
     * If successful, a trust token will be issued for the specified scope.
     *
     * Requires req.session.trust_flow = { scope: String, next: String }
     */
    async get_issue(req, res, next) {
        if ( !req.trust.has_flow() )
            return res.status(400).message(req.T('auth.missing_trust_flow')).send()

        // Check if the session already has a token for this scope
        const has_scope = req.trust.has(req.trust.flow_scope())

        // If so, redirect them to the destination
        if ( has_scope ) {
            return res.redirect(req.trust.end())
        }

        // Otherwise, show the trust prompt for re-authorization
        const token = req.trust.start()
        return res.page('auth:trust:grant', {
            ...this.Vue.data({
                grant_code: token,
                login_message: req.T('auth.reauth_to_continue'),
            }),
            ...this.Vue.session(req)
        })
    }
}

module.exports = exports = TrustController
