<commit_before>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminEditPage");}, gvm);
    gvm.pageHeaderEditUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserEditTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.firstname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.email = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Email");}, gvm);
    gvm.status = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessProjectStatus");}, gvm);

    gvm.adminEditUserPermissions = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminEditUserPermissions");}, gvm);
    gvm.adminRights = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminRights");}, gvm);

    gvm.adminGuest = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminGuest");}, gvm);
    gvm.adminStudent = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminStudent");}, gvm);
    gvm.adminUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminUser");}, gvm);
    gvm.adminSuperuser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminSuperuser");}, gvm);

    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);

    gvm.edituserid = $("#usereditHeader").data('value');

    gvm.loggedinuser = ko.observable();

    getLoggedInUser();

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);

    gvm.permissionRole = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionRole");}, gvm);
    gvm.permissionDescription = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionDescription");}, gvm);

    gvm.currentUserRole = ko.observable();
    gvm.availablePermissions = ko.observableArray(['GUEST', 'STUDENT', 'USER', 'SUPERUSER']);

    gvm.rights = ko.observableArray([]);
    gvm.allRights = ko.observableArray([]);
    gvm.userRights = ko.observableArray([]);
    gvm.user = ko.observableArray([]);

    gvm.updateUser = function(user)
    {
        gvm.user.push(user);
    },

    gvm.updatePermissions = function(permission)
    {
        gvm.rights.push(permission);
    },

    gvm.updateAllPermissions = function(permission)
    {
        gvm.allRights.push(permission);
    },

    gvm.removeUser = function(user) {
        gvm.user.remove(user);
        removeUser(user);
    },

    gvm.clearStructure = function() {
        gvm.rights.destroyAll();
        gvm.user.destroyAll();
    }
}

function initPage() {
    getAllUserDataById(viewModel.edituserid);

    $('#userEditForm').on('submit', function(e)
    {
        e.preventDefault();

        if(viewModel.loggedinuser != viewModel.edituserid)
        {
            saveChanges();
            saveUserPermissions();
        } else {
            saveChanges();
        }
    });

    $(".cancelPageBtn").click(function()
    {
        window.location.href = "/admin/home";
    });
}

function getLoggedInUser(){
    $.getJSON("/api/loggedinuser", function(data){
        viewModel.loggedinuser = data;
    });
}

function saveChanges(){
    saveUserEdits(viewModel.edituserid);
}

function saveUserEdits(id){
    $.ajax({
        type: "POST",
        url: "/api/saveedit/" + id,
        data: $('#userEditForm').serialize(),
        success: function() {
        },
        error: function() {
            console.log("Error saving user changes");
        }
    });
}

function saveUserPermissions(){
    alert(viewModel.permissions);
    var role = viewModel.permissions;
    var permissions = "GUEST ";

    if(role == 'STUDENT' || role == 'USER' || role == 'SUPERUSER'){
        permissions += "STUDENT ";
        if(role == 'USER' || role == 'SUPERUSER'){
            permissions += "USER ";
            if(role == 'SUPERUSER'){
                permissions += "SUPERUSER";
            }
        }
    }

    //SAVE NEW PERMISSIONS
    $.ajax({
        type: "POST",
        url: "/api/addrole/" + viewModel.edituserid,
        data: { 'permissions': permissions },
        success: function() {
            alert('Changes saved correctly');
            window.location.href = "/admin/home";
        },
        error: function() {
            alert('Error saving user. Please contact the Administrator');
        }
    });
}

function getAllUserDataById(edituserid){
    $.getJSON("/api/edituser/" + edituserid, function(data)
    {
        var addedUsername = "";
        $.each(data, function(i, item){
            var current = item.username;

            $.each(data, function(i, item)
            {
                if(item.username == current && addedUsername != current){
                    viewModel.updatePermissions(item.role)
                }
            });

            if (addedUsername != current) {
                addedUsername = current;
                console.log(viewModel.rights());
                viewModel.updateUser(new User(item.userid, item.username, item.firstname, item.lastname, item.status, viewModel.rights()));
            }
        });
    });
}

function contains(a, obj) {
    var i = a.length;
    while (i--) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

function User(id, username, firstname, lastname, status, permissions) {
    console.log(permissions);
    var hoogste = "GUEST";

    if (contains(permissions, "SUPERUSER")){
        hoogste = "SUPERUSER";
    } else if (contains(permissions, "USER")){
        hoogste = "USER";
    } else if (contains(permissions, "STUDENT")){
        hoogste = "STUDENT";
    } else if (contains(permissions, "GUEST")){
        hoogste = "GUEST";
    }
    console.log(hoogste);
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),
        permissions: ko.observable(hoogste),
        userStatuses: ko.observableArray(['ACTIVE', 'DISABLED']),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            if (this.status() == "ACTIVE"){
                this.status("DISABLED");
            } else if (this.status() == "DISABLED") {
                this.status("ACTIVE");
            } else if (this.status() == "WAIT_ACTIVATION") {
                this.status("ACTIVE");
            }
            updateUserStatus(this);
        }
    };
}<commit_msg>small fixes<commit_after>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminEditPage");}, gvm);
    gvm.pageHeaderEditUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserEditTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.firstname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.email = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Email");}, gvm);
    gvm.status = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessProjectStatus");}, gvm);

    gvm.adminEditUserPermissions = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminEditUserPermissions");}, gvm);
    gvm.adminRights = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminRights");}, gvm);

    gvm.adminGuest = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminGuest");}, gvm);
    gvm.adminStudent = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminStudent");}, gvm);
    gvm.adminUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminUser");}, gvm);
    gvm.adminSuperuser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AdminSuperuser");}, gvm);

    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);

    gvm.edituserid = $("#usereditHeader").data('value');

    gvm.loggedinuser = ko.observable();

    getLoggedInUser();

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);

    gvm.permissionRole = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionRole");}, gvm);
    gvm.permissionDescription = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionDescription");}, gvm);

    gvm.currentUserRole = ko.observable();
    gvm.availablePermissions = ko.observableArray(['GUEST', 'STUDENT', 'USER', 'SUPERUSER']);

    gvm.rights = ko.observableArray([]);
    gvm.allRights = ko.observableArray([]);
    gvm.userRights = ko.observableArray([]);
    gvm.user = ko.observableArray([]);

    gvm.updateUser = function(user)
    {
        gvm.user.push(user);
    },

    gvm.updatePermissions = function(permission)
    {
        gvm.rights.push(permission);
    },

    gvm.updateAllPermissions = function(permission)
    {
        gvm.allRights.push(permission);
    },

    gvm.removeUser = function(user) {
        gvm.user.remove(user);
        removeUser(user);
    },

    gvm.clearStructure = function() {
        gvm.rights.destroyAll();
        gvm.user.destroyAll();
    }
}

function initPage() {
    getAllUserDataById(viewModel.edituserid);

    $('#userEditForm').on('submit', function(e)
    {
        e.preventDefault();

        if(viewModel.loggedinuser != viewModel.edituserid)
        {
            saveChanges();
            saveUserPermissions();
        } else {
            saveChanges();
        }
    });

    $(".cancelPageBtn").click(function()
    {
        window.location.href = "/admin/home";
    });
}

function getLoggedInUser(){
    $.getJSON("/api/loggedinuser", function(data){
        viewModel.loggedinuser = data;
    });
}

function saveChanges(){
    saveUserEdits(viewModel.edituserid);
}

function saveUserEdits(id){
    $.ajax({
        type: "POST",
        url: "/api/saveedit/" + id,
        data: $('#userEditForm').serialize(),
        success: function() {
        },
        error: function() {
            console.log("Error saving user changes");
        }
    });
}

function saveUserPermissions(){
    console.log(viewModel.user);
    var role = viewModel.user.permissions;
    var permissions = "GUEST ";

    if(role == 'STUDENT' || role == 'USER' || role == 'SUPERUSER'){
        permissions += "STUDENT ";
        if(role == 'USER' || role == 'SUPERUSER'){
            permissions += "USER ";
            if(role == 'SUPERUSER'){
                permissions += "SUPERUSER";
            }
        }
    }

    //SAVE NEW PERMISSIONS
    $.ajax({
        type: "POST",
        url: "/api/addrole/" + viewModel.edituserid,
        data: { 'permissions': permissions },
        success: function() {
            alert('Changes saved correctly');
            window.location.href = "/admin/home";
        },
        error: function() {
            alert('Error saving user. Please contact the Administrator');
        }
    });
}

function getAllUserDataById(edituserid){
    $.getJSON("/api/edituser/" + edituserid, function(data)
    {
        var addedUsername = "";
        $.each(data, function(i, item){
            var current = item.username;

            $.each(data, function(i, item)
            {
                if(item.username == current && addedUsername != current){
                    viewModel.updatePermissions(item.role)
                }
            });

            if (addedUsername != current) {
                addedUsername = current;
                console.log(viewModel.rights());
                viewModel.updateUser(new User(item.userid, item.username, item.firstname, item.lastname, item.status, viewModel.rights()));
            }
        });
    });
}

