<commit_before>/* 
* @Author: <NAME>
* @Date:   2015-12-14 11:57:54
* @Last Modified 2015-12-16
*/

'use strict';


import passport from 'passport'
import fs from 'fs'

const isDev = process.env.NODE_ENV !== 'production';

export default class APIController {
  constructor(plugin, app) {
    this.app = app;
    var router = app.get('router')

    router.provide('route', 'GET', '/logout', this._logoutHandler.bind(this))

    app.on('startup', () => {
      router.request('getExpressApp').then((expressApp) => {
        expressApp.post(
          '/login',
          this._authenticationCallback.bind(this),
          this._loginHandler.bind(this)
        )
      })
    })
  }

  _authenticationCallback(req, res, next) {
    let failureRedirect = '/login'
    if (req.param.redirect) {
      failureRedirect += '?redirect=' + encodeURIComponent(req.param('redirect'))
    }
    passport.authenticate('local', {failureRedirect: failureRedirect, failureFlash: true})(req, res, next)
  }

  _loginHandler(req, res) {
    console.log('login callback')
    this.app.get('storage').request('model', 'user').then((User) => {
          
      req.session.flash = []
      req.session.save(err => {
        var r = req.param.redirect
        if (r) {
          if (r === '/' && User.isEditor(req.user)) {
            return res.redirect('/admin')
          }
          return res.redirect(r)
        } else
          return res.redirect("/")
      })
    })
  }

  _logoutHandler(req, res) {
    this.app.emit('user.loggedOut', req.user)
    req.session.flash = []
    req.session.save(err => {
      this.app.log.debug('logged out', req.user)
      req.logout()
      res.redirect('/login')
    })
  }

  // _authenticationCallback(req, res, next) {
  //   let failureRedirect = '/login'
  //   if (req.param('redirect')) {
  //     failureRedirect += '?redirect=' + encodeURIComponent(req.param('redirect'))
  //   }
  //   passport.authenticate('local', {failureRedirect: failureRedirect, failureFlash: true})(req, res, next)
  // }

  // _generateVerifyUrl(user) {
  //   const teamName = user.team.name
  //   const verifyEndpoint = `/api/users/${user._id}/verify/${user.verifyToken}`
  //   return `http://${teamName}.${this.appDomain}${verifyEndpoint}`
  // }

  // _sendInviteEmail(userId) {
  //   this.app.emit('storage.getModel', 'User', (err, User) => {
  //     this.app.log.warn('userId', userId)
  //     User.findOne({ _id: userId }).populate('team').exec((err, user) => {
  //       const link = this._generateResetPasswordUrl(user)
  //       const teamName = user.team.name
  //       var role = "view"
  //       if (user.isEditor()) role = "edit"
  //       this.app.emit('mail.send', {
  //         recipients: [user.email],
  //         subject: `DataDash.io: You've been invited`,
  //         messageText: this.render('inviteEmail', {
  //           teamName: teamName,<commit_msg>Added support for redirect to logout<commit_after>/* 
* @Author: <NAME>
* @Date:   2015-12-14 11:57:54
* @Last Modified 2015-12-16
*/

'use strict';


import passport from 'passport'
import fs from 'fs'

const isDev = process.env.NODE_ENV !== 'production';

export default class APIController {
  constructor(plugin, app) {
    this.app = app;
    var router = app.get('router')

    router.provide('route', 'GET', '/logout', this._logoutHandler.bind(this))

    app.on('startup', () => {
      router.request('getExpressApp').then((expressApp) => {
        expressApp.post(
          '/login',
          this._authenticationCallback.bind(this),
          this._loginHandler.bind(this)
        )
      })
    })
  }

  _authenticationCallback(req, res, next) {
    let failureRedirect = '/login'
    if (req.param.redirect) {
      failureRedirect += '?redirect=' + encodeURIComponent(req.param('redirect'))
    }
    passport.authenticate('local', {failureRedirect: failureRedirect, failureFlash: true})(req, res, next)
  }

  _loginHandler(req, res) {
    console.log('login callback')
    this.app.get('storage').request('model', 'user').then((User) => {
          
      req.session.flash = []
      req.session.save(err => {
        var r = req.param.redirect
        if (r) {
          if (r === '/' && User.isEditor(req.user)) {
            return res.redirect('/admin')
          }
          return res.redirect(r)
        } else
          return res.redirect("/")
      })
    })
  }

  _logoutHandler(req, res) {
    this.app.emit('user.loggedOut', req.user)
    req.session.flash = []
    req.session.save(err => {
      this.app.log.debug('logged out', req.user)
      req.logout()
      if(req.params.redirect)
        res.redirect(req.params.redirect)
      else
        res.redirect('/login')
    })
  }

  // _authenticationCallback(req, res, next) {
  //   let failureRedirect = '/login'
  //   if (req.param('redirect')) {
  //     failureRedirect += '?redirect=' + encodeURIComponent(req.param('redirect'))
  //   }
  //   passport.authenticate('local', {failureRedirect: failureRedirect, failureFlash: true})(req, res, next)
  // }

  // _generateVerifyUrl(user) {
  //   const teamName = user.team.name
  //   const verifyEndpoint = `/api/users/${user._id}/verify/${user.verifyToken}`
  //   return `http://${teamName}.${this.appDomain}${verifyEndpoint}`
  // }

  // _sendInviteEmail(userId) {
  //   this.app.emit('storage.getModel', 'User', (err, User) => {
  //     this.app.log.warn('userId', userId)
  //     User.findOne({ _id: userId }).populate('team').exec((err, user) => {
  //       const link = this._generateResetPasswordUrl(user)
  //       const teamName = user.team.name
  //       var role = "view"
  //       if (user.isEditor()) role = "edit"
  //       this.app.emit('mail.send', {
  //         recipients: [user.email],
  //         subject: `DataDash.io: You've been invited`,
  //         messageText: this.render('inviteEmail', {
  //           teamName: teamName,
{'fraction_non_alphanumeric': 0.17642083897158323, 'fraction_numerical': 0.007442489851150203, 'mean_word_length': 2.486438679245283, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2469289', 'n_tokens_mistral': 1946, 'n_tokens_neox': 1907, 'n_words': 327}