Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
touchto-core / modules / user.js
Size: Mime:
/* eslint-disable func-names */
const config = require( 'config' );
const debug = require( 'debug' )( 'touchto:base-user' );
const phpass = require( 'phpass' );
const mongoose = require( 'mongoose' );
mongoose.Promise = require( 'bluebird' );

const collection = config.has( 'database.collection.users' ) ?
    config.get( 'database.collections.users' ) : undefined;

const required = val => !!val;

const passwordhash = new phpass.PasswordHash();
const createPasswordHash = password => passwordhash.hashPassword( password );

const userSchema = new mongoose.Schema( {
    mail: {
        type: String,
        unique: true,
        validate: [{
            validator: /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/,
            msg: 'A valid email address is required',
        },
        {
            validator: required,
            msg: 'An email address is required',
        }],
    },
    passwd: {
        type: String,
        select: false,
        validate: [required, 'A password is required'],
    },
    created: {
        type: Date,
        default: Date.now,
    },
    updated: {
        type: Date,
        default: Date.now,
    },
    lastlogin: {
        type: Date,
    },
}, {
    strict: false,
    toObject: {
        virtuals: true,
    },
    toJSON: {
        virtuals: true,
    },
} );

userSchema.pre( 'save', function preSave( next ) {
    if ( this.isNew && this.get( 'passwd' ) ) {
        const hash = createPasswordHash( this.get( 'passwd' ) );
        this.set( { passwd: hash, } );
    } else {
        this.set( { updated: Date.now(), } );
    }
    next();
} );

userSchema.methods.checkhash = function ( hash ) { return passwordhash.checkPassword( hash, this.get( 'passwd' ) ); };

userSchema.statics.findAndUpdate = function ( criteria, doc ) {
    this.findOne( criteria ).exec()
        .then( ( user ) => {
            if ( user === null ) {
                const error = new Error( 'User not found' );
                return error;
            }
            return user.set( doc ).save( ( err, updUser ) => {
                if ( err !== null ) {
                    return err;
                }
                return updUser;
            } );
        } )
        .catch( ( err ) => {
            throw err;
        } );
};

userSchema.statics.createFromOAuth = function ( doc ) {
    return this.create( doc )
        .then( createdUser => createdUser )
        .catch( ( err ) => {
            throw err;
        } );
};

module.exports = {
    Model: mongoose.model( 'User', userSchema, collection ),
    schema: userSchema,
};