瀏覽代碼

1.修改用户schema
2.新增登录信息记录
3.修复分页bug

caiaolin 8 年之前
父節點
當前提交
1d0cc962e4

+ 657 - 0
lib/bootstrap/bootstrap-paginator.js

@@ -0,0 +1,657 @@
+/**
+ * bootstrap-paginator.js v0.5
+ * --
+ * Copyright 2013 Yun Lai <lyonlai1984@gmail.com>
+ * --
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+(function ($) {
+
+    "use strict"; // jshint ;_;
+
+
+    /* Paginator PUBLIC CLASS DEFINITION
+     * ================================= */
+
+    /**
+     * Boostrap Paginator Constructor
+     *
+     * @param element element of the paginator
+     * @param options the options to config the paginator
+     *
+     * */
+    var BootstrapPaginator = function (element, options) {
+        this.init(element, options);
+    },
+        old = null;
+
+    BootstrapPaginator.prototype = {
+
+        /**
+         * Initialization function of the paginator, accepting an element and the options as parameters
+         *
+         * @param element element of the paginator
+         * @param options the options to config the paginator
+         *
+         * */
+        init: function (element, options) {
+
+            this.$element = $(element);
+
+            var version = (options && options.bootstrapMajorVersion) ? options.bootstrapMajorVersion : $.fn.bootstrapPaginator.defaults.bootstrapMajorVersion,
+                id = this.$element.attr("id");
+
+            if (version === 2 && !this.$element.is("div")) {
+
+                throw "in Bootstrap version 2 the pagination must be a div element. Or if you are using Bootstrap pagination 3. Please specify it in bootstrapMajorVersion in the option";
+            } else if (version > 2 && !this.$element.is("ul")) {
+                throw "in Bootstrap version 3 the pagination root item must be an ul element."
+            }
+
+
+
+            this.currentPage = 1;
+
+            this.lastPage = 1;
+
+            this.setOptions(options);
+
+            this.initialized = true;
+        },
+
+        /**
+         * Update the properties of the paginator element
+         *
+         * @param options options to config the paginator
+         * */
+        setOptions: function (options) {
+
+            this.options = $.extend({}, (this.options || $.fn.bootstrapPaginator.defaults), options);
+
+            this.totalPages = parseInt(this.options.totalPages, 10);  //setup the total pages property.
+            this.numberOfPages = parseInt(this.options.numberOfPages, 10); //setup the numberOfPages to be shown
+
+            //move the set current page after the setting of total pages. otherwise it will cause out of page exception.
+            if (options && typeof (options.currentPage)  !== 'undefined') {
+
+                this.setCurrentPage(options.currentPage);
+            }
+
+            this.listen();
+
+            //render the paginator
+            this.render();
+
+            if (!this.initialized && this.lastPage !== this.currentPage) {
+                this.$element.trigger("page-changed", [this.lastPage, this.currentPage]);
+            }
+
+        },
+
+        /**
+         * Sets up the events listeners. Currently the pageclicked and pagechanged events are linked if available.
+         *
+         * */
+        listen: function () {
+
+            this.$element.off("page-clicked");
+
+            this.$element.off("page-changed");// unload the events for the element
+
+            if (typeof (this.options.onPageClicked) === "function") {
+                this.$element.bind("page-clicked", this.options.onPageClicked);
+            }
+
+            if (typeof (this.options.onPageChanged) === "function") {
+                this.$element.on("page-changed", this.options.onPageChanged);
+            }
+
+            this.$element.bind("page-clicked", this.onPageClicked);
+        },
+
+
+        /**
+         *
+         *  Destroys the paginator element, it unload the event first, then empty the content inside.
+         *
+         * */
+        destroy: function () {
+
+            this.$element.off("page-clicked");
+
+            this.$element.off("page-changed");
+
+            this.$element.removeData('bootstrapPaginator');
+
+            this.$element.empty();
+
+        },
+
+        /**
+         * Shows the page
+         *
+         * */
+        show: function (page) {
+
+            this.setCurrentPage(page);
+
+            this.render();
+
+            if (this.lastPage !== this.currentPage) {
+                this.$element.trigger("page-changed", [this.lastPage, this.currentPage]);
+            }
+        },
+
+        /**
+         * Shows the next page
+         *
+         * */
+        showNext: function () {
+            var pages = this.getPages();
+
+            if (pages.next) {
+                this.show(pages.next);
+            }
+
+        },
+
+        /**
+         * Shows the previous page
+         *
+         * */
+        showPrevious: function () {
+            var pages = this.getPages();
+
+            if (pages.prev) {
+                this.show(pages.prev);
+            }
+
+        },
+
+        /**
+         * Shows the first page
+         *
+         * */
+        showFirst: function () {
+            var pages = this.getPages();
+
+            if (pages.first) {
+                this.show(pages.first);
+            }
+
+        },
+
+        /**
+         * Shows the last page
+         *
+         * */
+        showLast: function () {
+            var pages = this.getPages();
+
+            if (pages.last) {
+                this.show(pages.last);
+            }
+
+        },
+
+        /**
+         * Internal on page item click handler, when the page item is clicked, change the current page to the corresponding page and
+         * trigger the pageclick event for the listeners.
+         *
+         *
+         * */
+        onPageItemClicked: function (event) {
+
+            var type = event.data.type,
+                page = event.data.page;
+
+            this.$element.trigger("page-clicked", [event, type, page]);
+
+        },
+
+        onPageClicked: function (event, originalEvent, type, page) {
+
+            //show the corresponding page and retrieve the newly built item related to the page clicked before for the event return
+
+            var currentTarget = $(event.currentTarget);
+
+            switch (type) {
+            case "first":
+                currentTarget.bootstrapPaginator("showFirst");
+                break;
+            case "prev":
+                currentTarget.bootstrapPaginator("showPrevious");
+                break;
+            case "next":
+                currentTarget.bootstrapPaginator("showNext");
+                break;
+            case "last":
+                currentTarget.bootstrapPaginator("showLast");
+                break;
+            case "page":
+                currentTarget.bootstrapPaginator("show", page);
+                break;
+            }
+
+        },
+
+        /**
+         * Renders the paginator according to the internal properties and the settings.
+         *
+         *
+         * */
+        render: function () {
+
+            //fetch the container class and add them to the container
+            var containerClass = this.getValueFromOption(this.options.containerClass, this.$element),
+                size = this.options.size || "normal",
+                alignment = this.options.alignment || "left",
+                pages = this.getPages(),
+                listContainer = this.options.bootstrapMajorVersion === 2 ? $("<ul></ul>") : this.$element,
+                listContainerClass = this.options.bootstrapMajorVersion === 2 ? this.getValueFromOption(this.options.listContainerClass, listContainer) : null,
+                first = null,
+                prev = null,
+                next = null,
+                last = null,
+                p = null,
+                i = 0;
+
+
+            this.$element.prop("class", "");
+
+            this.$element.addClass("pagination");
+
+            switch (size.toLowerCase()) {
+            case "large":
+            case "small":
+            case "mini":
+                this.$element.addClass($.fn.bootstrapPaginator.sizeArray[this.options.bootstrapMajorVersion][size.toLowerCase()]);
+                break;
+            default:
+                break;
+            }
+
+            if (this.options.bootstrapMajorVersion === 2) {
+                switch (alignment.toLowerCase()) {
+                case "center":
+                    this.$element.addClass("pagination-centered");
+                    break;
+                case "right":
+                    this.$element.addClass("pagination-right");
+                    break;
+                default:
+                    break;
+                }
+            }
+
+
+            this.$element.addClass(containerClass);
+
+            //empty the outter most container then add the listContainer inside.
+            this.$element.empty();
+
+            if (this.options.bootstrapMajorVersion === 2) {
+                this.$element.append(listContainer);
+
+                listContainer.addClass(listContainerClass);
+            }
+
+            //update the page element reference
+            this.pageRef = [];
+
+            if (pages.first) {//if the there is first page element
+                first = this.buildPageItem("first", pages.first);
+
+                if (first) {
+                    listContainer.append(first);
+                }
+
+            }
+
+            if (pages.prev) {//if the there is previous page element
+
+                prev = this.buildPageItem("prev", pages.prev);
+
+                if (prev) {
+                    listContainer.append(prev);
+                }
+
+            }
+
+
+            for (i = 0; i < pages.length; i = i + 1) {//fill the numeric pages.
+
+                p = this.buildPageItem("page", pages[i]);
+
+                if (p) {
+                    listContainer.append(p);
+                }
+            }
+
+            if (pages.next) {//if there is next page
+
+                next = this.buildPageItem("next", pages.next);
+
+                if (next) {
+                    listContainer.append(next);
+                }
+            }
+
+            if (pages.last) {//if there is last page
+
+                last = this.buildPageItem("last", pages.last);
+
+                if (last) {
+                    listContainer.append(last);
+                }
+            }
+        },
+
+        /**
+         *
+         * Creates a page item base on the type and page number given.
+         *
+         * @param page page number
+         * @param type type of the page, whether it is the first, prev, page, next, last
+         *
+         * @return Object the constructed page element
+         * */
+        buildPageItem: function (type, page) {
+
+            var itemContainer = $("<li></li>"),//creates the item container
+                itemContent = $("<a></a>"),//creates the item content
+                text = "",
+                title = "",
+                itemContainerClass = this.options.itemContainerClass(type, page, this.currentPage),
+                itemContentClass = this.getValueFromOption(this.options.itemContentClass, type, page, this.currentPage),
+                tooltipOpts = null;
+
+
+            switch (type) {
+
+            case "first":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            case "last":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            case "prev":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            case "next":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            case "page":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            }
+
+            itemContainer.addClass(itemContainerClass).append(itemContent);
+
+            itemContent.addClass(itemContentClass).html(text).on("click", null, {type: type, page: page}, $.proxy(this.onPageItemClicked, this));
+
+            if (this.options.pageUrl) {
+                itemContent.attr("href", this.getValueFromOption(this.options.pageUrl, type, page, this.currentPage));
+            }
+
+            if (this.options.useBootstrapTooltip) {
+                tooltipOpts = $.extend({}, this.options.bootstrapTooltipOptions, {title: title});
+
+                itemContent.tooltip(tooltipOpts);
+            } else {
+                itemContent.attr("title", title);
+            }
+
+            return itemContainer;
+
+        },
+
+        setCurrentPage: function (page) {
+            if (page > this.totalPages || page < 1) {// if the current page is out of range, throw exception.
+
+                throw "Page out of range";
+
+            }
+
+            this.lastPage = this.currentPage;
+
+            this.currentPage = parseInt(page, 10);
+
+        },
+
+        /**
+         * Gets an array that represents the current status of the page object. Numeric pages can be access via array mode. length attributes describes how many numeric pages are there. First, previous, next and last page can be accessed via attributes first, prev, next and last. Current attribute marks the current page within the pages.
+         *
+         * @return object output objects that has first, prev, next, last and also the number of pages in between.
+         * */
+        getPages: function () {
+
+            var totalPages = this.totalPages,// get or calculate the total pages via the total records
+                pageStart = (this.currentPage % this.numberOfPages === 0) ? (parseInt(this.currentPage / this.numberOfPages, 10) - 1) * this.numberOfPages + 1 : parseInt(this.currentPage / this.numberOfPages, 10) * this.numberOfPages + 1,//calculates the start page.
+                output = [],
+                i = 0,
+                counter = 0;
+
+            pageStart = pageStart < 1 ? 1 : pageStart;//check the range of the page start to see if its less than 1.
+
+            for (i = pageStart, counter = 0; counter < this.numberOfPages && i <= totalPages; i = i + 1, counter = counter + 1) {//fill the pages
+                output.push(i);
+            }
+
+            output.first = 1;//add the first when the current page leaves the 1st page.
+
+            if (this.currentPage > 1) {// add the previous when the current page leaves the 1st page
+                output.prev = this.currentPage - 1;
+            } else {
+                output.prev = 1;
+            }
+
+            if (this.currentPage < totalPages) {// add the next page when the current page doesn't reach the last page
+                output.next = this.currentPage + 1;
+            } else {
+                output.next = totalPages;
+            }
+
+            output.last = totalPages;// add the last page when the current page doesn't reach the last page
+
+            output.current = this.currentPage;//mark the current page.
+
+            output.total = totalPages;
+
+            output.numberOfPages = this.options.numberOfPages;
+
+            return output;
+
+        },
+
+        /**
+         * Gets the value from the options, this is made to handle the situation where value is the return value of a function.
+         *
+         * @return mixed value that depends on the type of parameters, if the given parameter is a function, then the evaluated result is returned. Otherwise the parameter itself will get returned.
+         * */
+        getValueFromOption: function (value) {
+
+            var output = null,
+                args = Array.prototype.slice.call(arguments, 1);
+
+            if (typeof value === 'function') {
+                output = value.apply(this, args);
+            } else {
+                output = value;
+            }
+
+            return output;
+
+        }
+
+    };
+
+
+    /* TYPEAHEAD PLUGIN DEFINITION
+     * =========================== */
+
+    old = $.fn.bootstrapPaginator;
+
+    $.fn.bootstrapPaginator = function (option) {
+
+        var args = arguments,
+            result = null;
+
+        $(this).each(function (index, item) {
+            var $this = $(item),
+                data = $this.data('bootstrapPaginator'),
+                options = (typeof option !== 'object') ? null : option;
+
+            if (!data) {
+                data = new BootstrapPaginator(this, options);
+
+                $this = $(data.$element);
+
+                $this.data('bootstrapPaginator', data);
+
+                return;
+            }
+
+            if (typeof option === 'string') {
+
+                if (data[option]) {
+                    result = data[option].apply(data, Array.prototype.slice.call(args, 1));
+                } else {
+                    throw "Method " + option + " does not exist";
+                }
+
+            } else {
+                result = data.setOptions(option);
+            }
+        });
+
+        return result;
+
+    };
+
+    $.fn.bootstrapPaginator.sizeArray = {
+
+        "2": {
+            "large": "pagination-large",
+            "small": "pagination-small",
+            "mini": "pagination-mini"
+        },
+        "3": {
+            "large": "pagination-lg",
+            "small": "pagination-sm",
+            "mini": ""
+        }
+
+    };
+
+    $.fn.bootstrapPaginator.defaults = {
+        containerClass: "",
+        size: "normal",
+        alignment: "left",
+        bootstrapMajorVersion: 2,
+        listContainerClass: "",
+        itemContainerClass: function (type, page, current) {
+            return (page === current) ? "active" : "";
+        },
+        itemContentClass: function (type, page, current) {
+            return "";
+        },
+        currentPage: 1,
+        numberOfPages: 5,
+        totalPages: 1,
+        pageUrl: function (type, page, current) {
+            return null;
+        },
+        onPageClicked: null,
+        onPageChanged: null,
+        useBootstrapTooltip: false,
+        shouldShowPage: function (type, page, current) {
+
+            var result = true;
+
+            switch (type) {
+            case "first":
+                result = (current !== 1);
+                break;
+            case "prev":
+                result = (current !== 1);
+                break;
+            case "next":
+                result = (current !== this.totalPages);
+                break;
+            case "last":
+                result = (current !== this.totalPages);
+                break;
+            case "page":
+                result = true;
+                break;
+            }
+
+            return result;
+
+        },
+        itemTexts: function (type, page, current) {
+            switch (type) {
+            case "first":
+                return "&lt;&lt;";
+            case "prev":
+                return "&lt;";
+            case "next":
+                return "&gt;";
+            case "last":
+                return "&gt;&gt;";
+            case "page":
+                return page;
+            }
+        },
+        tooltipTitles: function (type, page, current) {
+
+            switch (type) {
+            case "first":
+                return "Go to first page";
+            case "prev":
+                return "Go to previous page";
+            case "next":
+                return "Go to next page";
+            case "last":
+                return "Go to last page";
+            case "page":
+                return (page === current) ? "Current page is " + page : "Go to page " + page;
+            }
+        },
+        bootstrapTooltipOptions: {
+            animation: true,
+            html: true,
+            placement: 'top',
+            selector: false,
+            title: "",
+            container: false
+        }
+    };
+
+    $.fn.bootstrapPaginator.Constructor = BootstrapPaginator;
+
+
+
+}(window.jQuery));

