<commit_before>/*
 The MIT License (MIT)

 Copyright (c) 2016 Sergei Tolokonnikov

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

$(document).ready(function () {

    createSettingsFileIfNotExists();

    loadAppSettings(function () {
        setColorTheme(settings.color_theme);
        $(".container").fadeIn(settings.animationSpeed);
        registerShortcuts();
        showScreenSearch();
        toggleSidebar();
        loadTodosFromSettings();
        loadNotificationsFromSettings();
        checkNotifications();
        renderNotesLinks();
    });

    var appTimer = setInterval(function () {
        watchTodoRemainds();
    }, 1000);

    $(document).on('click', "#button-settings-back", function () {
        activeScreen = 'search';
        showScreenSearch();

    });

    $(document).on('click', "#button-settings-save", function () {
        if (settings.path_to_db != $("#screen-settings #path-to-db").val()) {
            dbSecretKey = null;
        }
        settings.path_to_db = $("#screen-settings #path-to-db").val();
        settings.local_keymap = $("#screen-settings #local-keymap").val();
        settings.history_length = $("#screen-settings #history-length").val();
        settings.color_theme = $("[name=color_theme]:checked").val();
        setColorTheme(settings.color_theme);
        updateAppSettings();
        activeScreen = 'search';
        renderNotesLinks();
        showScreenSearch();
        researchNotes();
    });

    $(document).on('click', "#button-add-note", function () {
        showScreenEdit();
    });

    $(document).on('click', "#button-todo", function () {
        showScreenTodo();
    });

    $(document).on('click', "#button-notifications", function () {
        showScreenNotifications();
    });

    $(document).on('click', "#button-todo-back", function () {
        vmTodoList.editMode.enabled = false;
        showScreenSearch();
    });

    $(document).on('click', "#button-notifications-back", function () {
        showScreenSearch();
    });

    $(document).on('click', "#button-clips", function () {
        showScreenClips();
    });

    $(document).on('click', "#button-clips-back", function () {
        showScreenSearch();
    });

    $(document).on('click', "#button-gotoresult-forward", function () {
        if (!searchMatchesCount) return;
        gotoNextResult();
    });

    $(document).on('click', "#button-gotoresult-backward", function () {
        if (!searchMatchesCount) return;
        gotoPrevResult();
    });

    $(document).on('click', "#button-navigator-forward", function () {
        navigatorForward();
    });

    $(document).on('click', "#button-navigator-backward", function () {
        navigatorBackward();
    });

    $(document).on('click', "#button-history-back", function () {
        $("#input-search").blur();
        historyBack();
    });

    $(document).on('click', "#button-history-forward", function () {
        $("#input-search").blur();
        historyForward();
    });

    $(document).on('click', "#screen-settings #button-clear-history", function () {
        actionClearHistory();
    });

    $(document).on('click', '#notes-links-area .note-link', function (e) {
        triggerNoteLink(parseInt($(this).attr('data-id')));
        addToHistory($(this).attr('data-id'));
    });

    $(document).on('selectionchange', function (e) {
        if (stripHtml(getHTMLOfSelection()) == '') {
            clipTitle = clipBody = '';
            return;
        } else {
            var noteID = window.getSelection().getRangeAt(0).commonAncestorContainer
                .parentNode.parentNode.getAttribute('data-id') ||
                window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode.getAttribute('data-id') ||
                window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode.parentNode.parentNode.getAttribute('data-id');
            if (noteID === null) {
                return;
            }
            clipTitle = $(".note[data-id="+noteID+"]").find(".title").text();
            clipBody = stripHtml(getHTMLOfSelection());

        }

    });

    $(document).on('click', "#search-results-area .note", function (e) {
        var noteID = parseInt($(this).attr('data-id'));
        addToHistory(noteID);
    });

    $(document).on('click', "#search-results-area .btn", function (e) {
        return false;
    });

    $(document).on('mousedown', "#search-results-area .note", function (e) {
        if (e.which == 2) {
            //e.preventDefault();
            contextCurrentNoteID = parseInt($(this).attr('data-id'));
            actionEditNote(contextCurrentNoteID);
        }
    });

    $(document).on('click', ".button-edit-note", function () {
        actionEditNote(parseInt($(this).attr('data-id')));
    });

    $(document).on('click', "#button-clear-clips", function () {
        if (confirm('Are you sure you want to delete all clips?')) {
            clearClips();
        }

    });

    $(document).on('click', "#button-edit-back", function () {
        showScreenSearch();
    });
    $(document).on('click', "#button-about-back", function () {
        showScreenSearch();
    });
    $(document).on('click', "#button-change-secret-key-back", function () {
        showScreenSearch();
    });

    // $(document).on('mouseenter', ".note", function () {
    //     markActiveNoteLink(parseInt($(this).attr('data-id')));
    // });

    $("#screen-search #input-search").keyup(function (e) {
        $("#notes-links-area .note-link").removeClass('active');
        searchNotes($(this).val());
    });

    // $(document).on('keyup', "#screen-search #input-search", function (e) {
    //
    //
    //
    //
    // });

    $(document).on('keydown', "#screen-edit #title, #screen-edit #body", function (e) {

        if (addingFromClipboard || $("#screen-edit").attr('data-id') === undefined) {
            return;
        }
        if (!e.ctrlKey) {
            editorDataModified = true;
        }
        displayEditorSaveButton();
    });

    $(document).on('click', "#screen-edit #button-save", function () {

        if (!editorDataModified) return;

        dontCloseScreen = true;
        windowMustBeHidden = false;
        $("#screen-edit #button-ok").trigger('click');
    });

    $(document).on('click', "#screen-edit #button-ok", function () {
        var title = $("#screen-edit #title").val().trim();
        var body = $("#screen-edit #body").val().trim();
        if (body == '' && !vmPasswordsEditWidget.passwords.length) {
            alert('Field Body is required.');
            return;
        }
        if (!validatePasswordsEditWidget()) {
            alert('Incorrect passwords data!');
            return;
        }
        if (title == '') {
            var prefix = '#untitled ';
            if (addingFromClipboard) {
                prefix = '#clipboard ';
                addingFromClipboard = false;
            }
            title = prefix + body.substr(0, 30)+'...'.trim();
        }
        if ($("#screen-edit").attr('data-id') === undefined) {
            addNote(title, body);
        } else {
            updateNote($("#screen-edit").attr('data-id'), title, body);
        }
        if (windowMustBeHidden) {
            windowMustBeHidden = false;
            const { remote } = require('electron');
            remote.BrowserWindow.getFocusedWindow().minimize();
        }
        editorDataModified = false;
        displayEditorSaveButton();
    });

    $(document).on('click', ".button-delete-note", function () {
        actionDeleteNote($(this).attr('data-id'));
    });

    $(document).on('click', "#clips-area .clip", function () {
        currentClipID = $(this).data('id');
        var clip = $(this).find(".clip-text").text();
        clipboard.writeText(clip);
        clipboard.writeText(clip, 'selection');
        $("#button-clips-back").trigger('click');
    });

    $(document).on('contextmenu', "#clips-area .clip", function (e) {
        e.preventDefault();
        currentClipID = $(this).data('id');
        clipsContextMenu.popup(remote.getCurrentWindow());
    });

    $(document).on('click', "#button-sidebar-toggle", function () {
        toggleSidebar();
    });

    $(document).on('click', ".edit-todo-button", function () {
        $('body').animate({
            scrollTop: $("#todo-list .editor-group[data-id="+$(this).data('id')+"]").offset().top - 93
        }, settings.settings.animationSpeed);
    });

    function setSidebarHeight() {
        var h = $(window).height();
        $('#sidebar').css('height', (h - 89 - 26)+'px');
    }
    function setEditorHeight() {
        var h = $(window).height();
        $('#screen-edit #body').css('height', (h - 175)+'px');
    }
    $(window).load(function (e) {
        setSidebarHeight();
        setEditorHeight();
    });
    $(window).resize(function (e) {
        setSidebarHeight();
        setEditorHeight();
    });

});

$(document).on('contextmenu', '#search-results-area .note', function (e) {
    e.preventDefault();
    contextCurrentNoteID = parseInt($(this).attr('data-id'));
    searchResultsContextMenu.popup(remote.getCurrentWindow());
});

$(document).on('contextmenu', '#notes-links-area .note-link', function (e) {
    e.preventDefault();
    contextCurrentNoteID = parseInt($(this).attr('data-id'));
    notesLinksContextMenu.popup(remote.getCurrentWindow());
});

$(document).on('mousedown', "#notes-links-area .note-link", function (e) {
    if (e.which == 2) {
        //e.preventDefault();
        contextCurrentNoteID = parseInt($(this).attr('data-id'));
        actionEditNote(contextCurrentNoteID);
    }
});

$(document).on('contextmenu', '#screen-edit #body', function (e) {
    e.preventDefault();
    editorBodyContextMenu.popup(remote.getCurrentWindow());
});

$(document).on('contextmenu', '#screen-edit #title', function (e) {
    e.preventDefault();
    editorTitleContextMenu.popup(remote.getCurrentWindow());
});

$(document).on('submit', '#screen-edit form', function (e) {
    e.preventDefault();
    $('#screen-edit #body').focus();
});

$(window).scroll(function (e) {
    if (activeScreen == 'search') {
        windowScrollTop = $(window).scrollTop();
    }
});

$(document).on('keyup', '#screen-set-secret-key #key-repeat, #screen-set-secret-key #key', function (e) {
    e.preventDefault();
    $('#screen-set-secret-key #key-repeat').removeClass('error').removeClass('equal');
    $('#screen-set-secret-key #key').removeClass('error').removeClass('equal');

    if ($('#screen-set-secret-key #key').val() == $('#screen-set-secret-key #key-repeat').val()) {
        $('#screen-set-secret-key #key-repeat').removeClass('error').addClass('equal');
    } else {
        $('#screen-set-secret-key #key-repeat').removeClass('equal').addClass('error');
    }
});

$(document).on('submit', '#screen-set-secret-key form', function (e) {
    e.preventDefault();

    if ($('#screen-set-secret-key #key').val() != $('#screen-set-secret-key #key-repeat').val()) {
        return;
    }

    dbSecretKey = $('#screen-set-secret-key #key').val();

    var nm = new DBManager();
    nm.setDB(settings.path_to_db);
    nm.createDB();
    nm.pingKey(function () {
        renderNotesLinks();
        showScreenSearch();
        researchNotes();
    });

});

$(document).on('keyup', '#screen-enter-secret-key #key', function (e) {
    e.preventDefault();
    $('#screen-enter-secret-key #key').removeClass('error');
});

$(document).on('submit', '#screen-enter-secret-key form', function (e) {
    e.preventDefault();

    dbSecretKey = $('#screen-enter-secret-key #key').val();

    var nm = new DBManager();
    nm.setDB(settings.path_to_db);
    nm.createDB();
    nm.pingKey(function () {
        renderNotesLinks();
        showScreenSearch();
        researchNotes();
    });

});

$(document).on('keyup', '#screen-change-secret-key #new-key-repeat, #screen-change-secret-key #new-key', function (e) {
    e.preventDefault();
    $('#screen-change-secret-key #new-key-repeat').removeClass('error').removeClass('equal');
    $('#screen-change-secret-key #new-key').removeClass('error').removeClass('equal');

    if ($('#screen-change-secret-key #new-key').val() == $('#screen-change-secret-key #new-key-repeat').val()) {
        $('#screen-change-secret-key #new-key-repeat').removeClass('error').addClass('equal');
    } else {
        $('#screen-change-secret-key #new-key-repeat').removeClass('equal').addClass('error');
    }
});

$(document).on('submit', '#screen-change-secret-key form', function (e) {
    e.preventDefault();

    if ($('#screen-change-secret-key #new-key').val() != $('#screen-change-secret-key #new-key-repeat').val()) {
        return;
    }

    dbChangedSecretKey = $('#screen-change-secret-key #new-key').val();

    var nm = new DBManager();
    nm.setDB(settings.path_to_db);
    nm.createDB();
    nm.pingKey(function () {
        renderNotesLinks();
        showScreenSearch();
        researchNotes();
    });

});

$(document).on('click', ".copy-password-button", function () {
    console.log($(this).data('password'));
    clipboard.writeText(''+$(this).data('password'));
});
<commit_msg>point<commit_after>/*
 The MIT License (MIT)

 Copyright (c) 2016 Sergei Tolokonnikov

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

$(document).ready(function () {

    createSettingsFileIfNotExists();

    loadAppSettings(function () {
        setColorTheme(settings.color_theme);
        $(".container").fadeIn(settings.animationSpeed);
        registerShortcuts();
        showScreenSearch();
        toggleSidebar();
        loadTodosFromSettings();
        loadNotificationsFromSettings();
        checkNotifications();
        renderNotesLinks();
    });

    var appTimer = setInterval(function () {
        watchTodoRemainds();
    }, 1000);

    $(document).on('click', "#button-settings-back", function () {
        activeScreen = 'search';
        showScreenSearch();

    });

    $(document).on('click', "#button-settings-save", function () {
        if (settings.path_to_db != $("#screen-settings #path-to-db").val()) {
            dbSecretKey = null;
        }
        settings.path_to_db = $("#screen-settings #path-to-db").val();
        settings.local_keymap = $("#screen-settings #local-keymap").val();
        settings.history_length = $("#screen-settings #history-length").val();
        settings.color_theme = $("[name=color_theme]:checked").val();
        setColorTheme(settings.color_theme);
        updateAppSettings();
        activeScreen = 'search';
        renderNotesLinks();
        showScreenSearch();
        researchNotes();
    });

    $(document).on('click', "#button-add-note", function () {
        showScreenEdit();
    });

    $(document).on('click', "#button-todo", function () {
        showScreenTodo();
    });

    $(document).on('click', "#button-notifications", function () {
        showScreenNotifications();
    });

    $(document).on('click', "#button-todo-back", function () {
        vmTodoList.editMode.enabled = false;
        showScreenSearch();
    });

    $(document).on('click', "#button-notifications-back", function () {
        showScreenSearch();
    });

    $(document).on('click', "#button-clips", function () {
        showScreenClips();
    });

    $(document).on('click', "#button-clips-back", function () {
        showScreenSearch();
    });

    $(document).on('click', "#button-gotoresult-forward", function () {
        if (!searchMatchesCount) return;
        gotoNextResult();
    });

    $(document).on('click', "#button-gotoresult-backward", function () {
        if (!searchMatchesCount) return;
        gotoPrevResult();
    });

    $(document).on('click', "#button-navigator-forward", function () {
        navigatorForward();
    });

    $(document).on('click', "#button-navigator-backward", function () {
        navigatorBackward();
    });

    $(document).on('click', "#button-history-back", function () {
        $("#input-search").blur();
        historyBack();
    });

    $(document).on('click', "#button-history-forward", function () {
        $("#input-search").blur();
        historyForward();
    });

    $(document).on('click', "#screen-settings #button-clear-history", function () {
        actionClearHistory();
    });

    $(document).on('click', '#notes-links-area .note-link', function (e) {
        triggerNoteLink(parseInt($(this).attr('data-id')));
        addToHistory($(this).attr('data-id'));
    });

    $(document).on('selectionchange', function (e) {
        if (stripHtml(getHTMLOfSelection()) == '') {
            clipTitle = clipBody = '';
            return;
        } else {
            var noteID = window.getSelection().getRangeAt(0).commonAncestorContainer
                .parentNode.parentNode.getAttribute('data-id') ||
                window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode.getAttribute('data-id') ||
                window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode.parentNode.parentNode.getAttribute('data-id');
            if (noteID === null) {
                return;
            }
            clipTitle = $(".note[data-id="+noteID+"]").find(".title").text();
            clipBody = stripHtml(getHTMLOfSelection());

        }

    });

    $(document).on('click', "#search-results-area .note", function (e) {
        var noteID = parseInt($(this).attr('data-id'));
        addToHistory(noteID);
    });

    $(document).on('click', "#search-results-area .btn", function (e) {
        return false;
    });

    $(document).on('mousedown', "#search-results-area .note", function (e) {
        if (e.which == 2) {
            //e.preventDefault();
            contextCurrentNoteID = parseInt($(this).attr('data-id'));
            actionEditNote(contextCurrentNoteID);
        }
    });

    $(document).on('click', ".button-edit-note", function () {
        actionEditNote(parseInt($(this).attr('data-id')));
    });

    $(document).on('click', "#button-clear-clips", function () {
        if (confirm('Are you sure you want to delete all clips?')) {
            clearClips();
        }

    });

    $(document).on('click', "#button-edit-back", function () {
        showScreenSearch();
    });
    $(document).on('click', "#button-about-back", function () {
        showScreenSearch();
    });
    $(document).on('click', "#button-change-secret-key-back", function () {
        showScreenSearch();
    });

    // $(document).on('mouseenter', ".note", function () {
    //     markActiveNoteLink(parseInt($(this).attr('data-id')));
    // });

    $("#screen-search #input-search").keyup(function (e) {
        $("#notes-links-area .note-link").removeClass('active');
        searchNotes($(this).val());
    });

    // $(document).on('keyup', "#screen-search #input-search", function (e) {
    //
    //
    //
    //
    // });

    $(document).on('keydown', "#screen-edit #title, #screen-edit #body", function (e) {

        if (addingFromClipboard || $("#screen-edit").attr('data-id') === undefined) {
            return;
        }
        if (!e.ctrlKey) {
            editorDataModified = true;
        }
        displayEditorSaveButton();
    });

    $(document).on('click', "#screen-edit #button-save", function () {

        if (!editorDataModified) return;

        dontCloseScreen = true;
        windowMustBeHidden = false;
        $("#screen-edit #button-ok").trigger('click');
    });

    $(document).on('click', "#screen-edit #button-ok", function () {
        var title = $("#screen-edit #title").val().trim();
        var body = $("#screen-edit #body").val().trim();
        if (body == '' && !vmPasswordsEditWidget.passwords.length) {
            alert('Field Body is required.');
            return;
        }
        if (!validatePasswordsEditWidget()) {
            alert('Incorrect passwords data!');
            return;
        }
        if (title == '') {
            var prefix = '#untitled ';
            if (addingFromClipboard) {
                prefix = '#clipboard ';
                addingFromClipboard = false;
            }
            title = prefix + body.substr(0, 30)+'...'.trim();
        }
        if ($("#screen-edit").attr('data-id') === undefined) {
            addNote(title, body);
        } else {
            updateNote($("#screen-edit").attr('data-id'), title, body);
        }
        if (windowMustBeHidden) {
            windowMustBeHidden = false;
            const { remote } = require('electron');
            remote.BrowserWindow.getFocusedWindow().minimize();
        }
        editorDataModified = false;
        displayEditorSaveButton();
    });

    $(document).on('click', ".button-delete-note", function () {
        actionDeleteNote($(this).attr('data-id'));
    });

    $(document).on('click', "#clips-area .clip", function () {
        currentClipID = $(this).data('id');
        var clip = $(this).find(".clip-text").text();
        clipboard.writeText(clip);
        clipboard.writeText(clip, 'selection');
        $("#button-clips-back").trigger('click');
    });

    $(document).on('contextmenu', "#clips-area .clip", function (e) {
        e.preventDefault();
        currentClipID = $(this).data('id');
        clipsContextMenu.popup(remote.getCurrentWindow());
    });

    $(document).on('click', "#button-sidebar-toggle", function () {
        toggleSidebar();
    });

    $(document).on('click', ".edit-todo-button", function () {
        $('body').animate({
            scrollTop: $("#todo-list .editor-group[data-id="+$(this).data('id')+"]").offset().top - 93
        }, settings.settings.animationSpeed);
    });

    function setSidebarHeight() {
        var h = $(window).height();
        $('#sidebar').css('height', (h - 89 - 26)+'px');
    }
    function setEditorHeight() {
        var h = $(window).height();
        $('#screen-edit #body').css('height', (h - 175)+'px');
    }
    $(window).load(function (e) {
        setSidebarHeight();
        setEditorHeight();
    });
    $(window).resize(function (e) {
        setSidebarHeight();
        setEditorHeight();
    });

});

$(document).on('contextmenu', '#search-results-area .note', function (e) {
    e.preventDefault();
    contextCurrentNoteID = parseInt($(this).attr('data-id'));
    searchResultsContextMenu.popup(remote.getCurrentWindow());
});

$(document).on('contextmenu', '#notes-links-area .note-link', function (e) {
    e.preventDefault();
    contextCurrentNoteID = parseInt($(this).attr('data-id'));
    notesLinksContextMenu.popup(remote.getCurrentWindow());
});

$(document).on('mousedown', "#notes-links-area .note-link", function (e) {
    if (e.which == 2) {
        //e.preventDefault();
        contextCurrentNoteID = parseInt($(this).attr('data-id'));
        actionEditNote(contextCurrentNoteID);
    }
});

$(document).on('contextmenu', '#screen-edit #body', function (e) {
    e.preventDefault();
    editorBodyContextMenu.popup(remote.getCurrentWindow());
});

$(document).on('contextmenu', '#screen-edit #title', function (e) {
    e.preventDefault();
    editorTitleContextMenu.popup(remote.getCurrentWindow());
});

$(document).on('submit', '#screen-edit form', function (e) {
    e.preventDefault();
    $('#screen-edit #body').focus();
});

$(window).scroll(function (e) {
    if (activeScreen == 'search') {
        windowScrollTop = $(window).scrollTop();
    }
});

$(document).on('keyup', '#screen-set-secret-key #key-repeat, #screen-set-secret-key #key', function (e) {
    e.preventDefault();
    $('#screen-set-secret-key #key-repeat').removeClass('error').removeClass('equal');
    $('#screen-set-secret-key #key').removeClass('error').removeClass('equal');

    if ($('#screen-set-secret-key #key').val() == $('#screen-set-secret-key #key-repeat').val()) {
        $('#screen-set-secret-key #key-repeat').removeClass('error').addClass('equal');
    } else {
        $('#screen-set-secret-key #key-repeat').removeClass('equal').addClass('error');
    }
});

$(document).on('submit', '#screen-set-secret-key form', function (e) {
    e.preventDefault();

    if ($('#screen-set-secret-key #key').val() != $('#screen-set-secret-key #key-repeat').val()) {
        return;
    }

    dbSecretKey = $('#screen-set-secret-key #key').val();

    var nm = new DBManager();
    nm.setDB(settings.path_to_db);
    nm.createDB();
    nm.pingKey(function () {
        renderNotesLinks();
        showScreenSearch();
        researchNotes();
    });

});

$(document).on('keyup', '#screen-enter-secret-key #key', function (e) {
    e.preventDefault();
    $('#screen-enter-secret-key #key').removeClass('error');
});

$(document).on('submit', '#screen-enter-secret-key form', function (e) {
    e.preventDefault();

    dbSecretKey = $('#screen-enter-secret-key #key').val();

    var nm = new DBManager();
    nm.setDB(settings.path_to_db);
    nm.createDB();
    nm.pingKey(function () {
        renderNotesLinks();
        showScreenSearch();
        researchNotes();
    });

});

$(document).on('keyup', '#screen-change-secret-key #new-key-repeat, #screen-change-secret-key #new-key', function (e) {
    e.preventDefault();
    $('#screen-change-secret-key #new-key-repeat').removeClass('error').removeClass('equal');
    $('#screen-change-secret-key #new-key').removeClass('error').removeClass('equal');

    if ($('#screen-change-secret-key #new-key').val() == $('#screen-change-secret-key #new-key-repeat').val()) {
        $('#screen-change-secret-key #new-key-repeat').removeClass('error').addClass('equal');
    } else {
        $('#screen-change-secret-key #new-key-repeat').removeClass('equal').addClass('error');
    }
});

$(document).on('submit', '#screen-change-secret-key form', function (e) {
    e.preventDefault();

    if ($('#screen-change-secret-key #new-key').val() != $('#screen-change-secret-key #new-key-repeat').val()) {
        return;
    }

    dbChangedSecretKey = $('#screen-change-secret-key #new-key').val();

    var nm = new DBManager();
    nm.setDB(settings.path_to_db);
    nm.createDB();
    nm.pingKey(function () {
        renderNotesLinks();
        showScreenSearch();
        researchNotes();
    });

});

$(document).on('click', ".copy-password-button", function () {
    clipboard.writeText(''+$(this).data('password'));
});
<|endoftext|>


<commit_before>// =========================================================================
// Open external links in a new window
// =========================================================================

"use strict";

(function (document, window, Ornament, $) {

  var config = {
    noOpener: true,
    noFollow: true,
    trackExternalLinks: true,
    trackExternalCategory: "External Link",
    externalFileExtensionSelectors: [
      "doc",
      "docx",
      "pdf",
      "ppt",
      "pptx",
      "xls",
      "xlsx"
    ],
    externalLinkSelectors: [
      "[href^='http://']",
      "[href^='https://']"
    ],
    internalLinkSelectors: [
      "[rel='internal']",
      "[data-internal-link]"
    ]
  }

  // Merge file extension selectors with configured external link
  // selectors
  config.externalFileExtensionSelectors.forEach(function(selector) {
    config.externalLinkSelectors.push("[href$='." + selector + "']");
    config.externalLinkSelectors.push("[href$='." + selector.toUpperCase() + "']");
  });

  var bindExternalLink = function(node) {
    var isExternal = true;
    config.internalLinkSelectors.forEach(function(selector) {
      if(node.matches(selector)) {
        isExternal = false;
      }
    });
    if(isExternal) {
      node.setAttribute("target", "_blank");
      var rel = node.getAttribute("rel") || "";
      var updateRel = false;
      // Update rel attribute with noopener and nofollow if configured to
      if(config.noOpener && rel.indexOf("noopener") === -1) {
        rel += " noopener";
        updateRel = true;
      }
      if(config.noFollow && rel.indexOf("nofollow") === -1) {
        rel += " nofollow";
        updateRel = true;
      }
      if(updateRel) {
        node.setAttribute("rel", rel);
      }
      // Event tracking for external links
      if(config.trackExternalLinks && Ornament.Components.Analytics && Ornament.Components.Analytics.trackingType) {
        Ornament.Components.Analytics.trackLink($button);
      }
    }
  }

  // Loop over all our external links and target them for
  // a new window
  var init = function(){
    config.externalLinkSelectors.forEach(function(selector){
      var externalLinks = document.querySelectorAll(selector);
      for(var nodeCount = 0; nodeCount < externalLinks.length; nodeCount++) {
        bindExternalLink(externalLinks[nodeCount]);
      }
    });
  }

  // Run init onLoad, this isn't a component so it won't run automatically
  Ornament.onLoad(init);

  // Expose to Ornament API
  Ornament.U.ExternalLinks = {
    config: config,
    bindExternalLink: bindExternalLink,
    init: init
  }

}(document, window, Ornament, jQuery));<commit_msg>Fixed issue in external links<commit_after>// =========================================================================
// Open external links in a new window
// =========================================================================

"use strict";

(function (document, window, Ornament, $) {

  var config = {
    noOpener: true,
    noFollow: true,
    trackExternalLinks: true,
    trackExternalCategory: "External Link",
    externalFileExtensionSelectors: [
      "doc",
      "docx",
      "pdf",
      "ppt",
      "pptx",
      "xls",
      "xlsx"
    ],
    externalLinkSelectors: [
      "[href^='http://']",
      "[href^='https://']"
    ],
    internalLinkSelectors: [
      "[rel='internal']",
      "[data-internal-link]"
    ]
  }

  // Merge file extension selectors with configured external link
  // selectors
  config.externalFileExtensionSelectors.forEach(function(selector) {
    config.externalLinkSelectors.push("[href$='." + selector + "']");
    config.externalLinkSelectors.push("[href$='." + selector.toUpperCase() + "']");
  });

  var bindExternalLink = function(node) {
    var isExternal = true;
    config.internalLinkSelectors.forEach(function(selector) {
      if(node.matches(selector)) {
        isExternal = false;
      }
    });
    if(isExternal) {
      node.setAttribute("target", "_blank");
      var rel = node.getAttribute("rel") || "";
      var updateRel = false;
      // Update rel attribute with noopener and nofollow if configured to
      if(config.noOpener && rel.indexOf("noopener") === -1) {
        rel += " noopener";
        updateRel = true;
      }
      if(config.noFollow && rel.indexOf("nofollow") === -1) {
        rel += " nofollow";
        updateRel = true;
      }
      if(updateRel) {
        node.setAttribute("rel", rel);
      }
      // Event tracking for external links
      if(config.trackExternalLinks && Ornament.Components.Analytics && Ornament.Components.Analytics.trackingType) {
        Ornament.Components.Analytics.trackLink($(node));
      }
    }
  }

  // Loop over all our external links and target them for
  // a new window
  var init = function(){
    config.externalLinkSelectors.forEach(function(selector){
      var externalLinks = document.querySelectorAll(selector);
      for(var nodeCount = 0; nodeCount < externalLinks.length; nodeCount++) {
        bindExternalLink(externalLinks[nodeCount]);
      }
    });
  }

  // Run init onLoad, this isn't a component so it won't run automatically
  Ornament.onLoad(init);

  // Expose to Ornament API
  Ornament.U.ExternalLinks = {
    config: config,
    bindExternalLink: bindExternalLink,
    init: init
  }

}(document, window, Ornament, jQuery));<|endoftext|>


<commit_before>"use strict";
var jsonApi = module.exports = { };
jsonApi._resources = { };
jsonApi._apiConfig = { };

var _ = require("underscore");
var ourJoi = require("./ourJoi.js");
var router = require("./router.js");
var responseHelper = require("./responseHelper.js");
var routes = require("./routes");
var mockHandlers = require("./mockHandlers.js");

jsonApi.Joi = ourJoi.Joi;
jsonApi.mockHandlers = mockHandlers.handlers;

jsonApi.setConfig = function(apiConfig) {
  jsonApi._apiConfig = apiConfig;
  jsonApi._apiConfig.base = jsonApi._cleanBaseUrl(jsonApi._apiConfig.base);
  jsonApi._apiConfig.pathPrefix = jsonApi._concatenateUrlPrefix(jsonApi._apiConfig);
  responseHelper.setBaseUrl(jsonApi._apiConfig.pathPrefix);
  responseHelper.setMetadata(jsonApi._apiConfig.meta);
};

jsonApi.authenticate = router.authenticateWith;

jsonApi._concatenateUrlPrefix = function(config) {
  var pathPrefix = "";
  pathPrefix += (config.protocol || "https") + "://";
  pathPrefix += (config.hostname || "localhost");
  if (config.port) pathPrefix += ":" + config.port;
  pathPrefix += config.base;
  return pathPrefix;
};

jsonApi._cleanBaseUrl = function(base) {
  if (!base) {
    base = "";
  }
  if (base[0] !== "/") {
    base = "/" + base;
  }
  if (base[base.length - 1] !== "/") {
    base += "/";
  }
  return base;
};

jsonApi.define = function(resourceConfig) {
  resourceConfig.namespace = resourceConfig.namespace || "default";
  resourceConfig.searchParams = resourceConfig.searchParams || { };
  jsonApi._resources[resourceConfig.resource] = resourceConfig;

  if (resourceConfig.handlers.initialise) {
    resourceConfig.handlers.initialise(resourceConfig);
  }

  Object.keys(resourceConfig.attributes).forEach(function(attribute) {
    if (!attribute.match(/^[A-Za-z0-9\-\_]*$/)) {
      throw new Error("Attribute '" + attribute + "' on " + resourceConfig.resource + " contains illegal characters!");
    }
  });

  resourceConfig.searchParams = _.extend({
    type: ourJoi.Joi.any().required().valid(resourceConfig.resource)
      .description("Always \"" + resourceConfig.resource + "\"")
      .example(resourceConfig.resource),
    sort: ourJoi.Joi.any()
      .description("An attribute to sort by")
      .example("title"),
    filter: ourJoi.Joi.any()
      .description("An attribute+value to filter by")
      .example("title"),
    fields: ourJoi.Joi.any()
      .description("An attribute+value to filter by")
      .example("title"),
    include: ourJoi.Joi.any()
      .description("An attribute to include")
      .example("title"),
    relationships: ourJoi.Joi.any()
      .description("An attribute to include")
      .example("title")
  }, resourceConfig.searchParams);

  resourceConfig.attributes = _.extend({
    id: ourJoi.Joi.string().required()
      .description("Unique resource identifier")
      .example("1234"),
    type: ourJoi.Joi.string().required().valid(resourceConfig.resource)
      .description("Always \"" + resourceConfig.resource + "\"")
      .example(resourceConfig.resource),
    meta: ourJoi.Joi.object().optional()
  }, resourceConfig.attributes);

  resourceConfig.onCreate = _.pick.apply(_, [].concat(resourceConfig.attributes, Object.keys(resourceConfig.attributes).filter(function(i) {
    return (resourceConfig.attributes[i]._meta.indexOf("readonly") === -1) && (!(resourceConfig.attributes[i]._settings || { }).__as);
  })));
};

jsonApi.onUncaughtException = function(errHandler) {
  jsonApi._errHandler = errHandler;
};

jsonApi.start = function() {
  routes.register();
  router.listen(jsonApi._apiConfig.port);
};

jsonApi.close = function() {
  router.close();
  for (var i in jsonApi._resources) {
    var resourceConfig = jsonApi._resources[i];
    if (resourceConfig.handlers.close) resourceConfig.handlers.close();
  }
};
<commit_msg>Respond with absolute urls throughout<commit_after>"use strict";
var jsonApi = module.exports = { };
jsonApi._resources = { };
jsonApi._apiConfig = { };

var _ = require("underscore");
var ourJoi = require("./ourJoi.js");
var router = require("./router.js");
var responseHelper = require("./responseHelper.js");
var routes = require("./routes");
var mockHandlers = require("./mockHandlers.js");
var url = require("url");

jsonApi.Joi = ourJoi.Joi;
jsonApi.mockHandlers = mockHandlers.handlers;

jsonApi.setConfig = function(apiConfig) {
  jsonApi._apiConfig = apiConfig;
  jsonApi._apiConfig.base = jsonApi._cleanBaseUrl(jsonApi._apiConfig.base);
  jsonApi._apiConfig.pathPrefix = jsonApi._concatenateUrlPrefix(jsonApi._apiConfig);
  responseHelper.setBaseUrl(jsonApi._apiConfig.pathPrefix);
  responseHelper.setMetadata(jsonApi._apiConfig.meta);
};

jsonApi.authenticate = router.authenticateWith;

jsonApi._concatenateUrlPrefix = function(config) {
  return url.format({
    protocol: config.protocol,
    hostname: config.hostname,
    port: config.port,
    pathname: config.base
  });
};

jsonApi._cleanBaseUrl = function(base) {
  if (!base) {
    base = "";
  }
  if (base[0] !== "/") {
    base = "/" + base;
  }
  if (base[base.length - 1] !== "/") {
    base += "/";
  }
  return base;
};

jsonApi.define = function(resourceConfig) {
  resourceConfig.namespace = resourceConfig.namespace || "default";
  resourceConfig.searchParams = resourceConfig.searchParams || { };
  jsonApi._resources[resourceConfig.resource] = resourceConfig;

  if (resourceConfig.handlers.initialise) {
    resourceConfig.handlers.initialise(resourceConfig);
  }

  Object.keys(resourceConfig.attributes).forEach(function(attribute) {
    if (!attribute.match(/^[A-Za-z0-9\-\_]*$/)) {
      throw new Error("Attribute '" + attribute + "' on " + resourceConfig.resource + " contains illegal characters!");
    }
  });

  resourceConfig.searchParams = _.extend({
    type: ourJoi.Joi.any().required().valid(resourceConfig.resource)
      .description("Always \"" + resourceConfig.resource + "\"")
      .example(resourceConfig.resource),
    sort: ourJoi.Joi.any()
      .description("An attribute to sort by")
      .example("title"),
    filter: ourJoi.Joi.any()
      .description("An attribute+value to filter by")
      .example("title"),
    fields: ourJoi.Joi.any()
      .description("An attribute+value to filter by")
      .example("title"),
    include: ourJoi.Joi.any()
      .description("An attribute to include")
      .example("title"),
    relationships: ourJoi.Joi.any()
      .description("An attribute to include")
      .example("title")
  }, resourceConfig.searchParams);

  resourceConfig.attributes = _.extend({
    id: ourJoi.Joi.string().required()
      .description("Unique resource identifier")
      .example("1234"),
    type: ourJoi.Joi.string().required().valid(resourceConfig.resource)
      .description("Always \"" + resourceConfig.resource + "\"")
      .example(resourceConfig.resource),
    meta: ourJoi.Joi.object().optional()
  }, resourceConfig.attributes);

  resourceConfig.onCreate = _.pick.apply(_, [].concat(resourceConfig.attributes, Object.keys(resourceConfig.attributes).filter(function(i) {
    return (resourceConfig.attributes[i]._meta.indexOf("readonly") === -1) && (!(resourceConfig.attributes[i]._settings || { }).__as);
  })));
};

jsonApi.onUncaughtException = function(errHandler) {
  jsonApi._errHandler = errHandler;
};

jsonApi.start = function() {
  routes.register();
  router.listen(jsonApi._apiConfig.port);
};

jsonApi.close = function() {
  router.close();
  for (var i in jsonApi._resources) {
    var resourceConfig = jsonApi._resources[i];
    if (resourceConfig.handlers.close) resourceConfig.handlers.close();
  }
};
<|endoftext|>


<commit_before>window.TextAreaEditorTest = new Class( {
   Implements : [Events, JsTestClass, Options],
   Binds : ['messageSubscriber', 'onAnchorClick', 'onEditorAttached'],

   options : {
      testMethods : [
          { method : 'attach_instantiatesMooEditable', isAsynchron : true },
          { method : 'onEditorClick_whenAnchorIsTheEventSource_invokesOnClick', isAsynchron : true },
          { method : 'textAddLink_whenNoTextIsSelected_showsNotification', isAsynchron : true },
          { method : 'textAddLink_whenTextIsSelected_showsDocumentExplorer', isAsynchron : true },
          { method : 'textAddLink_whenReceivesDocumentSelectedMessage_addsOrChangesAnchorHref', isAsynchron : true }]
   },

   constants : {
      LANGUAGE : "hu",
      TEXT_AREA_ID : "EditorContainer",
      WEBUI_CONFIGURATION_URI : "../TextAreaEditor/WebUIConfiguration.xml"
   },

   initialize : function( options ) {
      this.setOptions( options );

      this.clickEvent;
      this.internationalization;
      this.lastMessage;
      this.locale = new Locale({ language : this.constants.LANGUAGE });
      this.textAreaEditor;
      this.textAreaElement;
      this.webUIConfiguration;
      this.webUIController;
      this.webUILogger;
      this.webUIMessageBus;
   },

   beforeEachTest : function(){
      this.webUIConfiguration = new WebUIConfiguration( this.constants.WEBUI_CONFIGURATION_URI );
      this.webUILogger = new WebUILogger( this.webUIConfiguration );
      this.webUIMessageBus = new WebUIMessageBus();
      this.webUIMessageBus.subscribeToMessage( MenuSelectedMessage, this.messageSubscriber );
      this.internationalization = new XMLResourceBundle( this.webUIConfiguration );
      this.internationalization.load( this.locale );

      this.textAreaEditor = new TextAreaEditor( this.internationalization, { onEditorAttached : this.onEditorAttached, subscribeToWebUIMessages : [DocumentSelectedMessage] });
      this.textAreaElement = $( this.constants.TEXT_AREA_ID );
   },

   afterEachTest : function (){
      this.textAreaEditor.detach();
      this.webUIMessageBus.tearDown();
      this.lastMessage = null;
   },

   attach_instantiatesMooEditable : function() {
      this.testCaseChain.chain(
         function(){
            this.textAreaEditor.instantiateTools = spy( this.textAreaEditor.instantiateTools );
            this.textAreaEditor.attach( this.textAreaElement );
         }.bind( this ),
         function(){
            verify( this.textAreaEditor.instantiateTools );
            assertThat( instanceOf( this.textAreaEditor.mooEditable, MooEditable ), is( true ));
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   onEditorClick_whenAnchorIsTheEventSource_invokesOnClick : function() {
      this.testCaseChain.chain(
         function(){ this.textAreaEditor.attach( this.textAreaElement ); }.bind( this ),
         function(){
            this.textAreaEditor.onEditorClick = spy( this.textAreaEditor.onEditorClick );

            var anchorElement = new Element( 'a', { events: { click: this.onAnchorClick }});
            this.textAreaEditor.mooEditable.doc.body.grab( anchorElement );
            anchorElement.click();

            this.textAreaEditor.mooEditable.editorClick( this.clickEvent );

            verify( this.textAreaEditor.onEditorClick )();
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   textAddLink_whenNoTextIsSelected_showsNotification : function() {
      this.testCaseChain.chain(
         function(){ this.textAreaEditor.attach( this.textAreaElement ); }.bind( this ),
         function(){
            this.textAreaEditor.textAddLink();
            assertThat( this.lastMessage.getActivityType(), equalTo( DesktopWindow.Activity.SHOW_NOTIFICATION ));
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   textAddLink_whenTextIsSelected_showsDocumentExplorer : function() {
      this.testCaseChain.chain(
         function(){ this.textAreaEditor.attach( this.textAreaElement ); }.bind( this ),
         function(){
            this.selectElementContents( this.textAreaEditor.getMooEditable().win, this.textAreaEditor.getMooEditable().doc, this.textAreaEditor.getMooEditable().doc.getElementsByTagName( "body" )[0] );
            this.textAreaEditor.textAddLink();
            assertThat( this.lastMessage.getActivityType(), equalTo( DesktopWindow.Activity.SHOW_WINDOW ));
            assertThat( this.lastMessage.getWindowName(), equalTo( SYSTEM_WINDOWS.DOCUMENT_EXPLORER ));
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   textAddLink_whenReceivesDocumentSelectedMessage_addsOrChangesAnchorHref : function() {
      this.testCaseChain.chain(
         function(){ this.textAreaEditor.attach( this.textAreaElement ); }.bind( this ),
         function(){
            this.selectElementContents( this.textAreaEditor.getMooEditable().win, this.textAreaEditor.getMooEditable().doc, this.textAreaEditor.getMooEditable().doc.getElementsByTagName( "body" )[0] );
            this.textAreaEditor.textAddLink();
            var message = new DocumentSelectedMessage({ originator : SYSTEM_WINDOWS.DOCUMENT_EXPLORER, documentURI : 'http://processpuzzle.com' });
            this.webUIMessageBus.notifySubscribers( message );
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   messageSubscriber : function( webUIMessage ){
      this.lastMessage = webUIMessage;
   },

   onEditorAttached : function(){
      this.testCaseChain.callChain();
   },

   //Protected, private helper methods
   onAnchorClick : function( event ){
      this.clickEvent = event;
   },

   selectElementContents : function( targetWindow, targetDocument, el ) {
      var body = targetDocument.body, range, sel;
      if (body.createTextRange) {
          range = body.createTextRange();
          range.moveToElementText(el);
          range.select();
      } else if (targetDocument.createRange && window.getSelection) {
          range = targetDocument.createRange();
          range.selectNodeContents(el);
          sel = targetWindow.getSelection();
          sel.removeAllRanges();
          sel.addRange(range);
      }
   }.protect()
});<commit_msg>Remove TextAreaEditor.onClick test.<commit_after>window.TextAreaEditorTest = new Class( {
   Implements : [Events, JsTestClass, Options],
   Binds : ['messageSubscriber', 'onAnchorClick', 'onEditorAttached'],

   options : {
      testMethods : [
          { method : 'attach_instantiatesMooEditable', isAsynchron : true },
          { method : 'textAddLink_whenNoTextIsSelected_showsNotification', isAsynchron : true },
          { method : 'textAddLink_whenTextIsSelected_showsDocumentExplorer', isAsynchron : true },
          { method : 'textAddLink_whenReceivesDocumentSelectedMessage_addsOrChangesAnchorHref', isAsynchron : true }]
   },

   constants : {
      LANGUAGE : "hu",
      TEXT_AREA_ID : "EditorContainer",
      WEBUI_CONFIGURATION_URI : "../TextAreaEditor/WebUIConfiguration.xml"
   },

   initialize : function( options ) {
      this.setOptions( options );

      this.clickEvent;
      this.internationalization;
      this.lastMessage;
      this.locale = new Locale({ language : this.constants.LANGUAGE });
      this.textAreaEditor;
      this.textAreaElement;
      this.webUIConfiguration;
      this.webUIController;
      this.webUILogger;
      this.webUIMessageBus;
   },

   beforeEachTest : function(){
      this.webUIConfiguration = new WebUIConfiguration( this.constants.WEBUI_CONFIGURATION_URI );
      this.webUILogger = new WebUILogger( this.webUIConfiguration );
      this.webUIMessageBus = new WebUIMessageBus();
      this.webUIMessageBus.subscribeToMessage( MenuSelectedMessage, this.messageSubscriber );
      this.internationalization = new XMLResourceBundle( this.webUIConfiguration );
      this.internationalization.load( this.locale );

      this.textAreaEditor = new TextAreaEditor( this.internationalization, { onEditorAttached : this.onEditorAttached, subscribeToWebUIMessages : [DocumentSelectedMessage] });
      this.textAreaElement = $( this.constants.TEXT_AREA_ID );
   },

   afterEachTest : function (){
      this.textAreaEditor.detach();
      this.webUIMessageBus.tearDown();
      this.lastMessage = null;
   },

   attach_instantiatesMooEditable : function() {
      this.testCaseChain.chain(
         function(){
            this.textAreaEditor.instantiateTools = spy( this.textAreaEditor.instantiateTools );
            this.textAreaEditor.attach( this.textAreaElement );
         }.bind( this ),
         function(){
            verify( this.textAreaEditor.instantiateTools );
            assertThat( instanceOf( this.textAreaEditor.mooEditable, MooEditable ), is( true ));
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   onEditorClick_whenAnchorIsTheEventSource_invokesOnClick : function() {
      this.testCaseChain.chain(
         function(){ this.textAreaEditor.attach( this.textAreaElement ); }.bind( this ),
         function(){
            this.textAreaEditor.onEditorClick = spy( this.textAreaEditor.onEditorClick );

            var anchorElement = new Element( 'a', { events: { click: this.onAnchorClick }});
            this.textAreaEditor.mooEditable.doc.body.grab( anchorElement );
            anchorElement.click();

            this.textAreaEditor.mooEditable.editorClick( this.clickEvent );

            verify( this.textAreaEditor.onEditorClick )();
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   textAddLink_whenNoTextIsSelected_showsNotification : function() {
      this.testCaseChain.chain(
         function(){ this.textAreaEditor.attach( this.textAreaElement ); }.bind( this ),
         function(){
            this.textAreaEditor.textAddLink();
            assertThat( this.lastMessage.getActivityType(), equalTo( DesktopWindow.Activity.SHOW_NOTIFICATION ));
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   textAddLink_whenTextIsSelected_showsDocumentExplorer : function() {
      this.testCaseChain.chain(
         function(){ this.textAreaEditor.attach( this.textAreaElement ); }.bind( this ),
         function(){
            this.selectElementContents( this.textAreaEditor.getMooEditable().win, this.textAreaEditor.getMooEditable().doc, this.textAreaEditor.getMooEditable().doc.getElementsByTagName( "body" )[0] );
            this.textAreaEditor.textAddLink();
            assertThat( this.lastMessage.getActivityType(), equalTo( DesktopWindow.Activity.SHOW_WINDOW ));
            assertThat( this.lastMessage.getWindowName(), equalTo( SYSTEM_WINDOWS.DOCUMENT_EXPLORER ));
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   textAddLink_whenReceivesDocumentSelectedMessage_addsOrChangesAnchorHref : function() {
      this.testCaseChain.chain(
         function(){ this.textAreaEditor.attach( this.textAreaElement ); }.bind( this ),
         function(){
            this.selectElementContents( this.textAreaEditor.getMooEditable().win, this.textAreaEditor.getMooEditable().doc, this.textAreaEditor.getMooEditable().doc.getElementsByTagName( "body" )[0] );
            this.textAreaEditor.textAddLink();
            var message = new DocumentSelectedMessage({ originator : SYSTEM_WINDOWS.DOCUMENT_EXPLORER, documentURI : 'http://processpuzzle.com' });
            this.webUIMessageBus.notifySubscribers( message );
            this.testMethodReady();
         }.bind( this )
      ).callChain();
   },

   messageSubscriber : function( webUIMessage ){
      this.lastMessage = webUIMessage;
   },

   onEditorAttached : function(){
      this.testCaseChain.callChain();
   },

   //Protected, private helper methods
   onAnchorClick : function( event ){
      this.clickEvent = event;
   },

   selectElementContents : function( targetWindow, targetDocument, el ) {
      var body = targetDocument.body, range, sel;
      if (body.createTextRange) {
          range = body.createTextRange();
          range.moveToElementText(el);
          range.select();
      } else if (targetDocument.createRange && window.getSelection) {
          range = targetDocument.createRange();
          range.selectNodeContents(el);
          sel = targetWindow.getSelection();
          sel.removeAllRanges();
          sel.addRange(range);
      }
   }.protect()
});<|endoftext|>


<commit_before>/*global define*/
define([
        './freezeObject'
    ], function(
        freezeObject) {
    'use strict';

    /**
     * Returns the first parameter if not undefined, otherwise the second parameter.
     * Useful for setting a default value for a parameter.
     *
     * @exports defaultValue
     *
     * @param {*} a
     * @param {*} b
     * @returns {*} Returns the first parameter if not undefined, otherwise the second parameter.
     *
     * @example
     * param = Cesium.defaultValue(param, 'default');
     */
    function defaultValue(a, b) {
        if (a !== undefined) {
            return a;
        }
        return b;
    }

    /**
     * A frozen empty object that can be used as the default value for options passed as
     * an object literal.
     */
    defaultValue.EMPTY_OBJECT = freezeObject({});

    return defaultValue;
});
<commit_msg>defaultValue check for null<commit_after>/*global define*/
define([
        './freezeObject'
    ], function(
        freezeObject) {
    'use strict';

    /**
     * Returns the first parameter if not undefined, otherwise the second parameter.
     * Useful for setting a default value for a parameter.
     *
     * @exports defaultValue
     *
     * @param {*} a
     * @param {*} b
     * @returns {*} Returns the first parameter if not undefined, otherwise the second parameter.
     *
     * @example
     * param = Cesium.defaultValue(param, 'default');
     */
    function defaultValue(a, b) {
        if (a !== undefined && a !== null) {
            return a;
        }
        return b;
    }

    /**
     * A frozen empty object that can be used as the default value for options passed as
     * an object literal.
     */
    defaultValue.EMPTY_OBJECT = freezeObject({});

    return defaultValue;
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var _ = require('lodash');
var crypto = require('crypto');

/**
 * Returns a plugin that will parse the client's Authorization header.
 *
 * Subsequent handlers will see `req.authorization`, which looks like:
 *
 * {
 *   scheme: <Basic|Signature|...>,
 *   credentials: <Undecoded value of header>,
 *   basic: {
 *     username: $user
 *     password: $password
 *   }
 * }
 *
 * `req.username` will also be set, and defaults to 'anonymous'.
 *
 * @return {Function} restify handler.
 * @throws {TypeError} on bad input
 */

module.exports = function( InvalidHeaderError, NotAuthorizedError ) {

  var parseAuthorization = function( req, res, next ) {

    var credentialList = nconf.get('Security:Credentials'),
        error,
        authorizationPieces,
        secret,
        checkSignatureString,
        checkSignatureBase64;

    req.authorization = {};
    req.username      = 'anonymous';

    if ( !req.headers.authorization ) {
      return next( new InvalidHeaderError('Authorization header required.') );
    }

    authorizationPieces = req.headers.authorization.split(' ', 2);

    if ( !authorizationPieces || authorizationPieces.length !== 2 ) {
      return next( new InvalidHeaderError('Authorization header is invalid.') );
    }

    req.authorization.scheme      = authorizationPieces[0];
    req.authorization.credentials = authorizationPieces[1];

    if ( req.authorization.scheme !== nconf.get('Security:Scheme') ) {
      return next( new InvalidHeaderError('Authorization scheme is invalid.') );
    }

    if ( !req.headers[ nconf.get('Security:DateIdentifier').toLowerCase() ] ) {
      return next( new InvalidHeaderError('Authorization header is invalid: "' + nconf.get('Security:DateIdentifier') + '" missing') );
    }

    req.authorization[ req.authorization.scheme ] = {
      key       : req.authorization.credentials.split(':', 2)[0],
      signature : req.authorization.credentials.split(':', 2)[1],
      date      : req.headers[ nconf.get('Security:DateIdentifier') ]
    };

    // check if key is known & grab infos
    if ( !credentialList[ req.authorization[req.authorization.scheme].key ] ) {
      return next( new NotAuthorizedError('Authorization key unknown.') );
    }
    secret                    = credentialList[ req.authorization[req.authorization.scheme].key ].secret;
    req.username              = credentialList[ req.authorization[req.authorization.scheme].key ].username;
    req.authorization.isAdmin = credentialList[ req.authorization[req.authorization.scheme].key ].admin;

    // calc check signature
    checkSignatureString = crypto.createHmac('sha1', secret )
                                 .update( req.authorization[ req.authorization.scheme ].date )
                                 .digest('hex');
    checkSignatureBase64 = new Buffer( checkSignatureString ).toString( 'base64' );

    // check signature
    if ( checkSignatureBase64 !== req.authorization[ req.authorization.scheme ].signature ) {
      return next( new NotAuthorizedError('Authorization signature is invalid.') );
    }

    return next();

  };

  return parseAuthorization;

};
<commit_msg>Fix: DateIdentifier to lower case<commit_after>
/**
 * Module dependencies.
 */

var _ = require('lodash');
var crypto = require('crypto');

/**
 * Returns a plugin that will parse the client's Authorization header.
 *
 * Subsequent handlers will see `req.authorization`, which looks like:
 *
 * {
 *   scheme: <Basic|Signature|...>,
 *   credentials: <Undecoded value of header>,
 *   basic: {
 *     username: $user
 *     password: $password
 *   }
 * }
 *
 * `req.username` will also be set, and defaults to 'anonymous'.
 *
 * @return {Function} restify handler.
 * @throws {TypeError} on bad input
 */

module.exports = function( InvalidHeaderError, NotAuthorizedError ) {

  var parseAuthorization = function( req, res, next ) {

    var credentialList = nconf.get('Security:Credentials'),
        error,
        authorizationPieces,
        secret,
        checkSignatureString,
        checkSignatureBase64;

    req.authorization = {};
    req.username      = 'anonymous';

    if ( !req.headers.authorization ) {
      return next( new InvalidHeaderError('Authorization header required.') );
    }

    authorizationPieces = req.headers.authorization.split(' ', 2);

    if ( !authorizationPieces || authorizationPieces.length !== 2 ) {
      return next( new InvalidHeaderError('Authorization header is invalid.') );
    }

    req.authorization.scheme      = authorizationPieces[0];
    req.authorization.credentials = authorizationPieces[1];

    if ( req.authorization.scheme !== nconf.get('Security:Scheme') ) {
      return next( new InvalidHeaderError('Authorization scheme is invalid.') );
    }

    if ( !req.headers[ nconf.get('Security:DateIdentifier').toLowerCase() ] ) {
      return next( new InvalidHeaderError('Authorization header is invalid: "' + nconf.get('Security:DateIdentifier') + '" missing') );
    }

    req.authorization[ req.authorization.scheme ] = {
      key       : req.authorization.credentials.split(':', 2)[0],
      signature : req.authorization.credentials.split(':', 2)[1],
      date      : req.headers[ nconf.get('Security:DateIdentifier').toLowerCase() ]
    };

    // check if key is known & grab infos
    if ( !credentialList[ req.authorization[req.authorization.scheme].key ] ) {
      return next( new NotAuthorizedError('Authorization key unknown.') );
    }
    secret                    = credentialList[ req.authorization[req.authorization.scheme].key ].secret;
    req.username              = credentialList[ req.authorization[req.authorization.scheme].key ].username;
    req.authorization.isAdmin = credentialList[ req.authorization[req.authorization.scheme].key ].admin;

    // calc check signature
    checkSignatureString = crypto.createHmac('sha1', secret )
                                 .update( req.authorization[ req.authorization.scheme ].date )
                                 .digest('hex');
    checkSignatureBase64 = new Buffer( checkSignatureString ).toString( 'base64' );

    // check signature
    if ( checkSignatureBase64 !== req.authorization[ req.authorization.scheme ].signature ) {
      return next( new NotAuthorizedError('Authorization signature is invalid.') );
    }

    return next();

  };

  return parseAuthorization;

};
<|endoftext|>


<commit_before>
'use strict';

(function () {
  var dispatcher = {
    _listeners: [],

    _parseListener: function (dependencies, listener) {
      if(typeof dependencies == 'function') {
        listener = dependencies;
      } else if(Array.isArray(dependencies)) {
        listener.dependencies = dependencies;
      } else if(typeof dependencies == 'string') {
        listener.dependencies = [dependencies];
      } else throw new Error('EventHandler is not a function.');

      return listener;
    },

    removeAllListeners: function (eventName) {
      if(eventName || eventName == 0) return this.off(eventName);
      this._listeners = [];
    },

    setMaxListeners: function () {},

    on: function (eventName, dependencies, listener) {
      listener = this._parseListener(dependencies, listener);
      listener.eventName = eventName;
      this._listeners.push(listener);
    },

    once: function (eventName, dependencies, listener) {
      listener = this._parseListener(dependencies, listener);
      listener.eventName = eventName;
      listener.once = true;
      this._listeners.push(listener);
    },

    off: function (eventName, listener) {
      if(typeof eventName === 'undefined') return;
      if(listener) {
        for(var i = 0; i < this._listeners.length; i++) {
          if(eventName == this._listeners[i].eventName && this._listeners[i] === listener)
            this._listeners.splice(i, 1);
        }
      }
      else {
        for(var i = 0; i < this._listeners.length; i++) {
          if(eventName == this._listeners[i].eventName)
            this._listeners.splice(i, 1);
        }
      }
    },

    listeners: function (eventName) {
      var eventParts = eventName.split('.')
        , eventName = eventParts[0]
        , namespace = eventParts[1] ? '.' + eventParts[1] : null
        , results = [];

      if(namespace)
        _match = this._matchWithNamespace;
      else
        _match = this._matchEvent;

      if(typeof this._listeners.filter == 'function')
        return this._listeners.filter(function (listener) {
          _match(eventName, listener.eventName, namespace);
        });
      else {
        for(var i = 0; i < this._listeners; i++) {
          if(_match(eventName, listener.eventName, namespace))
            results.push(listener);
        }
        return results;
      }
    },

    _matchWithNamespace: function (eventName, listenerEventName, namespace) {
      return eventName == listenerEventName || eventName.indexOf(listenerEventName + ':') == 0 || listenerEventName == namespace || listenerEventName == '*';
    },

    _matchEvent: function (eventName, listenerEventName) {
      return eventName == listenerEventName || eventName.indexOf(listenerEventName + ':') == 0 || listenerEventName.indexOf(eventName + '.') == 0 || listenerEventName == '*';
    },

    _matchArray: function (listenerArray, eventName) {
      var _match, listener;

      // check for namespace
      if(eventName.indexOf('.') != -1) {
        var eventParts = eventName.split('.')
          , eventName = eventParts[0]
          , namespace = eventParts[1] ? '.' + eventParts[1] : null
        _match = this._matchWithNamespace;
      } else {
        _match = this._matchEvent;
      }

      while(listener = listenerArray.pop()) {
        if(_match(eventName, listener.eventName, namespace) || listener.eventName.substring(listener.eventName.indexOf('.')) == namespace && listener.eventName != '*')
          return true;
      }

      return false;
    },

    _deferredLoop: function (deferredListeners, waitingAsync) {
      var deferredLength, listener, promise, dependent
        , _this = this
        , deadlockCounter = 0;

      deferredLength = deadlockCounter = deferredListeners.length;;

      while(listener = deferredListeners.pop()) {
        if(deadlockCounter == 0) {
          if(!waitingAsync) {
              throw new Error('Deadlock!');
          } else {
            return;
          }
        }
        dependent = false;

        if(!listener.dependencies) {
          deferredListeners.unshift(listener);
          deadlockCounter--;
          continue;
        }

        for(var j = 0; j < listener.dependencies.length; j++) {
          dependent = _this._matchArray(deferredListeners.slice(), listener.dependencies[j]) ? true : dependent;
        }

        if(!dependent) {
          // run listener
          if(arguments.length > 1)
            promise = listener.apply(null, arguments);
          else
            promise = listener(eventName + '.' + namespace);

          if(promise && promise.then) {
            waitingAsync++;
            deferredListeners.unshift(listener);
            // run promise
            promise.then(function () {
              waitingAsync--;
              _this._deferredLoop(deferredListeners, waitingAsync);
            });
          }
        } else {
          deferredListeners.unshift(listener);
        }

        if(deferredListeners.length == deferredLength)
          deadlockCounter--;
        else
          deferredLength = deadlockCounter = deferredListeners.length;
      }
    },

    emit: function (eventName) {
      if(!eventName) {
        throw new Error('Nothing to emit.');
      }

      // common variables
      var deferredListeners = []
        , listenerArray = this._listeners.slice()
        , waitingAsync = 0
        , _this = this
        , listener, _match, promise;

      // check for namespace
      if(eventName.indexOf('.') != -1) {
        var eventParts = eventName.split('.')
          , eventName = eventParts[0]
          , namespace = eventParts[1] ? '.' + eventParts[1] : null;
        _match = _this._matchWithNamespace;
      } else {
        _match = _this._matchEvent;
      }

      if(!eventName) {
        throw new Error('Nothing to emit.');
      }

      while(listener = listenerArray.pop()) {
        // check if current listener matches
        if(_match(eventName, listener.eventName, namespace)) {
          // dependencies
          if(listener.dependencies) {
            deferredListeners.push(listener);
            continue;
          }

          // run listener
          if(arguments.length > 1)
            promise = listener.apply(null, arguments);
          else
            promise = listener(eventName + '.' + namespace);

          if(promise && promise.then) {
            waitingAsync++;
            deferredListeners.push(listener);
            // run promise
            promise.then(function () {
              waitingAsync--;
              _this._deferredLoop(deferredListeners, waitingAsync);
            });
          }
        }

        // remove one time listeners
        if(listener.once)
          _this._listeners.splice(listenerArray.length, 1);
      }

      // check if there is callback dependency
      if(deferredListeners.length > 0)
        _this._deferredLoop(deferredListeners, waitingAsync);
    }
  }

  dispatcher.removeListener = dispatcher.off;
  dispatcher.addListener = dispatcher.on;

  if (typeof define === 'function' && define.amd) {
     // AMD. Register as an anonymous module.
    define(function() {
      return dispatcher;
    });
  } else if (typeof exports === 'object') {
    // CommonJS
    module.exports = dispatcher;
  }
  else {
    // Browser global.
    window.dispatcher = dispatcher;
  }
})();
<commit_msg>listeners() will return all listeners when an eventName is not specified.<commit_after>
'use strict';

(function () {
  var dispatcher = {
    _listeners: [],

    _parseListener: function (dependencies, listener) {
      if(typeof dependencies == 'function') {
        listener = dependencies;
      } else if(Array.isArray(dependencies)) {
        listener.dependencies = dependencies;
      } else if(typeof dependencies == 'string') {
        listener.dependencies = [dependencies];
      } else throw new Error('EventHandler is not a function.');

      return listener;
    },

    removeAllListeners: function (eventName) {
      if(eventName || eventName == 0) return this.off(eventName);
      this._listeners = [];
    },

    setMaxListeners: function () {},

    on: function (eventName, dependencies, listener) {
      listener = this._parseListener(dependencies, listener);
      listener.eventName = eventName;
      this._listeners.push(listener);
    },

    once: function (eventName, dependencies, listener) {
      listener = this._parseListener(dependencies, listener);
      listener.eventName = eventName;
      listener.once = true;
      this._listeners.push(listener);
    },

    off: function (eventName, listener) {
      if(typeof eventName === 'undefined') return;
      if(listener) {
        for(var i = 0; i < this._listeners.length; i++) {
          if(eventName == this._listeners[i].eventName && this._listeners[i] === listener)
            this._listeners.splice(i, 1);
        }
      }
      else {
        for(var i = 0; i < this._listeners.length; i++) {
          if(eventName == this._listeners[i].eventName)
            this._listeners.splice(i, 1);
        }
      }
    },

    listeners: function (eventName) {
      if(!eventName)
        return this._listeners;

      var eventParts = eventName.split('.')
        , eventName = eventParts[0]
        , namespace = eventParts[1] ? '.' + eventParts[1] : null
        , results = [];

      if(namespace)
        _match = this._matchWithNamespace;
      else
        _match = this._matchEvent;

      if(typeof this._listeners.filter == 'function')
        return this._listeners.filter(function (listener) {
          _match(eventName, listener.eventName, namespace);
        });
      else {
        for(var i = 0; i < this._listeners; i++) {
          if(_match(eventName, listener.eventName, namespace))
            results.push(listener);
        }
        return results;
      }
    },

    _matchWithNamespace: function (eventName, listenerEventName, namespace) {
      return eventName == listenerEventName || eventName.indexOf(listenerEventName + ':') == 0 || listenerEventName == namespace || listenerEventName == '*';
    },

    _matchEvent: function (eventName, listenerEventName) {
      return eventName == listenerEventName || eventName.indexOf(listenerEventName + ':') == 0 || listenerEventName.indexOf(eventName + '.') == 0 || listenerEventName == '*';
    },

    _matchArray: function (listenerArray, eventName) {
      var _match, listener;

      // check for namespace
      if(eventName.indexOf('.') != -1) {
        var eventParts = eventName.split('.')
          , eventName = eventParts[0]
          , namespace = eventParts[1] ? '.' + eventParts[1] : null
        _match = this._matchWithNamespace;
      } else {
        _match = this._matchEvent;
      }

      while(listener = listenerArray.pop()) {
        if(_match(eventName, listener.eventName, namespace) || listener.eventName.substring(listener.eventName.indexOf('.')) == namespace && listener.eventName != '*')
          return true;
      }

      return false;
    },

    _deferredLoop: function (deferredListeners, waitingAsync) {
      var deferredLength, listener, promise, dependent
        , _this = this
        , deadlockCounter = 0;

      deferredLength = deadlockCounter = deferredListeners.length;;

      while(listener = deferredListeners.pop()) {
        if(deadlockCounter == 0) {
          if(!waitingAsync) {
              throw new Error('Deadlock!');
          } else {
            return;
          }
        }
        dependent = false;

        if(!listener.dependencies) {
          deferredListeners.unshift(listener);
          deadlockCounter--;
          continue;
        }

        for(var j = 0; j < listener.dependencies.length; j++) {
          dependent = _this._matchArray(deferredListeners.slice(), listener.dependencies[j]) ? true : dependent;
        }

        if(!dependent) {
          // run listener
          if(arguments.length > 1)
            promise = listener.apply(null, arguments);
          else
            promise = listener(eventName + '.' + namespace);

          if(promise && promise.then) {
            waitingAsync++;
            deferredListeners.unshift(listener);
            // run promise
            promise.then(function () {
              waitingAsync--;
              _this._deferredLoop(deferredListeners, waitingAsync);
            });
          }
        } else {
          deferredListeners.unshift(listener);
        }

        if(deferredListeners.length == deferredLength)
          deadlockCounter--;
        else
          deferredLength = deadlockCounter = deferredListeners.length;
      }
    },

    emit: function (eventName) {
      if(!eventName) {
        throw new Error('Nothing to emit.');
      }

      // common variables
      var deferredListeners = []
        , listenerArray = this._listeners.slice()
        , waitingAsync = 0
        , _this = this
        , listener, _match, promise;

      // check for namespace
      if(eventName.indexOf('.') != -1) {
        var eventParts = eventName.split('.')
          , eventName = eventParts[0]
          , namespace = eventParts[1] ? '.' + eventParts[1] : null;
        _match = _this._matchWithNamespace;
      } else {
        _match = _this._matchEvent;
      }

      if(!eventName) {
        throw new Error('Nothing to emit.');
      }

      while(listener = listenerArray.pop()) {
        // check if current listener matches
        if(_match(eventName, listener.eventName, namespace)) {
          // dependencies
          if(listener.dependencies) {
            deferredListeners.push(listener);
            continue;
          }

          // run listener
          if(arguments.length > 1)
            promise = listener.apply(null, arguments);
          else
            promise = listener(eventName + '.' + namespace);

          if(promise && promise.then) {
            waitingAsync++;
            deferredListeners.push(listener);
            // run promise
            promise.then(function () {
              waitingAsync--;
              _this._deferredLoop(deferredListeners, waitingAsync);
            });
          }
        }

        // remove one time listeners
        if(listener.once)
          _this._listeners.splice(listenerArray.length, 1);
      }

      // check if there is callback dependency
      if(deferredListeners.length > 0)
        _this._deferredLoop(deferredListeners, waitingAsync);
    }
  }

  dispatcher.removeListener = dispatcher.off;
  dispatcher.addListener = dispatcher.on;

  if (typeof define === 'function' && define.amd) {
     // AMD. Register as an anonymous module.
    define(function() {
      return dispatcher;
    });
  } else if (typeof exports === 'object') {
    // CommonJS
    module.exports = dispatcher;
  }
  else {
    // Browser global.
    window.dispatcher = dispatcher;
  }
})();
<|endoftext|>


<commit_before>/**

 Copyright 2015 Covistra Technologies Inc.

 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.
 */
var Boom = require('boom'),
    Calibrate = require('calibrate');

module.exports = function(server) {
    var Tokens = server.plugins['covistra-security'].Tokens.model;
    var Applications = server.plugins['covistra-security'].Applications.model;

    function handler(req, reply) {
        req.log.debug("Trying to authenticate user %s with application %s", req.auth.credentials.username, req.headers["x-app-key"]);

        // Retrieve the application for which the token is created
        Applications.getByKey(req.headers["x-app-key"]).then(function(app) {
            if(app) {
                req.log.debug("Found app", app);

                var tokenOptions = config.get('plugins:security:token_options', { roles: ['covistra-security'], expiresInMinutes: 30 * 24 * 60, audience: app.key, issuer: 'cmbf' });
                tokenOptions.subject = req.auth.credentials.username;
                return Tokens.allocateToken(req.auth.credentials, app, tokenOptions ).then(function(tok) {
                    req.log.debug("Token was successfully allocated for user", req.auth.credentials);
                    return {token: tok.token};
                });

            }
            else {
                throw Boom.create(401, "Unknown app", { key: req.headers['x-app-key']});
            }
        }).then(Calibrate.response).catch(Calibrate.error).then(reply);

    }

    return {
        method: 'GET',
        path: '/auth/token',
        handler: handler,
        config: {
            tags: ['api'],
            auth: 'simple'
        }
    };

};
<commit_msg>Add missing config ref<commit_after>/**

 Copyright 2015 Covistra Technologies Inc.

 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.
 */
var Boom = require('boom'),
    Calibrate = require('calibrate');

module.exports = function(server, log, config) {
    var Tokens = server.plugins['covistra-security'].Tokens.model;
    var Applications = server.plugins['covistra-security'].Applications.model;

    function handler(req, reply) {
        req.log.debug("Trying to authenticate user %s with application %s", req.auth.credentials.username, req.headers["x-app-key"]);

        // Retrieve the application for which the token is created
        Applications.getByKey(req.headers["x-app-key"]).then(function(app) {
            if(app) {
                req.log.debug("Found app", app);

                var tokenOptions = config.get('plugins:security:token_options', { roles: ['covistra-security'], expiresInMinutes: 30 * 24 * 60, audience: app.key, issuer: 'cmbf' });
                tokenOptions.subject = req.auth.credentials.username;
                return Tokens.allocateToken(req.auth.credentials, app, tokenOptions ).then(function(tok) {
                    req.log.debug("Token was successfully allocated for user", req.auth.credentials);
                    return {token: tok.token};
                });

            }
            else {
                throw Boom.create(401, "Unknown app", { key: req.headers['x-app-key']});
            }
        }).then(Calibrate.response).catch(Calibrate.error).then(reply);

    }

    return {
        method: 'GET',
        path: '/auth/token',
        handler: handler,
        config: {
            tags: ['api'],
            auth: 'simple'
        }
    };

};
<|endoftext|>