user_manager.py 8.85 KB
Newer Older
wanli's avatar
wanli committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
#!/usr/bin/env python
# -*- coding: utf_8 -*-

import time
import json
import logging
import traceback
import copy
import uuid
from datetime import datetime
from pony.orm import *
from flask import request
from app.setting import config
from model import fullStackDB
from model.user import User
from utils import md5_salt, filter_dict, sql_filter

logger = logging.getLogger("UserManager")

class UserManager(object):
    '''
     用户管理的单例类
    '''

    def __init__(self):
        super(UserManager, self).__init__()

    def add(self, data):
        '''
        添加用户
        '''

        # 判断账号是否存在
        isExists = select(u for u in User if u.account == data['account'] and u.is_delete == False).exists()
        if isExists:
            return False, "user already exists"

        editor = User.get(id=request.current_user.get("id"))
        if not editor:
            return False, "current user is not exists"

        if "role" in data:
            role = Role.get(uuid=data.get("role"))
            if not role:
                return False, "role does not exists"
            data.update({ "role": role.id })

        if "depot" in data:
            # depot = Depot.select().where(uuid=data["depot"]).first()
            depot = Depot.get(uuid=data.get("depot"))

            if not depot:
                return False, "depot does not exists"
            data.update({ "depot": depot.id })

        if "username" not in data or not data.get("username"):
            data.update({ "username": data.get("account") })

        # 密码加密
        data['password'] = md5_salt(data['password'])
        data.update({
            "create_by": editor.id,
            "create_at": datetime.now(),
            "update_by": editor.id,
            "update_at": datetime.now()
        })

        # 添加用户时,是否考虑将该用户的过期时间加入预警
        result = fullStackDB.add(User, **data)
        return result, "add user {}.".format("success" if result else "fail")

    def delete(self, uuid):
        '''
        删除用户
        '''
        with db_session:
            editor = User.get(id=request.current_user.get("id"))
            if not editor:
                return False, "current user is not exists"

            result = User.get(uuid=uuid)
            if result:
                result.delete()
                commit()
                result = True

        return result, "delete user {}.".format("success" if result else "fail")

    def update(self, uuid, data):
        '''
        更新用户
        '''
        # 当参数为空时,直接返回错误
        if len(data) <= 0 or (len(data.keys()) == 1 and "id" in data):
            return False, "parameters can not be null."

        with db_session:
            # 查询请求者是否存在
            editor = User.get(id=request.current_user.get("id"))
            if not editor:
                return False, "current user is not exists"

            if "password" in data:
                data["password"] = md5_salt(data['password'])

            if "role" in data:
                role = Role.get(uuid=data.get("role"))
                if not role:
                    return False, "role does not exists"
                data.update({ "role": role.id })

            if "depot" in data:
                depot = Depot.get(uuid=data.get("depot"))
                if not depot:
                    return False, "depot does not exists"
                data.update({ "depot": depot.id })

            user = User.get(uuid=uuid)
            if user:
                user.set(update_at=datetime.now(), update_by=editor.id, **data)
wanli's avatar
wanli committed
121
                result = user.to_dict(only=["account", "gender", "birthday", "hometown", "phone", "email",])
wanli's avatar
wanli committed
122 123 124 125 126 127 128 129 130 131 132 133
                if result.get("birthday"):
                    result.update({ "birthday": result.get("birthday").strftime("%Y-%m-%d") })
                return result, "update user success"
            else:
                return None, "user does not exists"

    def get(self, data):
        '''
        查询单用户
        '''
        result = User.get(id=request.current_user.get("id"), is_delete=False)
        if result:
wanli's avatar
wanli committed
134
            temp = result.to_dict(with_collections=True, related_objects=True, only=["uuid", "username", "account", "phone", "email", "hometown", "gender", "birthday", "entry_time", "expire_date", "create_at", "update_at"])