function contains(a, obj) {
    var i = a.length;
    while (i--) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

function User(id, username, firstname, lastname, status, permissions) {
    console.log(permissions);
    var hoogste = "GUEST";

    if (contains(permissions, "SUPERUSER")){
        hoogste = "SUPERUSER";
    } else if (contains(permissions, "USER")){
        hoogste = "USER";
    } else if (contains(permissions, "STUDENT")){
        hoogste = "STUDENT";
    } else if (contains(permissions, "GUEST")){
        hoogste = "GUEST";
    }
    console.log(hoogste);
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),
        permissions: ko.observable(hoogste),
        userStatuses: ko.observableArray(['ACTIVE', 'DISABLED']),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            if (this.status() == "ACTIVE"){
                this.status("DISABLED");
            } else if (this.status() == "DISABLED") {
                this.status("ACTIVE");
            } else if (this.status() == "WAIT_ACTIVATION") {
                this.status("ACTIVE");
            }
            updateUserStatus(this);
        }
    };
}<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminEditPage");}, gvm);
    gvm.pageHeaderEditUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserEditTitle");}, gvm);

    gvm.edituserid = $("#usereditHeader").data('value');

    gvm.loggedinuser = ko.observable();

    getLoggedInUser();

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);

    gvm.permissionRole = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionRole");}, gvm);
    gvm.permissionDescription = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionDescription");}, gvm);

    gvm.currentUserRole = ko.observable();
    gvm.oldUserRole = ko.observable("GUEST");
    gvm.availablePermissions = ko.observableArray(['GUEST', 'STUDENT', 'USER', 'SUPERUSER']);

    gvm.rights = ko.observableArray([]);
    gvm.allRights = ko.observableArray([]);
    gvm.userRights = ko.observableArray([]);
    gvm.user = ko.observableArray([]);

    gvm.oldUserRoleUpdate = function(role){
        gvm.oldUserRole = role;
    },

    gvm.updateUser = function(user)
    {
        gvm.user.push(user);
    },

    gvm.updatePermissions = function(permission)
    {
        gvm.rights.push(permission);
    },

    gvm.updateAllPermissions = function(permission)
    {
        gvm.allRights.push(permission);
    },

    gvm.removeUser = function(user) {
        gvm.user.remove(user);
        removeUser(user);
    },

    gvm.clearStructure = function() {
        gvm.rights.destroyAll();
        gvm.user.destroyAll();
    }
}

function initPage() {
    getAllUserDataById(viewModel.edituserid);
    getUserPermission();
    $('#userEditForm').on('submit', function(e)
    {
        e.preventDefault();

        if(viewModel.loggedinuser != viewModel.edituserid)
        {
            saveChanges();
            saveUserPermissions();
        } else {
            saveChanges();
        }
    });

}

function getUserPermission(){
    $.ajax({
        type: "POST",
        url: "/api/getUserRolesById/" + viewModel.edituserid,
        success: function(data) {
            console.log(data);

            if (data.length > 0) {
                var role = "GUEST";
                for (i = 0; i < data.length; i++) {
                    if (data[i] == "GUEST" && data[i] != null){
                        console.log("guest");
                        role = "GUEST";
                    }
                    if (data[i] == "STUDENT" && data[i] != null){
                        console.log("STUDENT");
                        role = "STUDENT";
                    }
                    if (data[i] == "USER" && data[i] != null){
                        console.log("USER");
                        role = "USER";
                    }
                    if (data[i] == "SUPERUSER" && data[i] != null){
                        console.log("SUPERUSER");
                        role = "SUPERUSER";
                    }
                }
                console.log("role: " + role);
                viewModel.oldUserRoleUpdate(role);
                return role;
            } else {
                console.log("guest else");
                return "GUEST";
            }
        },
        error: function() {
            alert("Error while getting user info, please contact your administrator");
        }
    });
}

function getLoggedInUser(){
    $.getJSON("/api/loggedinuser", function(data){
        viewModel.loggedinuser = data;
    });
}

function saveChanges(){
    saveUserEdits(viewModel.edituserid);
}

function saveUserEdits(id){
    $.ajax({
        type: "POST",
        url: "/api/saveedit/" + id,
        data: $('#userEditForm').serialize(),
        success: function() {
        },
        error: function() {
            console.log("Error saving user changes");
        }
    });
}

function saveUserPermissions(){
    var role = viewModel.currentUserRole();
    var permissions = "GUEST ";

    if(role == 'STUDENT' || role == 'USER' || role == 'SUPERUSER'){
        permissions += "STUDENT ";
        if(role == 'USER' || role == 'SUPERUSER'){
            permissions += "USER ";
            if(role == 'SUPERUSER'){
                permissions += "SUPERUSER";
            }
        }
    }

    //SAVE NEW PERMISSIONS
    $.ajax({
        type: "POST",
        url: "/api/addrole/" + viewModel.edituserid,
        data: { 'permissions': permissions },
        success: function() {
            alert('Changes saved correctly');
        },
        error: function() {
            alert('Error saving user. Please contact the Administrator');
        }
    });
}

function getAllUserDataById(edituserid){
    $.getJSON("/api/edituser/" + edituserid, function(data)
    {
        var addedUsername = "";
        $.each(data, function(i, item){
            var current = item.username;

            $.each(data, function(i, item)
            {
                if(item.username == current && addedUsername != current){
                    viewModel.updatePermissions(item.role)
                }
            });

            if (addedUsername != current) {
                addedUsername = current;
                viewModel.updateUser(new User(item.userid, item.username, item.firstname, item.lastname, item.status, viewModel.rights()));
            }
        });
    });
}

function User(id, username, firstname, lastname, status, permissions) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),
        permissions: ko.observableArray(permissions),
        userStatuses: ko.observableArray(['ACTIVE', 'DISABLED']),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            if (this.status() == "ACTIVE"){
                this.status("DISABLED");
            } else if (this.status() == "DISABLED") {
                this.status("ACTIVE");
            } else if (this.status() == "WAIT_ACTIVATION") {
                this.status("ACTIVE");
            }
            updateUserStatus(this);
        }
    };
}<commit_msg>Load current permission user edit<commit_after>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminEditPage");}, gvm);
    gvm.pageHeaderEditUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserEditTitle");}, gvm);

    gvm.edituserid = $("#usereditHeader").data('value');

    gvm.loggedinuser = ko.observable();

    getLoggedInUser();

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);

    gvm.permissionRole = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionRole");}, gvm);
    gvm.permissionDescription = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionDescription");}, gvm);

    gvm.currentUserRole = ko.observable();
    gvm.oldUserRole = ko.observable("GUEST");
    gvm.availablePermissions = ko.observableArray(['GUEST', 'STUDENT', 'USER', 'SUPERUSER']);

    gvm.rights = ko.observableArray([]);
    gvm.allRights = ko.observableArray([]);
    gvm.userRights = ko.observableArray([]);
    gvm.user = ko.observableArray([]);

    gvm.oldUserRoleUpdate = function(role){
        gvm.oldUserRole = role;
    },

    gvm.updateUser = function(user)
    {
        gvm.user.push(user);
    },

    gvm.updatePermissions = function(permission)
    {
        gvm.rights.push(permission);
    },

    gvm.updateAllPermissions = function(permission)
    {
        gvm.allRights.push(permission);
    },

    gvm.removeUser = function(user) {
        gvm.user.remove(user);
        removeUser(user);
    },

    gvm.clearStructure = function() {
        gvm.rights.destroyAll();
        gvm.user.destroyAll();
    }
}

function initPage() {
    getAllUserDataById(viewModel.edituserid);
    getUserPermission();
    $('#userEditForm').on('submit', function(e)
    {
        e.preventDefault();

        if(viewModel.loggedinuser != viewModel.edituserid)
        {
            saveChanges();
            saveUserPermissions();
        } else {
            saveChanges();
        }
    });

}

function getUserPermission(){
    $.ajax({
        type: "POST",
        url: "/api/getUserRolesById/" + viewModel.edituserid,
        success: function(data) {
            console.log(data);

            if (data.length > 0) {
                var role = "GUEST";
                for (i = 0; i < 1; i++) {
                    if (data[i] == "GUEST" && data[i] != null){
                        console.log("guest");
                        role = "GUEST";
                        i++;
                        if (data[i] == "STUDENT" && data[i] != null){
                            console.log("STUDENT");
                            role = "STUDENT";
                            i++;
                            if (data[i] == "USER" && data[i] != null){
                                console.log("USER");
                                role = "USER";
                                i++;
                                if (data[i] == "SUPERUSER" && data[i] != null){
                                    console.log("SUPERUSER");
                                    role = "SUPERUSER";
                                }
                            }
                        }
                    }

                }
                console.log("role: " + role);
                viewModel.oldUserRoleUpdate(role);
                return role;
            } else {
                console.log("guest else");
                return "GUEST";
            }
        },
        error: function() {
            alert("Error while getting user info, please contact your administrator");
        }
    });
}

function getLoggedInUser(){
    $.getJSON("/api/loggedinuser", function(data){
        viewModel.loggedinuser = data;
    });
}

function saveChanges(){
    saveUserEdits(viewModel.edituserid);
}

function saveUserEdits(id){
    $.ajax({
        type: "POST",
        url: "/api/saveedit/" + id,
        data: $('#userEditForm').serialize(),
        success: function() {
        },
        error: function() {
            console.log("Error saving user changes");
        }
    });
}

