<commit_before>/*
 * Copyright 2013 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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.
 */

var assert = require('assert');

var ConfigTestUtil = require('oae-config/lib/test/util');
var Context = require('oae-context').Context;
var PrincipalsAPI = require('oae-principals');
var RestAPI = require('oae-rest');
var RestContext = require('oae-rest/lib/model').RestContext;
var TestsUtil = require('oae-tests');

var AuthenticationAPI = require('oae-authentication');
var AuthenticationConstants = require('oae-authentication/lib/constants').AuthenticationConstants;
var LoginId = require('oae-authentication/lib/model').LoginId;

describe('Authentication', function() {

    // Rest context that can be used for anonymous requests on the cambridge tenant
    var anonymousCamRestContext = null;
    // Rest context that can be used for anonymous requests on the georgia tech tenant
    var anonymousGtRestContext = null;
    // Rest context that can be used every time we need to make a request as a tenant admin
    var camAdminRestContext = null;

    /**
     * Function that will fill up the tenant admin and anymous rest context
     */
    before(function(callback) {
        // Fill up the anonymous cam rest context
        anonymousCamRestContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
        // Fill up the anonymous gt rest context
        anonymousGtRestContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.gt.host);
        // Fill up global admin rest context
        camAdminRestContext = TestsUtil.createTenantAdminRestContext(global.oaeTests.tenants.cam.host);
        callback();
    });

    /**
     * Ensure that all tests will start with local authentication enabled, even if tests that disable it fail
     */
    afterEach(function(callback) {
        ConfigTestUtil.updateConfigAndWait(camAdminRestContext, null, 'oae-authentication/local/enabled', true, function(err) {
            assert.ok(!err);
        });

        // When the strategies have refreshed, then continue
        AuthenticationAPI.once(AuthenticationConstants.events.REFRESHED_STRATEGIES, function(tenant) {
            callback();
        });
    });


    describe('Local authentication', function() {

        /**
         * Test that verifies that users can log into the system using a local authorization strategy
         */
        it('verify local authentication', function(callback) {
            // Create a test user
            var userId = TestsUtil.generateTestUserId();
            RestAPI.User.createUser(camAdminRestContext, userId, 'password', '<PASSWORD>', null, function(err, createdUser) {
                assert.ok(!err);
                assert.ok(createdUser);
                var userRestContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host, userId, 'password');

                // Log the user out first, to make sure that the cookie jar for the user is empty
                RestAPI.Authentication.logout(userRestContext, function(err) {
                    assert.ok(!err);

                    // Login without a user id
                    RestAPI.Authentication.login(userRestContext, null, 'password', function(err) {
                        assert.ok(err);

                        // Log in with the wrong password
                        RestAPI.Authentication.login(userRestContext, userId, '<PASSWORD>', function(err) {
                            assert.ok(err);

                            // Log in with the correct password
                            RestAPI.Authentication.login(userRestContext, userId, 'password', function(err) {
                                assert.ok(!err);

                                // Verify that we are actually logged in
                                RestAPI.User.getMe(userRestContext, function(err, meObj) {
                                    assert.ok(!err);
                                    assert.ok(meObj);
                                    assert.equal(meObj.id, createdUser.id);

                                    // Logout
                                    RestAPI.Authentication.logout(userRestContext, function(err) {
                                        assert.ok(!err);

                                        // Verify that we are now logged out
                                        RestAPI.User.getMe(userRestContext, function(err, meObj) {
                                            assert.ok(!err);
                                            assert.ok(meObj);
                                            assert.equal(meObj.anon, true);
                                            callback();
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that an account can't be created with an existing id
         */
        it('verify account creation locking', function(callback) {
            var err1;
            var err2;
            var count = 0;

            var checkComplete = function() {
                count++;
                // Make sure both calls to createUser have returned
                if (count == 2) {
                    // Make sure at least one call errored
                    var err = err1 || err2;
                    assert.ok(err);
                    assert.equal(err.code, 400);
                    callback();
                }
            };

            // Create a test user
            var userId = TestsUtil.generateTestUserId();
            RestAPI.User.createUser(camAdminRestContext, userId, 'password', '<PASSWORD>', null, function(err, createdUser) {
                err1 = err;
                checkComplete();
            });
            RestAPI.User.createUser(camAdminRestContext, userId, 'password', '<PASSWORD>', null, function(err, createdUser) {<commit_msg>Added jsdoc and assertion for double failure to account creation locking unit test<commit_after>/*
 * Copyright 2013 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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.
 */

var assert = require('assert');

var ConfigTestUtil = require('oae-config/lib/test/util');
var Context = require('oae-context').Context;
var PrincipalsAPI = require('oae-principals');
var RestAPI = require('oae-rest');
var RestContext = require('oae-rest/lib/model').RestContext;
var TestsUtil = require('oae-tests');

var AuthenticationAPI = require('oae-authentication');
var AuthenticationConstants = require('oae-authentication/lib/constants').AuthenticationConstants;
var LoginId = require('oae-authentication/lib/model').LoginId;

describe('Authentication', function() {

    // Rest context that can be used for anonymous requests on the cambridge tenant
    var anonymousCamRestContext = null;
    // Rest context that can be used for anonymous requests on the georgia tech tenant
    var anonymousGtRestContext = null;
    // Rest context that can be used every time we need to make a request as a tenant admin
    var camAdminRestContext = null;

    /**
     * Function that will fill up the tenant admin and anymous rest context
     */
    before(function(callback) {
        // Fill up the anonymous cam rest context
        anonymousCamRestContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
        // Fill up the anonymous gt rest context
        anonymousGtRestContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.gt.host);
        // Fill up global admin rest context
        camAdminRestContext = TestsUtil.createTenantAdminRestContext(global.oaeTests.tenants.cam.host);
        callback();
    });

    /**
     * Ensure that all tests will start with local authentication enabled, even if tests that disable it fail
     */
    afterEach(function(callback) {
        ConfigTestUtil.updateConfigAndWait(camAdminRestContext, null, 'oae-authentication/local/enabled', true, function(err) {
            assert.ok(!err);
        });

        // When the strategies have refreshed, then continue
        AuthenticationAPI.once(AuthenticationConstants.events.REFRESHED_STRATEGIES, function(tenant) {
            callback();
        });
    });


    describe('Local authentication', function() {

        /**
         * Test that verifies that users can log into the system using a local authorization strategy
         */
        it('verify local authentication', function(callback) {
            // Create a test user
            var userId = TestsUtil.generateTestUserId();
            RestAPI.User.createUser(camAdminRestContext, userId, 'password', '<PASSWORD>', null, function(err, createdUser) {
                assert.ok(!err);
                assert.ok(createdUser);
                var userRestContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host, userId, 'password');

                // Log the user out first, to make sure that the cookie jar for the user is empty
                RestAPI.Authentication.logout(userRestContext, function(err) {
                    assert.ok(!err);

                    // Login without a user id
                    RestAPI.Authentication.login(userRestContext, null, 'password', function(err) {
                        assert.ok(err);

                        // Log in with the wrong password
                        RestAPI.Authentication.login(userRestContext, userId, '<PASSWORD>', function(err) {
                            assert.ok(err);

                            // Log in with the correct password
                            RestAPI.Authentication.login(userRestContext, userId, 'password', function(err) {
                                assert.ok(!err);

                                // Verify that we are actually logged in
                                RestAPI.User.getMe(userRestContext, function(err, meObj) {
                                    assert.ok(!err);
                                    assert.ok(meObj);
                                    assert.equal(meObj.id, createdUser.id);

                                    // Logout
                                    RestAPI.Authentication.logout(userRestContext, function(err) {
                                        assert.ok(!err);

                                        // Verify that we are now logged out
                                        RestAPI.User.getMe(userRestContext, function(err, meObj) {
                                            assert.ok(!err);
                                            assert.ok(meObj);
                                            assert.equal(meObj.anon, true);
                                            callback();
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that an account can't be created with an existing id
         */
        it('verify account creation locking', function(callback) {
            var err1;
            var err2;
            var count = 0;

            /*!
             * Callback for the create user requests
             */
            var checkComplete = function() {
                count++;
                // Make sure both calls to createUser have returned
                if (count == 2) {
                    // Make sure at most one call errored
                    if (err1 && err2) {
                        assert.fail('Expected only one create user call to fail');
                    }

                    // Make sure at least one call errored
                    var err = err1 || err2;
                    assert.ok(err);
                    assert.equal(err.code, 400);
                    callback();
                }
            };

            // Create a test user
            var userId = TestsUtil.generateTestUserId();
            RestAPI.User.createUser(camAdminRestContext, userId, 'password', '<PASSWORD>', null, function(err, createdUser) {
                err1 = err;
                checkComplete();
            });
            RestAPI.User.createUser(camAdminRestContext, userId, 'password', '<PASSWORD>', null, function(err, createdUser) {
{'fraction_non_alphanumeric': 0.08790394307737918, 'fraction_numerical': 0.0028164838422769047, 'mean_word_length': 1.6739992072929053, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 42, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '933247', 'n_tokens_mistral': 3130, 'n_tokens_neox': 3027, 'n_words': 940}