wanli's avatar
wanli committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
            temp.update({
                "birthday": result.birthday.strftime("%Y-%m-%d") if result.birthday else None,
                "create_at": result.create_at.strftime("%Y-%m-%d %H:%M:%S") if result.create_at else None,
                "entry_time": result.entry_time.strftime("%Y-%m-%d %H:%M:%S") if result.entry_time else None,
                "expire_date": result.expire_date.strftime("%Y-%m-%d %H:%M:%S") if result.expire_date else None,
                "update_at": result.update_at.strftime("%Y-%m-%d %H:%M:%S") if result.update_at else None,
            })
            result = temp
        return result, "get user {}.".format("success" if result else "not found")

    def getList(self, data):
        '''
        查询多用户
        '''
        # 当参数为空时,直接返回错误
        if not data or len(data) <= 0:
            return False, 0, "parameters can not be null."

        # select_sql = "select `id`, `account`, `username` from `{}`".format(User._table_)
        # conditions = []
        # globals_dict = dict()

        # if "id" in data and data.get("id"):
        #     conditions.append(" id = $id")
        #     globals_dict.update({ "id": data.get("id") })

        # if "account" in data and data.get("account"):
        #     conditions.append("account = \"$account\"")
        #     globals_dict.update({ "account": sql_filter(data.get("account")) })

        # if "username" in data and data.get("username"):
        #     conditions.append("username = \"$username\"")
        #     globals_dict.update({ "username": sql_filter(data.get("username")) })

        # if len(conditions):
        #     select_sql = select_sql + " where " + " and ".join(conditions)
        #     conditions = []

        # select_sql = select_sql + " "

        # conditions.append("order by $order")
        # globals_dict.update({ "order": sql_filter(data.get("order", "create_at")) })

        # conditions.append("limit $limit")
        # globals_dict.update({ "limit": data.get("pagesize", 10) })

        # conditions.append("offset $offset")
        # globals_dict.update({ "offset": (data.get("pagenum", 1) - 1) * data.get("pagesize", 10) })

        # result = User.select_by_sql(select_sql + " ".join(conditions), globals=globals_dict)
        
        temp = copy.deepcopy(data)
        if 'pagenum' in temp:
            temp.pop('pagenum')
        if 'pagesize' in temp:
            temp.pop('pagesize')
        if 'scope_type' in temp:
            temp.pop('scope_type')
        if 'role' in temp:
            role = Role.get(uuid=temp.get('role'))
            if role:
                temp.update({ "role": role })
            else:
                temp.pop('pagenum')
        if 'depot' in temp:
            depot = Depot.get(uuid=temp.get('depot'))
            if depot:
                temp.update({ "depot": depot })
            else:
                temp.pop('pagenum')
        temp.setdefault("is_delete", False)

        if "scope_type" in data and data.get("scope_type") == "list":
            result = User.select().where(**temp).order_by(desc(User.create_at))
            temp = []
            for item in result:
                t = item.to_dict(only=["id", "uuid", "username", "account"])
                temp.append(t)
            return temp, len(temp), "get select {}.".format("success" if temp else "no data")

        result = User.select().where(**temp).order_by(desc(User.create_at)).page(data.get("pagenum", 1), data.get("pagesize", 10))
        count = User.select().where(**temp).count()

        if result and len(result):
            temp = []
            for item in result:
wanli's avatar
wanli committed
221
                t = item.to_dict(with_collections=True, related_objects=True, only=["uuid", "username", "account", "phone", "email", "hometown", "gender", "birthday", "entry_time", "expire_date", "create_at", "update_at", "remarks"])
wanli's avatar
wanli committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235
                t.update({
                    "email": "" if item.email == "user@example.com" else item.email,
                    "birthday": item.birthday.strftime("%Y-%m-%d") if item.birthday else None,
                    "create_at": item.create_at.strftime("%Y-%m-%d %H:%M:%S"),
                    "entry_time": item.entry_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "expire_date": item.expire_date.strftime("%Y-%m-%d %H:%M:%S"),
                    "update_at": item.update_at.strftime("%Y-%m-%d %H:%M:%S"),
                })
                temp.append(t)
            result = temp

        return result, count, "get users {}.".format("success" if result else "no data")

userManager = UserManager()