function saveUserPermissions(){
    var role = viewModel.currentUserRole();
    var permissions = "GUEST ";

    if(role == 'STUDENT' || role == 'USER' || role == 'SUPERUSER'){
        permissions += "STUDENT ";
        if(role == 'USER' || role == 'SUPERUSER'){
            permissions += "USER ";
            if(role == 'SUPERUSER'){
                permissions += "SUPERUSER";
            }
        }
    }

    //SAVE NEW PERMISSIONS
    $.ajax({
        type: "POST",
        url: "/api/addrole/" + viewModel.edituserid,
        data: { 'permissions': permissions },
        success: function() {
            alert('Changes saved correctly');
        },
        error: function() {
            alert('Error saving user. Please contact the Administrator');
        }
    });
}

function getAllUserDataById(edituserid){
    $.getJSON("/api/edituser/" + edituserid, function(data)
    {
        var addedUsername = "";
        $.each(data, function(i, item){
            var current = item.username;

            $.each(data, function(i, item)
            {
                if(item.username == current && addedUsername != current){
                    viewModel.updatePermissions(item.role)
                }
            });

            if (addedUsername != current) {
                addedUsername = current;
                viewModel.updateUser(new User(item.userid, item.username, item.firstname, item.lastname, item.status, viewModel.rights()));
            }
        });
    });
}

function User(id, username, firstname, lastname, status, permissions) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),
        permissions: ko.observableArray(permissions),
        userStatuses: ko.observableArray(['ACTIVE', 'DISABLED']),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            if (this.status() == "ACTIVE"){
                this.status("DISABLED");
            } else if (this.status() == "DISABLED") {
                this.status("ACTIVE");
            } else if (this.status() == "WAIT_ACTIVATION") {
                this.status("ACTIVE");
            }
            updateUserStatus(this);
        }
    };
}<|endoftext|>


<commit_before>var $ = require('jquery'),
    Backbone = require('backbone'),
    DetailView = require('views/detail_view'),
    ListView = require('views/list_view'),
    Query = require('lib/query'),
    facilities = require('collections/facilities').instance;

var Router = Backbone.Router.extend({
  routes: {
    '': 'list',
    'detail/:id': 'detail'
  },

  list: function() {

    var json = $('#results').data('results');
    this.facilities.reset(json);

    console.log('entering list route:', this.facilities);

    var listView = new ListView({ collection: this.facilities });
    listView.render();
  },

  detail: function(id) {

    //var facility = this.facilities.get(id);
    //var facility = this.facilities.models[0].toJSON();
    //var facility = $('#results').data('results').models[0].toJSON()

//we need to write an event func in listview that passes the object on click. this var setting here is TEMPORARY:
    var facility = JSON.parse('{"address":"225 30th Street","description":"Women thing","gender":"F","name":"30TH STREET SENIOR CENTER","notes":"foobar","phone":"(415) 550-2210","age":["S"],"hours":{"Sun": "11-12"},"location":{"__type":"GeoPoint","latitude":37.7421083,"longitude":-122.4251428},"services":["technology"],"objectId":"20ivH0qnQE","createdAt":"2013-04-09T07:01:45.280Z","updatedAt":"2013-04-09T14:55:19.177Z"}');
    //Fetch Facility from backend if not in collection

    console.log('entering details route:', facility );

    var detailView = new DetailView({ model: facility });
    detailView.render();
  }
});

var instance = new Router();
module.exports = { instance: instance };
<commit_msg>listenTo and rerender on facilities changes<commit_after>var $ = require('jquery'),
    Backbone = require('backbone'),
    DetailView = require('views/detail_view'),
    ListView = require('views/list_view'),
    Query = require('lib/query'),
    facilities = require('collections/facilities').instance;

var Router = Backbone.Router.extend({
  routes: {
    '': 'list',
    'detail/:id': 'detail'
  },

  list: function() {
    var listView = new ListView({ collection: facilities });

    listView.render();

    // render when facilities is reset
    listView.listenTo(facilities, 'reset', function() {
      listView.render();
    });
  },

  detail: function(id) {

    //var facility = this.facilities.get(id);
    //var facility = this.facilities.models[0].toJSON();
    //var facility = $('#results').data('results').models[0].toJSON()

//we need to write an event func in listview that passes the object on click. this var setting here is TEMPORARY:
    var facility = JSON.parse('{"address":"225 30th Street","description":"Women thing","gender":"F","name":"30TH STREET SENIOR CENTER","notes":"foobar","phone":"(415) 550-2210","age":["S"],"hours":{"Sun": "11-12"},"location":{"__type":"GeoPoint","latitude":37.7421083,"longitude":-122.4251428},"services":["technology"],"objectId":"20ivH0qnQE","createdAt":"2013-04-09T07:01:45.280Z","updatedAt":"2013-04-09T14:55:19.177Z"}');
    //Fetch Facility from backend if not in collection

    console.log('entering details route:', facility );

    var detailView = new DetailView({ model: facility });
    detailView.render();
  }
});

var instance = new Router();
module.exports = { instance: instance };
<|endoftext|>


<commit_before>var React = require('react/addons');
var Material = require('material-ui');
var Paper = Material.Paper;
var TextField = Material.TextField;
var RaisedButton = Material.RaisedButton;
var Checkbox = Material.Checkbox;
var Snackbar = Material.Snackbar;

var Contact = React.createClass({

  getInitialState() {
    return{
      validName: true,
      validEmail: true,
      validMessage: true,
      userReadTheGuide: false
    }
  },

  handleClick() {
    //Check inputs are valid
    var validName = true, validEmail = true, validMessage = true;
    if(this.refs.contactName.getValue().length == 0){
      validName = false;
    }

    if(!this.validateEmail(this.refs.contactEmail.getValue())){
      validEmail = false;
    }

    if(this.refs.contactMessage.getValue().length < 10){
      validMessage = false;
    }

    if(validName && validEmail && validMessage) {
      this.refs.SnackBar.show();
      this.refs.contactName.clearValue();
      this.refs.contactEmail.clearValue();
      this.refs.contactMessage.clearValue();
      this.refs.checkReadTheGuide.setChecked(false);

      this.setState({validName: validName, validEmail: validEmail, validMessage: validMessage,
        userReadTheGuide: false});

    }else{
      this.setState({validName: validName, validEmail: validEmail, validMessage: validMessage});
    }
  },

  handleChange(e){
    var value = e.target.value;
    switch(e.target.name){
      case "contactName":
        //Check name has at least 1 character
        if(!this.state.validName && value.length > 0){
          this.setState({validName: true});
        }
        break;
      case "contactEmail":
        //Check email is correct;
        if(!this.state.validEmail && this.validateEmail(value)){
          this.setState({validEmail: true});
        }
        break;
      case "contactMessage":
        //Check message has at least 10 characters
        if(!this.state.validMessage && value.length >= 10){
          this.setState({validMessage: true});
        }
        break;
      default:
        break;
    }
  },

  //From http://stackoverflow.com/a/46181/2277631 (is more than enough)
  validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
  },

  render() {
    return (

          <Paper zDepth={1} rounded={true} innerClassName={'contact-body'}>

Contact

To contact me, you can use our email
             or Twitter. It is also possible to
              use the form below.

            <TextField
              ref="contactName"
              name="contactName"
              className="field"
              onChange={this.handleChange}
              errorText={this.state.validName ? '' : 'This field is required.'}
              floatingLabelText="Your name"/>
            <TextField
              ref="contactEmail"
              name="contactEmail"
              className="field email"
              onChange={this.handleChange}
              hintText="valid@email.com"
              type="email"
              errorText={this.state.validEmail ? '' : 'Your email appears to be invalid.'}
              floatingLabelText="Your email"/>
            <TextField
              ref="contactMessage"
              name="contactMessage"
              className="message"
              onChange={this.handleChange}
              floatingLabelText="Your message"
              errorText={this.state.validMessage ? '' : 'Your message appears to be too short.'}
              multiLine={true}/>

            <Checkbox
              ref="checkReadTheGuide"
              onClick={(e) => {this.setState({userReadTheGuide: e.target.checked})}}
              className="checkbox"
              label="I read the guide before sending an issue." />

            <RaisedButton className="submit" label="Send" primary={true}
                          disabled={!this.state.userReadTheGuide}
                          onClick={this.handleClick}/>

            <Snackbar
              ref="SnackBar"
              className="snackbar"
              message="Your message was submitted. Thank you!"/>
          </Paper>

    );
  }

});

module.exports = Contact;<commit_msg>Disabled send contact button till its functional.<commit_after>var React = require('react/addons');
var Material = require('material-ui');
var Paper = Material.Paper;
var TextField = Material.TextField;
var RaisedButton = Material.RaisedButton;
var Checkbox = Material.Checkbox;
var Snackbar = Material.Snackbar;

