<commit_before>'use strict';

////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2010-2013 triAGENS GmbH, Cologne, Germany
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author <NAME>
/// @author <NAME>
////////////////////////////////////////////////////////////////////////////////

const joi = require('joi');
const dd = require('dedent');
const internal = require('internal');
const db = require('@arangodb').db;
const errors = require('@arangodb').errors;
const notifications = require('@arangodb/configuration').notifications;
const examples = require('@arangodb/graph-examples/example-graph');
const createRouter = require('@arangodb/foxx/router');

const API_DOCS = require(module.context.fileName('api-docs.json'));
API_DOCS.basePath = `/_db/${encodeURIComponent(db._name())}`;

const sessions = module.context.sessions;
const auth = module.context.auth;
const router = createRouter();
module.exports = router;


router.get('/whoAmI', function(req, res) {
  let user = null;

  if (req.session.uid) {
    try {
      const doc = db._users.document(req.session.uid);
      user = doc.user;
    } catch (e) {
      if (!e.isArangoError || e.errorNum !== errors.ERROR_ARANGO_DOCUMENT_NOT_FOUND.code) {
        throw e;
      }
      sessions.setUser(req.session, null);
    }
  }

  res.json({user});
})
.summary('Return the current user')
.description(dd`
  Returns the current user or "null" if the user is not authenticated.
  Returns "false" if authentication is disabled.
`);


router.post('/logout', function (req, res) {
  sessions.clear(req.session);
  delete req.session;
  res.json({success: true});
})
.summary('Log out')
.description(dd`
  Destroys the current session and revokes any authentication.
`);


router.post('/login', function (req, res) {
  const doc = db._users.firstExample({user: req.body.username});
  const valid = auth.verify(
    doc ? doc.authData.simple : null,
    req.body.password
  );

  if (!valid) {
    res.throw('unauthorized');
  }

  sessions.setUser(req.session, doc);
  sessions.save(req.session);

  const user = doc.user;
  res.json({user});
})
.body({
  username: joi.string().required(),
  password: <PASSWORD>().required().allow('')
}, 'Login credentials.')
.error('unauthorized', 'Invalid credentials.')
.summary('Log in')
.description(dd`
  Authenticates the user for the active session with a username and password.
  Creates a new session if none exists.
`);


const authRouter = createRouter();
router.use(authRouter);


authRouter.use((req, res, next) => {
  if (!req.session.uid) {
    res.throw('unauthorized');
  }
  next();
});


authRouter.get('/api/*', module.context.apiDocumentation({
  swaggerJson(req, res) {
    res.json(API_DOCS);
  }
}))
.summary('System API documentation')
.description(dd`
  Mounts the system API documentation.
`);<commit_msg>Allow switching databases in login<commit_after>'use strict';

////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2010-2013 triAGENS GmbH, Cologne, Germany
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author <NAME>
/// @author <NAME>
////////////////////////////////////////////////////////////////////////////////

const joi = require('joi');
const dd = require('dedent');
const internal = require('internal');
const db = require('@arangodb').db;
const errors = require('@arangodb').errors;
const joinPath = require('path').posix.join;
const notifications = require('@arangodb/configuration').notifications;
const examples = require('@arangodb/graph-examples/example-graph');
const createRouter = require('@arangodb/foxx/router');

const API_DOCS = require(module.context.fileName('api-docs.json'));
API_DOCS.basePath = `/_db/${encodeURIComponent(db._name())}`;

const sessions = module.context.sessions;
const auth = module.context.auth;
const router = createRouter();
module.exports = router;


router.get('/whoAmI', function(req, res) {
  let user = null;

  if (req.session.uid) {
    try {
      const doc = db._users.document(req.session.uid);
      user = doc.user;
    } catch (e) {
      if (!e.isArangoError || e.errorNum !== errors.ERROR_ARANGO_DOCUMENT_NOT_FOUND.code) {
        throw e;
      }
      sessions.setUser(req.session, null);
    }
  }

  res.json({user});
})
.summary('Return the current user')
.description(dd`
  Returns the current user or "null" if the user is not authenticated.
  Returns "false" if authentication is disabled.
`);


router.post('/logout', function (req, res) {
  sessions.clear(req.session);
  delete req.session;
  res.json({success: true});
})
.summary('Log out')
.description(dd`
  Destroys the current session and revokes any authentication.
`);


router.post('/login', function (req, res) {
  const currentDb = db._name();
  const actualDb = req.body.database;
  if (actualDb !== currentDb) {
    res.redirect(307, joinPath(
      '/_db',
      encodeURIComponent(actualDb),
      module.context.mount,
      '/login'
    ));
    return;
  }

  const doc = db._users.firstExample({user: req.body.username});
  const valid = auth.verify(
    doc ? doc.authData.simple : null,
    req.body.password
  );

  if (!valid) {
    res.throw('unauthorized');
  }

  sessions.setUser(req.session, doc);
  sessions.save(req.session);

  const user = doc.user;
  res.json({user});
})
.body({
  username: joi.string().required(),
  password: joi.string().required().allow(''),
  database: joi.string().default(db._name())
}, 'Login credentials.')
.error('unauthorized', 'Invalid credentials.')
.summary('Log in')
.description(dd`
  Authenticates the user for the active session with a username and password.
  Creates a new session if none exists.
`);


const authRouter = createRouter();
router.use(authRouter);


authRouter.use((req, res, next) => {
  if (!req.session.uid) {
    res.throw('unauthorized');
  }
  next();
});


authRouter.get('/api/*', module.context.apiDocumentation({
  swaggerJson(req, res) {
    res.json(API_DOCS);
  }
}))
.summary('System API documentation')
.description(dd`
  Mounts the system API documentation.
`);
{'fraction_non_alphanumeric': 0.1907522243192235, 'fraction_numerical': 0.004718252898355352, 'mean_word_length': 3.10797342192691, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '362312', 'n_tokens_mistral': 2236, 'n_tokens_neox': 2177, 'n_words': 613}