+ 9 - 2
modules/common/base/base_controller.js

@@ -5,6 +5,9 @@
  * @date 2017/6/29
  * @version
  */
+import Moment from "moment";
+import Url from "url";
+
 class BaseController {
 
     /**
@@ -34,8 +37,12 @@ class BaseController {
      * @return {void}
      */
     init(request, response, next) {
-        // 页面标题
-        response.locals.title = 'test';
+        // moment工具
+        response.locals.moment = Moment;
+
+        // url相关数据
+        let urlInfo = Url.parse(request.originalUrl, true);
+        response.locals.urlQuery = JSON.stringify(urlInfo.query);
 
         next();
     }

+ 14 - 0
modules/common/const/log_type_const.js

@@ -0,0 +1,14 @@
+/**
+ * 日志类型常量
+ *
+ * @author CaiAoLin
+ * @date 2017/7/27
+ * @version
+ */
+
+const logType = {
+    // 登录日志
+    LOGIN_LOG: 1
+};
+
+export default logType;

+ 7 - 1
modules/common/helper/mongoose_helper.js

@@ -51,6 +51,12 @@ class MongooseHelper {
      */
     find(conditions, fields = null, option = null) {
         let self = this;
+        let limit = 0;
+        let skip = 0;
+        if (Object.keys(option).length > 0) {
+            limit = option.pageSize !== undefined ? option.pageSize : limit;
+            skip = option.offset !== undefined ? option.offset : skip;
+        }
         return new Promise(function (resolve, reject) {
             self.model.find(conditions, fields, option, function (error, data) {
                 if (error) {
@@ -58,7 +64,7 @@ class MongooseHelper {
                 } else {
                     resolve(data);
                 }
-            });
+            }).skip(skip).limit(limit);
         });
     }
 

+ 3 - 2
modules/users/controllers/login_controller.js

@@ -55,11 +55,11 @@ class LoginController {
                 ssoId: userData.id,
                 username: userData.username,
                 email: userData.useremail,
-                mobile: userData.mobile
+                mobile: userData.mobile,
             };
             request.session.sessionUser = sessionUser;
             // 记录用户数据到数据库
-            let [result, exist] = await userModel.markUser(sessionUser);
+            let [result, exist] = await userModel.markUser(sessionUser, request);
             userExist = exist;
 
             if (!result) {
@@ -67,6 +67,7 @@ class LoginController {
             }
 
         } catch (error) {
+            console.log(error);
             return response.json({error: 1, msg: error});
         }
 

+ 31 - 5
modules/users/controllers/user_controller.js

@@ -7,6 +7,8 @@
  */
 import UserModel from "../models/user_model";
 import BaseController from "../../common/base/base_controller";
+import LogType from "../../common/const/log_type_const";
+import LogModel from "../models/log_model";
 
 class UserController extends BaseController {
 
@@ -75,14 +77,38 @@ class UserController extends BaseController {
      * @return {void}
      */
     async safe(request, response) {
-        // 获取当前用户信息
-        let sessionUser = request.session.sessionUser;
-        let userModel = new UserModel();
-        let userData = await userModel.findDataByName(sessionUser.username);
-        userData = userData.length <= 0 ? [] : userData[0];
+        let userData = [];
+        let logList = [];
+        let pageData = {};
+        try {
+            // 获取当前用户信息
+            let sessionUser = request.session.sessionUser;
+            let userModel = new UserModel();
+            userData = await userModel.findDataByName(sessionUser.username);
+            userData = userData.length <= 0 ? [] : userData[0];
+
+            let page = request.query.page === undefined ? 1 : request.query.page;
+
+            // 获取登录信息
+            let logModel = new LogModel();
+            let logCount = await logModel.count();
+            let pageSize = 3;
+            logList = await logModel.getLog(sessionUser.id, LogType.LOGIN_LOG, page, pageSize);
+
+            // 分页数据
+            pageData = {
+                current: page,
+                total: parseInt(logCount / pageSize),
+                queryData: response.locals.urlQuery
+            };
+        } catch (error) {
+            console.log(error);
+        }
 
         let renderData = {
             userData: userData,
+            logList: logList,
+            pages: pageData
         };
         response.render('users/html/user-safe', renderData);
     }

+ 104 - 0
modules/users/models/log_model.js

@@ -0,0 +1,104 @@
+/**
+ * 日志业务逻辑模型
+ *
+ * @author CaiAoLin
+ * @date 2017/7/27
+ * @version
+ */
+import BaseModel from "../../common/base/base_model";
+import LogType from "../../common/const/log_type_const";
+import LogSchema from "./schema/log";
+import UAParser from "ua-parser-js";
+
+class LogModel extends BaseModel {
+
+    /**
+     * 构造函数
+     *
+     * @return {void}
+     */
+    constructor() {
+        let parent = super();
+        parent.model = LogSchema;
+        parent.init();
+    }
+
+    /**
+     * 新增日志
+     *
+     * @param {String} userId
+     * @param {Number} type
+     * @param {String|Object} message
+     * @return {Promise}
+     */
+    addLog(userId, type, message) {
+        let result = null;
+        if (typeof message === 'string' && message === '') {
+            return result;
+        }
+        if (typeof message === 'object' && Object.keys(message).length <= 0) {
+            return result;
+        }
+
+        let addData = {
+            user_id: userId,
+            type: type,
+            message: message,
+            create_time: new Date().getTime()
+        };
+        result = this.db.create(addData);
+        return result;
+    }
+
+    /**
+     * 新增登录日志
+     *
+     * @param {String} userId
+     * @param {Object} request
+     * @return {Promise}
+     */
+    addLoginLog(userId, request) {
+        let ip = request.connection.remoteAddress;
+        ip = ip.split(':');
+        ip = ip[3] === undefined ? '' : ip[3];
+
+        let userAgentObject = new UAParser(request.headers['user-agent']);
+        let osInfo = userAgentObject.getOS();
+        let cpuInfo = userAgentObject.getCPU();
+        let browserInfo = userAgentObject.getBrowser();
+        let message = {
+            os: osInfo.name + ' ' + osInfo.version + ' ' + cpuInfo.architecture,
+            browser: browserInfo.name + ' ' + browserInfo.version,
+            ip: ip
+        };
+
+        return this.addLog(userId, LogType.LOGIN_LOG, message);
+    }
+
+    /**
+     * 获取log列表
+     *
+     * @param {String} userId
+     * @param {Number} type
+     * @param {Number} page
+     * @param {Number} pageSize
+     * @return {Promise}
+     */
+    async getLog(userId, type, page = 1, pageSize = 3) {
+        let condition = {
+            user_id: userId,
+            type: type
+        };
+        page = parseInt(page);
+        page = page <= 1 ? 1 : page;
+        let option = {pageSize: pageSize, offset: parseInt((page - 1) * pageSize)};
+
+        let logList = await this.db.find(condition, null, option);
+        logList = logList.length > 0 ? logList : [];
+
+        return logList
+    }
+
+}
+
+export default LogModel;

+ 29 - 0
modules/users/models/schema/log.js

@@ -0,0 +1,29 @@
+/**
+ * 日志数据结构
+ *
+ * @author CaiAoLin
+ * @date 2017/7/27
+ * @version
+ */
+import mongoose from "mongoose";
+
+let Schema = mongoose.Schema;
+let collectionName = 'log';
+let modelSchema = {
+    // 日志类型
+    type: {
+        type: Number,
+        index: true
+    },
+    // 日志内容
+    message: Schema.Types.Mixed,
+    // 关联用户id
+    user_id: {
+        type: String,
+        index: true
+    },
+    // 创建时间
+    create_time: Number
+};
+let model = mongoose.model(collectionName, new Schema(modelSchema, {versionKey: false, collection: collectionName}));
+export {model as default, collectionName as collectionName};

+ 24 - 7
modules/users/models/schema/user.js

@@ -16,13 +16,30 @@ let schema = {
     username: String,
     email: String,
     mobile: String,
-    real_name: String,
-    company: String,
-    province: String,
-    area: Number,
-    company_type: Number,
-    company_scale: Number,
-    last_login: Number,
+    real_name: {
+        type: String,
+        default: ''
+    },
+    company: {
+        type: String,
+        default: ''
+    },
+    province: {
+        type: Number,
+        default: -1
+    },
+    area: {
+        type: Number,
+        default: 0
+    },
+    company_type: {
+        type: Number,
+        default: -1,
+    },
+    company_scale: {
+        type: Number,
+        default: -1
+    },
     create_time: Number
 };
 

+ 8 - 16
modules/users/models/user_model.js

@@ -8,6 +8,7 @@
 import userSchema from "./schema/user";
 import Request from "request";
 import BaseModel from "../../common/base/base_model"
+import LogModel from "./log_model";
 
 class UserModel extends BaseModel {
 
@@ -79,9 +80,10 @@ class UserModel extends BaseModel {
      * 标记用户
      *
      * @param {object} userData
+     * @param {Object} request
      * @return {Promise}
      */
-    async markUser(userData) {
+    async markUser(userData, request = null) {
         let userDataFromDb = await this.findDataByName(userData.username);
         let result = false;
 
@@ -91,15 +93,12 @@ class UserModel extends BaseModel {
             // 不存在用户则入库
             result = await this.addUser(userData);
         } else {
-            // 存在则更新用户信息
-            let updateData = {last_login: new Date().getTime()};
-            let condition = {email: userData.email};
-            result = await this.updateUser(condition, updateData);
-
-            userDataFromDb = userDataFromDb[0];
-            info = userDataFromDb.real_name !== undefined && userDataFromDb.real_name !== '';
-            result = result.ok === 1;
+            info = true;
+            // 存在则新增登录信息
+            let logModel = new LogModel();
+            result = await logModel.addLoginLog(userDataFromDb._id, request);
         }
+        request.session.sessionUser.id = userDataFromDb._id;
 
         return [result, info];
     }
@@ -141,14 +140,7 @@ class UserModel extends BaseModel {
             username: userData.username,
             email: userData.email,
             mobile: userData.mobile,
-            real_name: '',
-            company: '',
-            province: -1,
-            company_type: -1,
-            company_scale: -1,
-            last_login: 0,
             create_time: new Date().getTime(),
-            area: 0
         };
         return this.db.create(insertData);
     }

+ 3 - 3
modules/users/routes/user_route.js

@@ -14,8 +14,8 @@ module.exports = function (app) {
     const userController = new UserController();
 
 // action定义区域
-    router.get('/info', userController.info);
-    router.get('/safe', userController.safe);
-    router.post('/info', userController.saveData);
+    router.get('/info', userController.init, userController.info);
+    router.get('/safe', userController.init, userController.safe);
+    router.post('/info', userController.init, userController.saveData);
     app.use('/user',router);
 };

+ 2 - 0
package.json

@@ -24,7 +24,9 @@
   "dependencies": {
     "bluebird": "^3.5.0",
     "jszip": "^3.1.3",
+    "moment": "^2.18.1",
     "socket.io": "^2.0.3",
+    "ua-parser-js": "^0.7.14",
     "uuid": "^3.1.0"
   },
   "scripts": {

+ 89 - 0
web/common/html/page.html

@@ -0,0 +1,89 @@
+<nav aria-label="...">
+    <ul aria-label="pagination" id="pages"></ul>
+</nav>
+<script type="text/javascript">
+    let options = {
+        bootstrapMajorVersion: 3,
+        currentPage: "<%= pages.current %>",
+        totalPages: "<%= pages.total %>",
+        size: "normal",
+        itemContainerClass: function(type, page, current) {
+            let className = 'page-item';
+            this.currentPage = parseInt(this.currentPage);
+            this.totalPages = parseInt(this.totalPages);
+
+            switch (type) {
+                case "prev":
+                    className = this.currentPage === 1 ? className + ' disabled' : className;
+                    break;
+                case "next":
+                    className = this.currentPage === this.totalPages ? className + ' disabled' : className;
+                    break;
+                case "page":
+                    className = page === this.currentPage ? className + ' active' : className;
+                    break;
+            }
+
+            return className;
+        },
+        itemContentClass: function(type, page, current) {
+            return 'page-link';
+        },
+        itemTexts: function(type, page, current) {
+            switch (type) {
+                case "first":
+                    return "&laquo;";
+                case "prev":
+                    return "上一页";
+                case "next":
+                    return "下一页";
+                case "last":
+                    return "最后一页";
+                case "page":
+                    return page;
+            }
+        },
+        shouldShowPage: function (type, page, current) {
+            let result = true;
+            switch (type) {
+                case "first":
+                    result = (current !== 1);
+                    break;
+                case "prev":
+                    break;
+                case "next":
+                    break;
+                case "last":
+                    result = false;
+                    break;
+                case "page":
+                    result = true;
+                    break;
+            }
+            return result;
+
+        },
+        pageUrl: function(type, page, current){
+            let queryData = JSON.parse('<%- pages.queryData %>');
+
+            // 如果没有附带查询条件则直接返回
+            if (Object.keys(queryData).length <= 0) {
+                return "?page=" + page;
+            }
+            // 有其它数据则重新赋值page,然后组合字符串
+            queryData.page = page;
+            let queryArray = [];
+            for(let tmp in queryData) {
+                let tempString = tmp + '=' + queryData[tmp];
+                queryArray.push(tempString);
+            }
+
+            let firstQuery = queryArray.shift();
+            let queryString = queryArray.join('&');
+            return  queryString === '' ? '?' + firstQuery : '?' + firstQuery + '&' + queryString;
+        }
+    };
+    if (options.totalPages > 0) {
+        $("#pages").bootstrapPaginator(options);
+    }
+</script>

+ 1 - 1
web/glj/html/header.html

@@ -6,7 +6,7 @@
     <link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css">
     <link rel="stylesheet" href="/web/building_saas/css/main.css">
     <link rel="stylesheet" href="/lib/font-awesome/font-awesome.min.css">
-    <link rel="stylesheet" href="/lib/spreadjs/sheets/css/gc.spread.sheets.excel2013white.10.0.1.css">
+    <link rel="stylesheet" href="/lib/spreadjs/sheets/css/gc.spread.sheets.excel2013lightGray.10.0.1.css">
     <script type="text/javascript" src="/public/web/sheet/sheet_common.js"></script>
     <script type="text/javascript" src="/public/web/sheet/sheet_data_helper.js"></script>
     <script src="/lib/spreadjs/sheets/gc.spread.sheets.all.10.0.1.min.js"></script>

+ 30 - 51
web/users/html/user-safe.html

@@ -9,6 +9,12 @@
     <link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css">
     <link rel="stylesheet" href="/web/building_saas/css/main.css">
     <link rel="stylesheet" href="/lib/font-awesome/font-awesome.min.css">
+    <!-- JS. -->
+    <script src="/lib/jquery/jquery.min.js"></script>
+    <script src="/lib/tether/tether.min.js"></script>
+    <script src="/lib/bootstrap/bootstrap.min.js"></script>
+    <script type="text/javascript" src="/lib/bootstrap/bootstrap-paginator.js"></script>
+    <script src="/web/building_saas/js/global.js"></script>
 </head>
 
 <body>
@@ -80,52 +86,30 @@
                         </div>
                     </from>
                 </div>
-                <!--<div class="mt-5">-->
-                    <!--<legend>访问日志</legend>-->
-                    <!--<table class="table table-hover">-->
-                        <!--<thead>-->
-                        <!--<tr>-->
-                            <!--<th>系统</th>-->
-                            <!--<th>浏览器</th>-->
-                            <!--<th>访问日期</th>-->
-                            <!--<th>地址</th>-->
-                        <!--</tr>-->
-                        <!--</thead>-->
-                        <!--<tbody>-->
-                        <!--<tr>-->
-                            <!--<td>Windows NT 10.0 64-bit</td>-->
-                            <!--<td>Chrome 55.0.2883.87 m (64-bit)</td>-->
-                            <!--<td>2017-01-12 09:09</td>-->
-                            <!--<td>广东省珠海市 电信(116.19.86.133)</td>-->
-                        <!--</tr>-->
-                        <!--<tr>-->
-                            <!--<td>Windows NT 10.0 64-bit</td>-->
-                            <!--<td>Chrome 55.0.2883.87 m (64-bit)</td>-->
-                            <!--<td>2017-01-12 09:09</td>-->
-                            <!--<td>广东省珠海市 电信(116.19.86.133)</td>-->
-                        <!--</tr>-->
-                        <!--<tr>-->
-                            <!--<td>Windows NT 10.0 64-bit</td>-->
-                            <!--<td>Chrome 55.0.2883.87 m (64-bit)</td>-->
-                            <!--<td>2017-01-12 09:09</td>-->
-                            <!--<td>广东省珠海市 电信(116.19.86.133)</td>-->
-                        <!--</tr>-->
-                        <!--</tbody>-->
-                    <!--</table>-->
-                    <!--<nav aria-label="...">-->
-                        <!--<ul class="pagination">-->
-                            <!--<li class="page-item disabled">-->
-                                <!--<a class="page-link" href="#" tabindex="-1">上一页</a>-->
-                            <!--</li>-->
-                            <!--<li class="page-item active"><a class="page-link" href="#">1</a></li>-->
-                            <!--<li class="page-item"><a class="page-link" href="#">2</a></li>-->
-                            <!--<li class="page-item"><a class="page-link" href="#">3</a></li>-->
-                            <!--<li class="page-item">-->
-                                <!--<a class="page-link" href="#">下一页</a>-->
-                            <!--</li>-->
-                        <!--</ul>-->
-                    <!--</nav>-->
-                <!--</div>-->
+                <div class="mt-5">
+                    <legend>访问日志</legend>
+                    <table class="table table-hover">
+                        <thead>
+                        <tr>
+                            <th>系统</th>
+                            <th>浏览器</th>
+                            <th>访问日期</th>
+                            <th>地址</th>
+                        </tr>
+                        </thead>
+                        <tbody>
+                        <% logList.forEach(function (log){ %>
+                        <tr>
+                            <td><%= log.message.os %></td>
+                            <td><%= log.message.browser %></td>
+                            <td><%= moment(log.create_time).format('YYYY-MM-DD HH:mm:ss') %></td>
+                            <td>(<%= log.message.ip %>)</td>
+                        </tr>
+                        <% }) %>
+                        </tbody>
+                    </table>
+                    <%include ../../common/html/page.html %>
+                </div>
             </div>
         </div>
     </div>
@@ -144,11 +128,6 @@
         </div>
     </div>
 </div>
-<!-- JS. -->
-<script src="/lib/jquery/jquery.min.js"></script>
-<script src="/lib/tether/tether.min.js"></script>
-<script src="/lib/bootstrap/bootstrap.min.js"></script>
-<script src="/web/building_saas/js/global.js"></script>
 </body>
 <script type="text/javascript">
     autoFlashHeight();