var Contact = React.createClass({

  getInitialState() {
    return{
      validName: true,
      validEmail: true,
      validMessage: true,
      userReadTheGuide: false
    }
  },

  handleClick() {
    //Check inputs are valid
    var validName = true, validEmail = true, validMessage = true;
    if(this.refs.contactName.getValue().length == 0){
      validName = false;
    }

    if(!this.validateEmail(this.refs.contactEmail.getValue())){
      validEmail = false;
    }

    if(this.refs.contactMessage.getValue().length < 10){
      validMessage = false;
    }

    if(validName && validEmail && validMessage) {
      this.refs.SnackBar.show();
      this.refs.contactName.clearValue();
      this.refs.contactEmail.clearValue();
      this.refs.contactMessage.clearValue();
      this.refs.checkReadTheGuide.setChecked(false);

      this.setState({validName: validName, validEmail: validEmail, validMessage: validMessage,
        userReadTheGuide: false});

    }else{
      this.setState({validName: validName, validEmail: validEmail, validMessage: validMessage});
    }
  },

  handleChange(e){
    var value = e.target.value;
    switch(e.target.name){
      case "contactName":
        //Check name has at least 1 character
        if(!this.state.validName && value.length > 0){
          this.setState({validName: true});
        }
        break;
      case "contactEmail":
        //Check email is correct;
        if(!this.state.validEmail && this.validateEmail(value)){
          this.setState({validEmail: true});
        }
        break;
      case "contactMessage":
        //Check message has at least 10 characters
        if(!this.state.validMessage && value.length >= 10){
          this.setState({validMessage: true});
        }
        break;
      default:
        break;
    }
  },

  //From http://stackoverflow.com/a/46181/2277631 (is more than enough)
  validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
  },

  render() {
    return (

          <Paper zDepth={1} rounded={true} innerClassName={'contact-body'}>

Contact

To contact me, you can use our email
             or Twitter. It is also possible to
              use the form below.

            <TextField
              ref="contactName"
              name="contactName"
              className="field"
              onChange={this.handleChange}
              errorText={this.state.validName ? '' : 'This field is required.'}
              floatingLabelText="Your name"/>
            <TextField
              ref="contactEmail"
              name="contactEmail"
              className="field email"
              onChange={this.handleChange}
              hintText="valid@email.com"
              type="email"
              errorText={this.state.validEmail ? '' : 'Your email appears to be invalid.'}
              floatingLabelText="Your email"/>
            <TextField
              ref="contactMessage"
              name="contactMessage"
              className="message"
              onChange={this.handleChange}
              floatingLabelText="Your message"
              errorText={this.state.validMessage ? '' : 'Your message appears to be too short.'}
              multiLine={true}/>

            <Checkbox
              ref="checkReadTheGuide"
              onClick={(e) => {this.setState({userReadTheGuide: e.target.checked})}}
              className="checkbox"
              label="I read the guide before sending an issue." />

            {/* TODO for now disabled because it's not implemented */}
            <RaisedButton className="submit" label="Send" primary={true}
                          disabled={true}
                          onClick={this.handleClick}/>

            <Snackbar
              ref="SnackBar"
              className="snackbar"
              message="Your message was submitted. Thank you!"/>
          </Paper>

    );
  }

});

module.exports = Contact;<|endoftext|>


<commit_before>/*
 * Plantalytics
 *     Copyright (c) 2016 Sapphire Becker, Katy Brimm, Scott Ewing,
 *       Matt Fraser, Kelly Ledford, Michael Limb, Steven Ngo, Eric Turley.
 *     This project is licensed under the MIT License.
 *     Please see the file LICENSE in this distribution for license terms.
 * Contact: plantalytics.capstone@gmail.com
 */

/////////////////////////////////// Controls ///////////////////////////////////

$(function() {
    $("#menu").click(function() {
        var $menu = $(".menu");
        var visible = $menu.is(":visible");
        $menu.show();
        var width = $menu.width();
        var height = $menu.height();
        if (!$menu.is(':animated')) {
            if (visible) {
                // Animate hiding menu.
                $menu.animate({
                    "height": 10,
                }, {
                    "duration": 150,
                }).animate({
                    "width": 0,
                }, {
                    "duration": 300,
                    "queue": true,
                    "complete": function() {
                        $menu.width(width);
                        $menu.height(height);
                        $menu.hide();
                    }
                });
            } else {
                // Animate showing menu.
                $menu.width(0).height(10);
                $menu.animate({
                    "width": width,
                }, {
                    "duration": 150,
                }).animate({
                    "height": height,
                }, {
                    "duration": 300,
                    "queue": true
                });
            }
        }
    });

    $(".data-view-defaults .data-button-label div").click(function(e) {
        var parent = $(this).parent();
        var selector = "." + parent.attr("class").replace(/ /g, ".");
        if (localStorage.defaultDataView == selector) {
            // Double tap to turn off.
            delete localStorage.defaultDataView;
            setTimeout(function() {
                parent.find("input").prop("checked", false);
            }, 10);
        } else {
            // Set new default.
            localStorage.defaultDataView = selector;
        }
    });

    $('#leafwetness-button').click(makeGetEnvData("leafwetness"));

    $('#temperature-button').click(makeGetEnvData("temperature"));

    $('#humidity-button').click(makeGetEnvData("humidity"));

    $("#menu-logout").click(function() {
        // Delete access token from local storage.
        delete localStorage.accessToken;

        // Redirect to login page
        window.location = "index.html";
    });
});

function makeGetEnvData(env_variable) {
    return function () {
        $.ajax({
            "url": backendIpAddress + "env_data",
            "data": {
              "vineyard_id": 1,
              "env_variable": env_variable,
              "auth_token": localStorage.accessToken
            },
            "dataType": "json",
            "type": "GET",
        }).done(function(json) {
            if (json.env_data) {
                var envData = parseEnvData(json.env_data, env_variable);
                map.removeLayer(idw);
                idw = L.idwLayer(envData, idwOptions).addTo(map);
            } else {
                /* TODO: add error handing message*/
            }
        }).fail(function() {
            /* TODO: add error handing message*/
        });
    }
}

function parseEnvData(envData, envDataType) {
    var parsedData = [];
    for (var i = 0; i < envData.length; ++i) {
        var envDataItem = [];
        envDataItem[0] = envData[i].latitude;
        envDataItem[1] = envData[i].longitude;
        switch (envDataType) {
          case "leafwetness":
            envDataItem[2] = envData[i].leafwetness;
            break;
          case "temperature":
            envDataItem[2] = envData[i].temperature;
            break;
          case "humidity":
            envDataItem[2] = envData[i].humidity;
        }

        parsedData[i] = envDataItem;
    }

    return parsedData;
}
<commit_msg>FE#51: Switch env_data endpoint to POST<commit_after>/*
 * Plantalytics
 *     Copyright (c) 2016 Sapphire Becker, Katy Brimm, Scott Ewing,
 *       Matt Fraser, Kelly Ledford, Michael Limb, Steven Ngo, Eric Turley.
 *     This project is licensed under the MIT License.
 *     Please see the file LICENSE in this distribution for license terms.
 * Contact: plantalytics.capstone@gmail.com
 */

/////////////////////////////////// Controls ///////////////////////////////////

$(function() {
    $("#menu").click(function() {
        var $menu = $(".menu");
        var visible = $menu.is(":visible");
        $menu.show();
        var width = $menu.width();
        var height = $menu.height();
        if (!$menu.is(':animated')) {
            if (visible) {
                // Animate hiding menu.
                $menu.animate({
                    "height": 10,
                }, {
                    "duration": 150,
                }).animate({
                    "width": 0,
                }, {
                    "duration": 300,
                    "queue": true,
                    "complete": function() {
                        $menu.width(width);
                        $menu.height(height);
                        $menu.hide();
                    }
                });
            } else {
                // Animate showing menu.
                $menu.width(0).height(10);
                $menu.animate({
                    "width": width,
                }, {
                    "duration": 150,
                }).animate({
                    "height": height,
                }, {
                    "duration": 300,
                    "queue": true
                });
            }
        }
    });

    $(".data-view-defaults .data-button-label div").click(function(e) {
        var parent = $(this).parent();
        var selector = "." + parent.attr("class").replace(/ /g, ".");
        if (localStorage.defaultDataView == selector) {
            // Double tap to turn off.
            delete localStorage.defaultDataView;
            setTimeout(function() {
                parent.find("input").prop("checked", false);
            }, 10);
        } else {
            // Set new default.
            localStorage.defaultDataView = selector;
        }
    });

    $('#leafwetness-button').click(makeGetEnvData("leafwetness"));

    $('#temperature-button').click(makeGetEnvData("temperature"));

    $('#humidity-button').click(makeGetEnvData("humidity"));

    $("#menu-logout").click(function() {
        // Delete access token from local storage.
        delete localStorage.accessToken;

        // Redirect to login page
        window.location = "index.html";
    });
});

function makeGetEnvData(env_variable) {
    return function () {
        $.ajax({
            "url": backendIpAddress + "env_data",
            "data": JSON.stringify({
              "vineyard_id": 1,
              "env_variable": env_variable,
              "auth_token": localStorage.accessToken
            }),
            "dataType": "json",
            "type": "POST",
        }).done(function(json) {
            if (json.env_data) {
                var envData = parseEnvData(json.env_data, env_variable);
                map.removeLayer(idw);
                idw = L.idwLayer(envData, idwOptions).addTo(map);
            } else {
                /* TODO: add error handing message*/
            }
        }).fail(function() {
            /* TODO: add error handing message*/
        });
    }
}

function parseEnvData(envData, envDataType) {
    var parsedData = [];
    for (var i = 0; i < envData.length; ++i) {
        var envDataItem = [];
        envDataItem[0] = envData[i].latitude;
        envDataItem[1] = envData[i].longitude;
        switch (envDataType) {
          case "leafwetness":
            envDataItem[2] = envData[i].leafwetness;
            break;
          case "temperature":
            envDataItem[2] = envData[i].temperature;
            break;
          case "humidity":
            envDataItem[2] = envData[i].humidity;
        }

        parsedData[i] = envDataItem;
    }

    return parsedData;
}
<|endoftext|>


