<commit_before>/* global User, Group, Document, sails, Auth, Authorship, SqlService, Alias */
'use strict';

/**
 * User
 *
 * @module      :: Model
 * @description :: This is the base user model
 * @docs        :: http://waterlock.ninja/documentation
 */

const assert = require('assert');
const _ = require('lodash');
const waterlock = require('waterlock');
const Promise = require("bluebird");
const ResearchEntity = require('../lib/ResearchEntity');

const USER = 'user';
const ADMINISTRATOR = 'administrator';

module.exports = _.merge({}, ResearchEntity, {
    DEFAULT_SORTING: {
        surname: 'asc',
        name: 'asc',
        updatedAt: 'desc'
    },
    USER: USER,
    ADMINISTRATOR: ADMINISTRATOR,
    searchKey: 'username',
    attributes: require('waterlock').models.user.attributes({
        //Constants
        username: {
            type: 'email',
            defaultsTo: ""
        },
        name: {
            type: 'STRING',
            defaultsTo: ""
        },
        surname: {
            type: 'STRING',
            defaultsTo: ""
        },
        slug: {
            type: 'STRING',
            unique: true,
            alphanumericdashed: true,
            minLength: 3,
            maxLength: 30,
            defaultsTo: ""
        },
        alreadyAccess: {
            type: "BOOLEAN",
            defaultsTo: false
        },
        alreadyOpenedSuggested: {
            type: "BOOLEAN",
            defaultsTo: false
        },
        role: {
            type: 'STRING',
            enum: [USER, ADMINISTRATOR],
            defaultsTo: USER
        },
        orcidId: {
            type: 'STRING'
        },
        scopusId: {
            type: 'STRING'
        },
        jobTitle: {
            type: 'STRING'
        },
        drafts: {
            collection: 'Document',
            via: 'draftCreator'
        },
        documents: {
            collection: 'Document',
            via: 'users',
            through: 'authorship'
        },
        publicDocuments: {
            collection: 'Document',
            via: 'researchEntity',
            through: 'publicauthorship'
        },
        disseminationTalks: {
            collection: 'Document',
            via: 'researchEntity',
            through: 'disseminationtalk'
        },
        scientificTalks: {
            collection: 'Document',
            via: 'researchEntity',
            through: 'scientifictalk'
        },
        publications: {
            collection: 'Document',
            via: 'researchEntity',
            through: 'publication'
        },
        suggestedDocuments: {
            collection: 'Document',
            via: 'users',
            through: 'documentsuggestion'
        },
        externalDocuments: {
            collection: 'document',
            via: 'researchEntity',
            through: 'externaldocument'
        },
        authorships: {
            collection: 'authorship',
            via: 'researchEntity',
        },
        discardedDocuments: {
            collection: 'Document',
            via: 'discardedCoauthors',
            through: 'discarded'
        },
        jsonWebTokens: {
            collection: 'jwt',
            via: 'owner'
        },
        collaborations: {
            collection: 'collaboration',
            via: 'user'
        },
        aliases: {
            collection: 'alias',
            via: 'user'
        },
        administratedGroups: {
            collection: 'group',
            via: 'administrators',
            through: 'groupadministrator'
        },
        memberships: {
            collection: 'Group',
            via: 'members',
            through: 'membership'
        },
        attributes: {
            collection: 'Attribute',
            through: 'userattribute'
        },
        getAliases: async function () {
            const aliases = await Alias.find({user: this.id});
            return aliases.map(a => a.str);
        },
        getType: function () {
            return 'user';
        }
    }),
    getAdministeredGroups: function (userId) {
        return User.findOneById(userId)
            .populate('administratedGroups')
            .then(function (user) {
                return user.administratedGroups;
            });
    },
    setSlug: async function (user) {
        const basicSlug = user.username.toLowerCase().trim().replace(/\./gi, '-').split('@')[0];

        let slug = basicSlug;
        while (true) {
            const otherUserBySlug = await User.findOneBySlug(slug);
            if (!otherUserBySlug)
                break;
            slug = basicSlug + _.random(1, 999);
        }

        user.slug = slug;
        return user;
    },
    createCompleteUser: function (params) {
        params.username = _.toLower(params.username);
        var attributes = _.keys(User._attributes);
        var userObj = _.pick(params, attributes);

        return Promise.resolve(userObj)
            .then(User.checkUsername)
            .then(User.create)
            .then(function (user) {
                var authAttributes = _.keys(Auth._attributes);
                var auth = _.pick(params, authAttributes);<commit_msg>Refactor.<commit_after>/* global User, Group, Document, sails, Auth, Authorship, SqlService, Alias */
'use strict';

/**
 * User
 *
 * @module      :: Model
 * @description :: This is the base user model
 * @docs        :: http://waterlock.ninja/documentation
 */

const assert = require('assert');
const _ = require('lodash');
const waterlock = require('waterlock');
const Promise = require("bluebird");
const ResearchEntity = require('../lib/ResearchEntity');

const USER = 'user';
const ADMINISTRATOR = 'administrator';

module.exports = _.merge({}, ResearchEntity, {
    DEFAULT_SORTING: {
        surname: 'asc',
        name: 'asc',
        updatedAt: 'desc'
    },
    USER: USER,
    ADMINISTRATOR: ADMINISTRATOR,
    searchKey: 'username',
    attributes: require('waterlock').models.user.attributes({
        //Constants
        username: {
            type: 'email',
            defaultsTo: ""
        },
        name: {
            type: 'STRING',
            defaultsTo: ""
        },
        surname: {
            type: 'STRING',
            defaultsTo: ""
        },
        slug: {
            type: 'STRING',
            unique: true,
            alphanumericdashed: true,
            minLength: 3,
            maxLength: 30,
            defaultsTo: ""
        },
        alreadyAccess: {
            type: "BOOLEAN",
            defaultsTo: false
        },
        alreadyOpenedSuggested: {
            type: "BOOLEAN",
            defaultsTo: false
        },
        role: {
            type: 'STRING',
            enum: [USER, ADMINISTRATOR],
            defaultsTo: USER
        },
        orcidId: {
            type: 'STRING'
        },
        scopusId: {
            type: 'STRING'
        },
        jobTitle: {
            type: 'STRING'
        },
        drafts: {
            collection: 'Document',
            via: 'draftCreator'
        },
        documents: {
            collection: 'Document',
            via: 'users',
            through: 'authorship'
        },
        publicDocuments: {
            collection: 'Document',
            via: 'researchEntity',
            through: 'publicauthorship'
        },
        disseminationTalks: {
            collection: 'Document',
            via: 'researchEntity',
            through: 'disseminationtalk'
        },
        scientificTalks: {
            collection: 'Document',
            via: 'researchEntity',
            through: 'scientifictalk'
        },
        publications: {
            collection: 'Document',
            via: 'researchEntity',
            through: 'publication'
        },
        suggestedDocuments: {
            collection: 'Document',
            via: 'users',
            through: 'documentsuggestion'
        },
        externalDocuments: {
            collection: 'document',
            via: 'researchEntity',
            through: 'externaldocument'
        },
        authorships: {
            collection: 'authorship',
            via: 'researchEntity',
        },
        discardedDocuments: {
            collection: 'Document',
            via: 'discardedCoauthors',
            through: 'discarded'
        },
        jsonWebTokens: {
            collection: 'jwt',
            via: 'owner'
        },
        collaborations: {
            collection: 'collaboration',
            via: 'user'
        },
        aliases: {
            collection: 'alias',
            via: 'user'
        },
        administratedGroups: {
            collection: 'group',
            via: 'administrators',
            through: 'groupadministrator'
        },
        memberships: {
            collection: 'Group',
            via: 'members',
            through: 'membership'
        },
        attributes: {
            collection: 'Attribute',
            through: 'userattribute'
        },
        getAliases: async function () {
            const aliases = await Alias.find({user: this.id});
            return aliases.map(a => a.str);
        },
        getType: function () {
            return 'user';
        }
    }),
    getAdministeredGroups: function (userId) {
        return User.findOneById(userId)
            .populate('administratedGroups')
            .then(function (user) {
                return user.administratedGroups;
            });
    },
    setSlug: async function (user) {
        const basicSlug = user.username.toLowerCase().trim().replace(/\./gi, '-').split('@')[0];

        let slug = basicSlug;
        while (true) {
            const otherUserBySlug = await User.findOneBySlug(slug);
            if (!otherUserBySlug)
                break;
            slug = basicSlug + _.random(1, 999);
        }

        user.slug = slug;
        return user;
    },
    createCompleteUser: async function (params) {
        params.username = _.toLower(params.username);
        const attributes = _.keys(User._attributes);
        const userObj = _.pick(params, attributes);
        await User.checkUsername(userObj);
        const user = await User.create(userObj);
        const authAttributes = _.keys(Auth._attributes);
        const auth = _.pick(params, authAttributes);
        return new Promise(function (resolve, reject) {
            waterlock.engine.attachAuthToUser(auth, user,
                function (err) {
                    if (err)
                        reject(err);
                    else
                        resolve(user);
                });
        });

        return Promise.resolve(userObj)
            .then(User.checkUsername)
            .then(User.create)
            .then(function (user) {
                var authAttributes = _.keys(Auth._attributes);
                var auth = _.pick(params, authAttributes);
{'fraction_non_alphanumeric': 0.1178253283129764, 'fraction_numerical': 0.0014693727615024336, 'mean_word_length': 1.4931318681318682, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '186776', 'n_tokens_mistral': 2892, 'n_tokens_neox': 2812, 'n_words': 611}