<commit_before>// from Eli Grey @ http://eligrey.com/blog/post/textcontent-in-ie8
if (Object.defineProperty && Object.getOwnPropertyDescriptor &&
    Object.getOwnPropertyDescriptor(Element.prototype, "textContent") &&
    !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) {
    (function() {
        var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
        Object.defineProperty(Element.prototype, "textContent", {
            // It won't work if you just drop in innerText.get
            // and innerText.set or the whole descriptor.
            get: function() {
                return innerText.get.call(this)
            },
            set: function(x) {
                return innerText.set.call(this, x)
            }
        });
    })();
}
<commit_msg>wrap Element.prototype.textContent shim in a try/catch for Firefox<commit_after>(function() {
    try {
        // from Eli Grey @ http://eligrey.com/blog/post/textcontent-in-ie8
        if (Object.defineProperty && Object.getOwnPropertyDescriptor &&
            Object.getOwnPropertyDescriptor(Element.prototype, "textContent") &&
            !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) {
            var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
            Object.defineProperty(Element.prototype, "textContent", {
                // It won't work if you just drop in innerText.get
                // and innerText.set or the whole descriptor.
                get: function() {
                    return innerText.get.call(this)
                },
                set: function(x) {
                    return innerText.set.call(this, x)
                }
            });
        }
    } catch (e) {
        // bad Firefox
    }
})();
<|endoftext|>


<commit_before><commit_msg>Added WeatherScoutEditor module to provide WeatherScout editor behavior. - Works with weather-scout-editor DOM element. - Re: issue #26.<commit_after><|endoftext|>


<commit_before>/*
 * This class contains utilities to help parse the data
 * author: ucla-cs
 * See COPYING for copyright and distribution information.
 */

var DataUtils = function DataUtils(){

};

/*
 * NOTE THIS IS CURRENTLY NOT BEHING USED
 *
 */

DataUtils.keyStr = "ABCDEFGHIJKLMNOP" +
               "QRSTUVWXYZabcdef" +
               "ghijklmnopqrstuv" +
               "wxyz0123456789+/" +
               "=";

/**
 * Raw String to Base 64
 */
DataUtils.stringtoBase64=function stringtoBase64(input) {
     input = escape(input);
     var output = "";
     var chr1, chr2, chr3 = "";
     var enc1, enc2, enc3, enc4 = "";
     var i = 0;

     do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
           enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
           enc4 = 64;
        }

        output = output +
           DataUtils.keyStr.charAt(enc1) +
           DataUtils.keyStr.charAt(enc2) +
           DataUtils.keyStr.charAt(enc3) +
           DataUtils.keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
     } while (i < input.length);

     return output;
  }

/**
 * Base 64 to Raw String
 */
DataUtils.base64toString = function base64toString(input) {
     var output = "";
     var chr1, chr2, chr3 = "";
     var enc1, enc2, enc3, enc4 = "";
     var i = 0;

     // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
     var base64test = /[^A-Za-z0-9\+\/\=]/g;
     /* Test for invalid characters. */
     if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" +
              "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
              "Expect errors in decoding.");
     }

     input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

     do {
        enc1 = DataUtils.keyStr.indexOf(input.charAt(i++));
        enc2 = DataUtils.keyStr.indexOf(input.charAt(i++));
        enc3 = DataUtils.keyStr.indexOf(input.charAt(i++));
        enc4 = DataUtils.keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
           output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
           output = output + String.fromCharCode(chr3);
        }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

     } while (i < input.length);

     return unescape(output);
  };

//byte []

/**
 * NOT WORKING!!!!!
 *
 * Unsiged Long Number to Byte Array
 */

 /*
DataUtils.unsignedLongToByteArray= function( value) {

	if(LOG>4)console.log('INPUT IS '+value);

	if( 0 == value )
		return [0];

	if( 0 <= value && value <= 0x00FF ) {
		//byte []
		var bb = new Array(1);
		bb[0] = (value & 0x00FF);
		return bb;
	}

	if(LOG>4) console.log('type of value is '+typeof value);
	if(LOG>4) console.log('value is '+value);
	//byte []
	var out = null;
	//int
	var offset = -1;
	for(var i = 7; i >=0; --i) {
		//byte
		console.log(i);
		console.log('value is '+value);
		console.log('(value >> (i * 8)) '+ (value >> (i * 8))  );
		console.log(' ((value >> (i * 8)) & 0xFF) '+ ((value >> (i * 8)) & 0xFF)  );

		var b = ((value >> (i * 8)) & 0xFF)  ;

		if(LOG>4) console.log('b is '+b);

		if( out == null && b != 0 ) {
			//out = new byte[i+1];
			out = new Array(i+1);
			offset = i;
		}

		if( out != null )
			out[ offset - i ] = b;
	}
	if(LOG>4)console.log('OUTPUT IS ');
	if(LOG>4)console.log(out);
	return out;
}
*/

/**
 * NOT WORKING!!!!!
 *
 * Unsiged Long Number to Byte Array
 *//*
DataUtils.byteArrayToUnsignedLong = function(//final byte []
	src) {
		if(LOG>4) console.log('INPUT IS ');
		if(LOG>4) console.log(src);

		var value = 0;
		for(var i = 0; i < src.length; i++) {
			value = value << 8;
			// Java will assume the byte is signed, so extend it and trim it.

			var b = ((src[i]) & 0xFF );
			value |= b;
		}

		if(LOG>4) console.log('OUTPUT IS ');

		if(LOG>4) console.log(value);

		return value;
	}*/

/**
 * Hex String to Byte Array
 */
	//THIS IS NOT WORKING
/*
DataUtils.HexStringtoByteArray = function(str) {
    var byteArray = [];
    for (var i = 0; i < str.length; i++)
        if (str.charCodeAt(i) <= 0x7F)
            byteArray.push(str.charCodeAt(i));
        else {
            var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
            for (var j = 0; j < h.length; j++)
                byteArray.push(parseInt(h[j], 16));
        }
    return byteArray;
};
*/

/**
 * Byte Array to Hex String
 */
DataUtils.byteArrayToHexString = function(byteArray) {
    var str = '';
    for (var i = 0; i < byteArray.length; i++)
        str +=  byteArray[i] <= 0x7F?
                byteArray[i] === 0x25 ? "%25" : // %
                String.fromCharCode(byteArray[i]) :
                "%" + byteArray[i].toString(16).toUpperCase();
    return decodeURIComponent(str);
};

/**
 * Byte array to Hex String
 */
//http://ejohn.org/blog/numbers-hex-and-colors/
DataUtils.toHex = function(arguments){
	if(LOG>4) console.log('ABOUT TO CONVERT '+ arguments);
  //console.log(arguments);
  var ret = "";
  for ( var i = 0; i < arguments.length; i++ )
    ret += (arguments[i] < 16 ? "0" : "") + arguments[i].toString(16);
  return ret; //.toUpperCase();
}

/**
 * Raw string to hex string.
 */
DataUtils.stringToHex = function(arguments){
	var ret = "";
	for (var i = 0; i < arguments.length; ++i) {
		var value = arguments.charCodeAt(i);
		ret += (value < 16 ? "0" : "") + value.toString(16);
	}
	return ret;
}

/**
 * Byte array to raw string
 */
//DOES NOT SEEM TO WORK
DataUtils.toString = function(arguments){
  //console.log(arguments);
  var ret = "";
  for ( var i = 0; i < arguments.length; i++ )
    ret += String.fromCharCode(arguments[i]);
  return ret;
}

/**
 * Hex String to byte array
 */
DataUtils.toNumbers=function( str ){
	if(typeof str =='string'){
		  var ret = [];
		   str.replace(/(..)/g, function(str){
		    ret.push( parseInt( str, 16 ) );
		  });
		   return ret;
    }
}

/**
 * Hex String to raw string.
 */
DataUtils.hexToRawString = function(str) {
    if(typeof str =='string') {
		var ret = "";
		str.replace(/(..)/g, function(s) {
			ret += String.fromCharCode(parseInt(s, 16));
		});
		return ret;
    }
}

/**
 * Raw String to Byte Array
 */
DataUtils.toNumbersFromString = function( str ){
	var bytes = new Array(str.length);
	for(var i=0;i<str.length;i++)
		bytes[i] = str.charCodeAt(i);
	return bytes;
}

DataUtils.encodeUtf8 = function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	};

	// public method for url decoding
DataUtils.decodeUtf8 = function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	};

	test = function(){
		console.log(DataUtils.decodeUtf8("HELLO.~"));
		return DataUtils.decodeUtf8("HELLO.~");
	}

//NOT WORKING
/*
DataUtils.getUTF8StringFromBytes = function(bytes) {

	bytes = toString(bytes);

    var ix = 0;

    if( bytes.slice(0,3) == "\xEF\xBB\xBF") {
        ix = 3;
    }

    var string = "";
    for( ; ix < bytes.length; ix++ ) {
        var byte1 = bytes[ix].charCodeAt(0);
        if( byte1 < 0x80 ) {
            string += String.fromCharCode(byte1);
        } else if( byte1 >= 0xC2 && byte1 < 0xE0 ) {
            var byte2 = bytes[++ix].charCodeAt(0);
            string += String.fromCharCode(((byte1&0x1F)<<6) + (byte2&0x3F));
        } else if( byte1 >= 0xE0 && byte1 < 0xF0 ) {
            var byte2 = bytes[++ix].charCodeAt(0);
            var byte3 = bytes[++ix].charCodeAt(0);
            string += String.fromCharCode(((byte1&0xFF)<<12) + ((byte2&0x3F)<<6) + (byte3&0x3F));
        } else if( byte1 >= 0xF0 && byte1 < 0xF5) {
            var byte2 = bytes[++ix].charCodeAt(0);
            var byte3 = bytes[++ix].charCodeAt(0);
            var byte4 = bytes[++ix].charCodeAt(0);
            var codepoint = ((byte1&0x07)<<18) + ((byte2&0x3F)<<12)+ ((byte3&0x3F)<<6) + (byte4&0x3F);
            codepoint -= 0x10000;
            string += String.fromCharCode(
                (codepoint>>10) + 0xD800,
                (codepoint&0x3FF) + 0xDC00
            );
        }
    }

    return string;
}*/

/**
 * Return true if a1 and a2 are the same length with equal elements.
 */
DataUtils.arraysEqual = function(a1, a2){
    if (a1.length != a2.length)
        return false;

    for (var i = 0; i < a1.length; ++i) {
        if (a1[i] != a2[i])
            return false;
    }

    return true;
}<commit_msg>Added bigEndianToUnsignedInt and nonNegativeIntToBigEndian.<commit_after>/*
 * This class contains utilities to help parse the data
 * author: ucla-cs
 * See COPYING for copyright and distribution information.
 */

var DataUtils = function DataUtils(){

};

/*
 * NOTE THIS IS CURRENTLY NOT BEHING USED
 *
 */

DataUtils.keyStr = "ABCDEFGHIJKLMNOP" +
               "QRSTUVWXYZabcdef" +
               "ghijklmnopqrstuv" +
               "wxyz0123456789+/" +
               "=";

/**
 * Raw String to Base 64
 */
DataUtils.stringtoBase64=function stringtoBase64(input) {
     input = escape(input);
     var output = "";
     var chr1, chr2, chr3 = "";
     var enc1, enc2, enc3, enc4 = "";
     var i = 0;

     do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
           enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
           enc4 = 64;
        }

        output = output +
           DataUtils.keyStr.charAt(enc1) +
           DataUtils.keyStr.charAt(enc2) +
           DataUtils.keyStr.charAt(enc3) +
           DataUtils.keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
     } while (i < input.length);

     return output;
  }

/**
 * Base 64 to Raw String
 */
DataUtils.base64toString = function base64toString(input) {
     var output = "";
     var chr1, chr2, chr3 = "";
     var enc1, enc2, enc3, enc4 = "";
     var i = 0;

     // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
     var base64test = /[^A-Za-z0-9\+\/\=]/g;
     /* Test for invalid characters. */
     if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" +
              "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
              "Expect errors in decoding.");
     }

     input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

     do {
        enc1 = DataUtils.keyStr.indexOf(input.charAt(i++));
        enc2 = DataUtils.keyStr.indexOf(input.charAt(i++));
        enc3 = DataUtils.keyStr.indexOf(input.charAt(i++));
        enc4 = DataUtils.keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
           output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
           output = output + String.fromCharCode(chr3);
        }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

     } while (i < input.length);

     return unescape(output);
  };

//byte []

/**
 * NOT WORKING!!!!!
 *
 * Unsiged Long Number to Byte Array
 */

 /*
DataUtils.unsignedLongToByteArray= function( value) {

	if(LOG>4)console.log('INPUT IS '+value);

	if( 0 == value )
		return [0];

	if( 0 <= value && value <= 0x00FF ) {
		//byte []
		var bb = new Array(1);
		bb[0] = (value & 0x00FF);
		return bb;
	}

	if(LOG>4) console.log('type of value is '+typeof value);
	if(LOG>4) console.log('value is '+value);
	//byte []
	var out = null;
	//int
	var offset = -1;
	for(var i = 7; i >=0; --i) {
		//byte
		console.log(i);
		console.log('value is '+value);
		console.log('(value >> (i * 8)) '+ (value >> (i * 8))  );
		console.log(' ((value >> (i * 8)) & 0xFF) '+ ((value >> (i * 8)) & 0xFF)  );

		var b = ((value >> (i * 8)) & 0xFF)  ;

		if(LOG>4) console.log('b is '+b);

		if( out == null && b != 0 ) {
			//out = new byte[i+1];
			out = new Array(i+1);
			offset = i;
		}

		if( out != null )
			out[ offset - i ] = b;
	}
	if(LOG>4)console.log('OUTPUT IS ');
	if(LOG>4)console.log(out);
	return out;
}
*/

/**
 * NOT WORKING!!!!!
 *
 * Unsiged Long Number to Byte Array
 *//*
DataUtils.byteArrayToUnsignedLong = function(//final byte []
	src) {
		if(LOG>4) console.log('INPUT IS ');
		if(LOG>4) console.log(src);

		var value = 0;
		for(var i = 0; i < src.length; i++) {
			value = value << 8;
			// Java will assume the byte is signed, so extend it and trim it.

			var b = ((src[i]) & 0xFF );
			value |= b;
		}

		if(LOG>4) console.log('OUTPUT IS ');

		if(LOG>4) console.log(value);

		return value;
	}*/

/**
 * Hex String to Byte Array
 */
	//THIS IS NOT WORKING
/*
DataUtils.HexStringtoByteArray = function(str) {
    var byteArray = [];
    for (var i = 0; i < str.length; i++)
        if (str.charCodeAt(i) <= 0x7F)
            byteArray.push(str.charCodeAt(i));
        else {
            var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
            for (var j = 0; j < h.length; j++)
                byteArray.push(parseInt(h[j], 16));
        }
    return byteArray;
};
*/

/**
 * Byte Array to Hex String
 */
DataUtils.byteArrayToHexString = function(byteArray) {
    var str = '';
    for (var i = 0; i < byteArray.length; i++)
        str +=  byteArray[i] <= 0x7F?
                byteArray[i] === 0x25 ? "%25" : // %
                String.fromCharCode(byteArray[i]) :
                "%" + byteArray[i].toString(16).toUpperCase();
    return decodeURIComponent(str);
};

/**
 * Byte array to Hex String
 */
//http://ejohn.org/blog/numbers-hex-and-colors/
DataUtils.toHex = function(arguments){
	if(LOG>4) console.log('ABOUT TO CONVERT '+ arguments);
  //console.log(arguments);
  var ret = "";
  for ( var i = 0; i < arguments.length; i++ )
    ret += (arguments[i] < 16 ? "0" : "") + arguments[i].toString(16);
  return ret; //.toUpperCase();
}

/**
 * Raw string to hex string.
 */
DataUtils.stringToHex = function(arguments){
	var ret = "";
	for (var i = 0; i < arguments.length; ++i) {
		var value = arguments.charCodeAt(i);
		ret += (value < 16 ? "0" : "") + value.toString(16);
	}
	return ret;
}

/**
 * Byte array to raw string
 */
//DOES NOT SEEM TO WORK
DataUtils.toString = function(arguments){
  //console.log(arguments);
  var ret = "";
  for ( var i = 0; i < arguments.length; i++ )
    ret += String.fromCharCode(arguments[i]);
  return ret;
}

/**
 * Hex String to byte array
 */
DataUtils.toNumbers=function( str ){
	if(typeof str =='string'){
		  var ret = [];
		   str.replace(/(..)/g, function(str){
		    ret.push( parseInt( str, 16 ) );
		  });
		   return ret;
    }
}

/**
 * Hex String to raw string.
 */
DataUtils.hexToRawString = function(str) {
    if(typeof str =='string') {
		var ret = "";
		str.replace(/(..)/g, function(s) {
			ret += String.fromCharCode(parseInt(s, 16));
		});
		return ret;
    }
}

/**
 * Raw String to Byte Array
 */
DataUtils.toNumbersFromString = function( str ){
	var bytes = new Array(str.length);
	for(var i=0;i<str.length;i++)
		bytes[i] = str.charCodeAt(i);
	return bytes;
}

DataUtils.encodeUtf8 = function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	};

	// public method for url decoding
DataUtils.decodeUtf8 = function (utftext) {
		var string = "";
		var i = 0;
		var c = 0;
        var c1 = 0;
        var c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				var c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	};

	test = function(){
		console.log(DataUtils.decodeUtf8("HELLO.~"));
		return DataUtils.decodeUtf8("HELLO.~");
	}

//NOT WORKING
/*
DataUtils.getUTF8StringFromBytes = function(bytes) {

	bytes = toString(bytes);

    var ix = 0;

    if( bytes.slice(0,3) == "\xEF\xBB\xBF") {
        ix = 3;
    }

    var string = "";
    for( ; ix < bytes.length; ix++ ) {
        var byte1 = bytes[ix].charCodeAt(0);
        if( byte1 < 0x80 ) {
            string += String.fromCharCode(byte1);
        } else if( byte1 >= 0xC2 && byte1 < 0xE0 ) {
            var byte2 = bytes[++ix].charCodeAt(0);
            string += String.fromCharCode(((byte1&0x1F)<<6) + (byte2&0x3F));
        } else if( byte1 >= 0xE0 && byte1 < 0xF0 ) {
            var byte2 = bytes[++ix].charCodeAt(0);
            var byte3 = bytes[++ix].charCodeAt(0);
            string += String.fromCharCode(((byte1&0xFF)<<12) + ((byte2&0x3F)<<6) + (byte3&0x3F));
        } else if( byte1 >= 0xF0 && byte1 < 0xF5) {
            var byte2 = bytes[++ix].charCodeAt(0);
            var byte3 = bytes[++ix].charCodeAt(0);
            var byte4 = bytes[++ix].charCodeAt(0);
            var codepoint = ((byte1&0x07)<<18) + ((byte2&0x3F)<<12)+ ((byte3&0x3F)<<6) + (byte4&0x3F);
            codepoint -= 0x10000;
            string += String.fromCharCode(
                (codepoint>>10) + 0xD800,
                (codepoint&0x3FF) + 0xDC00
            );
        }
    }

    return string;
}*/

/**
 * Return true if a1 and a2 are the same length with equal elements.
 */
DataUtils.arraysEqual = function(a1, a2){
    if (a1.length != a2.length)
        return false;

    for (var i = 0; i < a1.length; ++i) {
        if (a1[i] != a2[i])
            return false;
    }

    return true;
};

/*
 * Convert the big endian byte array to an unsigned int.
 * Don't check for overflow.
 */
DataUtils.bigEndianToUnsignedInt = function(bytes) {
    var result = 0;
    for (var i = 0; i < bytes.length; ++i) {
        result <<= 8;
        result += bytes[i];
    }
    return result;
};

/*
 * Convert the int value to a new big endian byte array and return.
 * If value is 0 or negative, return [].
 */
DataUtils.nonNegativeIntToBigEndian = function(value) {
    var result = [];
    if (value <= 0)
        return result;

    while (value != 0) {
        result.unshift(value & 0xff);
        value >>= 8;
    }
    return result;
};
<|endoftext|>


<commit_before><commit_msg>var -let<commit_after><|endoftext|>


<commit_before>'use strict';

const mongoose = require('mongoose');
const assert = require('assert');
const express = require('express');
const bodyParser = require('body-parser');
const request = require('supertest');

const Restaman = require('..');
const ModelWrapper = require('..').ModelWrapper;

describe('Restaman', function () {

    before(done => {

        mongoose.connect('localhost/restaman-test-db', () => {
            const testSchema = new mongoose.Schema(
                {_id: Number, name: String, object: {someProp: String}},
                {versionKey: false}
            );
            testSchema.statics.exposedStaticMethod = function (param1, param2) {
                return {message: `exposedStaticMethod invoked with: param1: '${param1}', param2: '${param2}'`};
            };
            testSchema.statics.exposedStaticMethod2 = function (param1, param2) {
                return {message: `exposedStaticMethod2 invoked with: param1: '${param1}', param2: '${param2}'`};
            };
            const postSchema = new mongoose.Schema(
                {_id: Number, title: String, content: String, user: Number, field1: String, field2: String},
                {versionKey: false}
            );

            mongoose.model('Post', postSchema);
            mongoose.model('Test', testSchema);
            mongoose.model('Test').remove()
                .then(() => mongoose.model('Post').remove())
                .then(() => done()).catch(done);
        });

    });

    describe('Adding model', function () {
        it('should return ModelWrapper instance', () => {
            const restaman = new Restaman();
            restaman.removeModel('Test');
            let modelWrapper = restaman.addModel('Test');
            assert.equal(modelWrapper instanceof ModelWrapper, true);
        });
    });

    describe('Exposing static method', function () {
        const restaman = new Restaman();
        let modelWrapper = restaman.addModel('Test');

        it('should done without errors when method exists in model statics', () => {
            modelWrapper.exposeStatic('exposedStaticMethod');
        });
        it('should produce error when method exists in model statics', done => {
            try {
                modelWrapper.exposeStatic('wrongStaticMethod');
                done('Error not produced!');
            } catch (err) {
                done();
            }
        });
        it('should add method to statics list', () => {
            modelWrapper.exposeStatic('exposedStaticMethod');
            let statics = modelWrapper.getStatics();
            assert.deepEqual(statics, [{name: 'exposedStaticMethod', exposeName: 'exposedStaticMethod'}])
        });
        it('should replace method with same exposeName', () => {
            modelWrapper.exposeStatic('exposedStaticMethod');
            modelWrapper.exposeStatic({name: 'exposedStaticMethod2', exposeName: 'exposedStaticMethod'});
            let statics = modelWrapper.getStatics();
            assert.deepEqual(statics, [{name: 'exposedStaticMethod2', exposeName: 'exposedStaticMethod'}])
        });
    });

    describe('Base routes', function () {

        const app = express();
        const restaman = new Restaman();
        let server;

        before(done => {
            restaman.addModel('Test').exposeStatic('exposedStaticMethod');
            let router = restaman.router();
            app.use(bodyParser.json());
            app.use('/api', router);
            app.get('/', (req, res) => {
                res.cookie('cookie', 'hey');
                res.send({message: 'OK!!!'})
            });
            app.post('/', (req, res) => res.send(req.body));
            server = app.listen(3003, () => {
                done();
            });
        });

        after(done => server.close(done));

        it('GET /', done => request(app).get('/')
            .expect('set-cookie', 'cookie=hey; Path=/')
            .expect(200, {message: 'OK!!!'}, done));

        it('POST /', done => request(app).post('/').send({msg: 'hello'}).expect(200, {msg: 'hello'}, done));

        it(`POST /api/tests "{name: 'someName', _id: 1}"`, done => {
            request(app)
                .post('/api/tests')
                .send({name: 'someName', _id: 1})
                .expect(200, {name: 'someName', _id: 1}, done)
        });

        it('GET /api/tests', done => {
            request(app)
                .get('/api/tests')
                .expect(200, [{name: 'someName', _id: 1}], done)
        });

        it('GET /api/tests/1', done => {
            request(app)
                .get('/api/tests/1')
                .expect(200, {name: 'someName', _id: 1}, done)
        });

        it(`POST /api/tests/1 "{name: 'newName', _id: 1}"`, done => {
            request(app)
                .post('/api/tests/1')
                .send({name: 'newName', _id: 1})
                .expect(200, {name: 'newName', _id: 1})
                .end(() => {
                    request(app).get('/api/tests').expect(200, [{name: 'newName', _id: 1}], done)
                });
        });

        it(`DELETE /api/tests/1`, done => {
            request(app)
                .delete('/api/tests/1')
                .expect(200, {name: 'newName', _id: 1})
                .end(() => {
                    request(app).get('/api/tests').expect(200, [], done)
                });
        });

        it(`POST /api/tests/exposedStaticMethod`, done => {
            request(app)
                .post('/api/tests/exposedStaticMethod')
                .send({param2: 'param2 value', param1: 'param1 value'})
                .expect(200, {message: `exposedStaticMethod invoked with: param1: 'param1 value', param2: 'param2 value'`}, done);

        });

    });

    describe('Hooks', function () {

        const app = express();
        const restaman = new Restaman();
        let server;

        before(done => {
            const filterUser = (req, res, query) => query.filter.user = 1;
            const addContent = (req, res) => req.body.content = 'from pre create hook';
            const updateContent = (req, res, doc) => doc.content = 'from pre update hook';
            const restrictDelete = () => {
                throw new Error('Oops!')
            };
            const restrictCount = function (req, res, next) {
                res.status(401).send({message: 'count op not allowed for you!'});
            };

            restaman.addModel('Test')
                .exposeStatic('exposedStaticMethod');
            let _post = restaman.addModel('Post')
                .pre('create', addContent)
                .pre('update', updateContent)
                .pre('find', filterUser)
                .pre('delete', restrictDelete)
                .middleware('count', restrictCount)
                .hide(['field1', 'field2']);

            let router = restaman.router();

            app.use(bodyParser.json());
            app.use('/api', router);

            /* error handler */
            app.use(function (err, req, res, next) {
                res.status(err.statusCode || 400).send({message: err.message}).end();
            });

            server = app.listen(3003, done);
        });

        after(done => server.close(done));

        it(`Add test Post "{title: 'some title', user: 1, _id: 1}"`, done => {
            request(app)
                .post('/api/posts')
                .send({title: 'some title', user: 1, _id: 1})
                .expect(200, {title: 'some title', user: 1, _id: 1, content: 'from pre create hook'}, done);
        });
        it(`Add test Post "{title: 'other title', user: 2, _id: 1}"`, done => {
            request(app)
                .post('/api/posts')
                .send({title: 'some title', user: 2, _id: 2, field1: '111'})
                .expect(200, {title: 'some title', user: 2, _id: 2, content: 'from pre create hook'}, done);
        });
        it(`pre create hook`, done => {
            request(app)
                .get('/api/posts/1')
                .expect(200, {title: 'some title', user: 1, _id: 1, content: 'from pre create hook'}, done);
        });
        it(`pre update hook`, done => {
            request(app)
                .post('/api/posts/1')
                .send({title: 'some title', user: 3, _id: 2})
                .expect(200, {title: 'some title', user: 3, _id: 2, content: 'from pre update hook'}, done);
        });
        it(`pre find hook`, done => {
            request(app)
                .get('/api/posts')
                .expect(200, [{title: 'some title', user: 1, _id: 1, content: 'from pre create hook'}], done);
        });
        it(`pre delete hook`, done => {
            request(app)
                .delete('/api/posts/1')
                .expect(400, {message: 'Oops!'}, done);
        });

        it(`middleware`, done => {
            request(app)
                .get('/api/posts/count')
                .expect(401, {message: 'count op not allowed for you!'}, done);
        });
        it(`hide`, done => {
            request(app)
                .get('/api/posts/2')
                .expect(200, {title: 'some title', user: 3, _id: 2, content: 'from pre update hook'}, done);
        });
    });

});

<commit_msg>added tests for `count` query<commit_after>'use strict';

const mongoose = require('mongoose');
const assert = require('assert');
const express = require('express');
const bodyParser = require('body-parser');
const request = require('supertest');

const Restaman = require('..');
const ModelWrapper = require('..').ModelWrapper;

describe('Restaman', function () {

    before(done => {

        mongoose.connect('localhost/restaman-test-db', () => {
            const testSchema = new mongoose.Schema(
                {_id: Number, name: String, object: {someProp: String}},
                {versionKey: false}
            );
            testSchema.statics.exposedStaticMethod = function (param1, param2) {
                return {message: `exposedStaticMethod invoked with: param1: '${param1}', param2: '${param2}'`};
            };
            testSchema.statics.exposedStaticMethod2 = function (param1, param2) {
                return {message: `exposedStaticMethod2 invoked with: param1: '${param1}', param2: '${param2}'`};
            };
            const postSchema = new mongoose.Schema(
                {_id: Number, title: String, content: String, user: Number, field1: String, field2: String},
                {versionKey: false}
            );

            mongoose.model('Post', postSchema);
            mongoose.model('Test', testSchema);
            mongoose.model('Test').remove()
                .then(() => mongoose.model('Post').remove())
                .then(() => done()).catch(done);
        });

    });

    describe('Adding model', function () {
        it('should return ModelWrapper instance', () => {
            const restaman = new Restaman();
            restaman.removeModel('Test');
            let modelWrapper = restaman.addModel('Test');
            assert.equal(modelWrapper instanceof ModelWrapper, true);
        });
    });

    describe('Exposing static method', function () {
        const restaman = new Restaman();
        let modelWrapper = restaman.addModel('Test');

        it('should done without errors when method exists in model statics', () => {
            modelWrapper.exposeStatic('exposedStaticMethod');
        });
        it('should produce error when method exists in model statics', done => {
            try {
                modelWrapper.exposeStatic('wrongStaticMethod');
                done('Error not produced!');
            } catch (err) {
                done();
            }
        });
        it('should add method to statics list', () => {
            modelWrapper.exposeStatic('exposedStaticMethod');
            let statics = modelWrapper.getStatics();
            assert.deepEqual(statics, [{name: 'exposedStaticMethod', exposeName: 'exposedStaticMethod'}])
        });
        it('should replace method with same exposeName', () => {
            modelWrapper.exposeStatic('exposedStaticMethod');
            modelWrapper.exposeStatic({name: 'exposedStaticMethod2', exposeName: 'exposedStaticMethod'});
            let statics = modelWrapper.getStatics();
            assert.deepEqual(statics, [{name: 'exposedStaticMethod2', exposeName: 'exposedStaticMethod'}])
        });
    });

    describe('Base routes', function () {

        const app = express();
        const restaman = new Restaman();
        let server;

        before(done => {
            restaman.addModel('Test').exposeStatic('exposedStaticMethod');
            let router = restaman.router();
            app.use(bodyParser.json());
            app.use('/api', router);
            app.get('/', (req, res) => {
                res.cookie('cookie', 'hey');
                res.send({message: 'OK!!!'})
            });
            app.post('/', (req, res) => res.send(req.body));
            server = app.listen(3003, () => {
                done();
            });
        });

        after(done => server.close(done));

        it('GET /', done => request(app).get('/')
            .expect('set-cookie', 'cookie=hey; Path=/')
            .expect(200, {message: 'OK!!!'}, done));

        it('POST /', done => request(app).post('/').send({msg: 'hello'}).expect(200, {msg: 'hello'}, done));

        it(`POST /api/tests "{name: 'someName', _id: 1}"`, done => {
            request(app)
                .post('/api/tests')
                .send({name: 'someName', _id: 1})
                .expect(200, {name: 'someName', _id: 1}, done)
        });
        it(`POST /api/tests "{name: 'someName2', _id: 2}"`, done => {
            request(app)
                .post('/api/tests')
                .send({name: 'someName2', _id: 2})
                .expect(200, {name: 'someName2', _id: 2}, done)
        });
        it('GET /api/tests', done => {
            request(app)
                .get('/api/tests')
                .expect(200, [{name: 'someName', _id: 1}, {name: 'someName2', _id: 2}], done)
        });

        it('GET /api/tests/1', done => {
            request(app)
                .get('/api/tests/1')
                .expect(200, {name: 'someName', _id: 1}, done)
        });

        it(`POST /api/tests/1 "{name: 'newName', _id: 1}"`, done => {
            request(app)
                .post('/api/tests/1')
                .send({name: 'newName', _id: 1})
                .expect(200, {name: 'newName', _id: 1})
                .end(() => {
                    request(app).get('/api/tests').expect(200, [{name: 'newName', _id: 1}, {
                        _id: 2,
                        name: 'someName2'
                    }], done)
                });
        });

        it(`GET /api/tests/count`, done => {
            request(app)
                .get('/api/tests/count')
                .expect(200, {count: 2}, done)
        });

        it(`GET /api/tests/count?_id=2`, done => {
            request(app)
                .get('/api/tests/count')
                .query({_id: 2 })
                .expect(200, {count: 1}, done)
        });

        it(`DELETE /api/tests/1`, done => {
            request(app)
                .delete('/api/tests/1')
                .expect(200, {name: 'newName', _id: 1})
                .end(() => {
                    request(app).get('/api/tests').expect(200, [{_id: 2, name: 'someName2'}], done)
                });
        });

        it(`POST /api/tests/exposedStaticMethod`, done => {
            request(app)
                .post('/api/tests/exposedStaticMethod')
                .send({param2: 'param2 value', param1: 'param1 value'})
                .expect(200, {message: `exposedStaticMethod invoked with: param1: 'param1 value', param2: 'param2 value'`}, done);

        });

    });

    describe('Hooks', function () {

        const app = express();
        const restaman = new Restaman();
        let server;

        before(done => {
            const filterUser = (req, res, query) => query.filter.user = 1;
            const addContent = (req, res) => req.body.content = 'from pre create hook';
            const updateContent = (req, res, doc) => doc.content = 'from pre update hook';
            const restrictDelete = () => {
                throw new Error('Oops!')
            };
            const restrictCount = function (req, res, next) {
                res.status(401).send({message: 'count op not allowed for you!'});
            };

            restaman.addModel('Test')
                .exposeStatic('exposedStaticMethod');
            let _post = restaman.addModel('Post')
                .pre('create', addContent)
                .pre('update', updateContent)
                .pre('find', filterUser)
                .pre('delete', restrictDelete)
                .middleware('count', restrictCount)
                .hide(['field1', 'field2']);

            let router = restaman.router();

            app.use(bodyParser.json());
            app.use('/api', router);

            /* error handler */
            app.use(function (err, req, res, next) {
                res.status(err.statusCode || 400).send({message: err.message}).end();
            });

            server = app.listen(3003, done);
        });

        after(done => server.close(done));

        it(`Add test Post "{title: 'some title', user: 1, _id: 1}"`, done => {
            request(app)
                .post('/api/posts')
                .send({title: 'some title', user: 1, _id: 1})
                .expect(200, {title: 'some title', user: 1, _id: 1, content: 'from pre create hook'}, done);
        });
        it(`Add test Post "{title: 'other title', user: 2, _id: 1}"`, done => {
            request(app)
                .post('/api/posts')
                .send({title: 'some title', user: 2, _id: 2, field1: '111'})
                .expect(200, {title: 'some title', user: 2, _id: 2, content: 'from pre create hook'}, done);
        });
        it(`pre create hook`, done => {
            request(app)
                .get('/api/posts/1')
                .expect(200, {title: 'some title', user: 1, _id: 1, content: 'from pre create hook'}, done);
        });
        it(`pre update hook`, done => {
            request(app)
                .post('/api/posts/1')
                .send({title: 'some title', user: 3, _id: 2})
                .expect(200, {title: 'some title', user: 3, _id: 2, content: 'from pre update hook'}, done);
        });
        it(`pre find hook`, done => {
            request(app)
                .get('/api/posts')
                .expect(200, [{title: 'some title', user: 1, _id: 1, content: 'from pre create hook'}], done);
        });
        it(`pre delete hook`, done => {
            request(app)
                .delete('/api/posts/1')
                .expect(400, {message: 'Oops!'}, done);
        });

        it(`middleware`, done => {
            request(app)
                .get('/api/posts/count')
                .expect(401, {message: 'count op not allowed for you!'}, done);
        });
        it(`hide`, done => {
            request(app)
                .get('/api/posts/2')
                .expect(200, {title: 'some title', user: 3, _id: 2, content: 'from pre update hook'}, done);
        });
    });

});

<|endoftext|>