user_manager.py 5.48 KB
Newer Older
wanli's avatar
wanli committed
1 2 3 4 5 6 7 8 9
#!/usr/bin/env python
# -*- coding: utf_8 -*-

import logging
import copy
from datetime import datetime
from pony.orm import *
from model import fullStackDB
from model.user import User
wanli's avatar
wanli committed
10
from utils import md5_salt
wanli's avatar
wanli committed
11

wanli's avatar
wanli committed
12
logger = logging.getLogger(__name__)
wanli's avatar
wanli committed
13 14 15 16 17 18 19 20 21

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

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

wanli's avatar
wanli committed
22 23 24 25 26 27 28
    def check(self, data):
        with db_session:
            user = User.get(uuid=data.get("uuid"))
            if not user:
                return False
            return True

wanli's avatar
wanli committed
29
    def add(self, uuid, data):
wanli's avatar
wanli committed
30 31 32 33 34 35 36 37 38
        '''
        添加用户
        '''

        # 判断账号是否存在
        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"

wanliofficial's avatar
wanliofficial committed
39
        editor = User.get(id=uuid)
wanli's avatar
wanli committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
        if not editor:
            return False, "current user is not exists"

        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:
wanli's avatar
wanli committed
64
            editor = User.get(uuid=uuid)
wanli's avatar
wanli committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
            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:
            # 查询请求者是否存在
wanli's avatar
wanli committed
86
            editor = User.get(uuid=uuid)
wanli's avatar
wanli committed
87 88 89 90 91 92 93 94 95
            if not editor:
                return False, "current user is not exists"

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

            user = User.get(uuid=uuid)
            if user:
                user.set(update_at=datetime.now(), update_by=editor.id, **data)
wanli's avatar
wanli committed
96
                result = user.to_dict(only=["account", "gender", "birthday", "phone", "email",])
wanli's avatar
wanli committed
97 98 99 100 101 102
                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"

wanli's avatar
wanli committed
103
    def get(self, user):
wanli's avatar
wanli committed
104 105 106
        '''
        查询单用户
        '''
wanli's avatar
wanli committed
107

wanli's avatar
wanli committed
108
        result = User.get(id=user, is_delete=False)
wanli's avatar
wanli committed
109
        if result:
wanli's avatar
wanli committed
110
            temp = result.to_dict(with_collections=True, related_objects=True, only=["uuid", "username", "account", "role", "phone", "email", "gender", "create_at", "update_at"])
wanli's avatar
wanli committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
            temp.update({
                "create_at": result.create_at.strftime("%Y-%m-%d %H:%M:%S") if result.create_at 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."
        
        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')
wanli's avatar
wanli committed
133

wanli's avatar
wanli committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        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
150
                t = item.to_dict(with_collections=True, related_objects=True, only=["uuid", "username", "account", "phone", "email", "gender", "create_at", "update_at", "remarks"])
wanli's avatar
wanli committed
151 152 153 154 155 156 157 158 159 160 161
                t.update({
                    "email": "" if item.email == "user@example.com" else item.email,
                    "create_at": item.create_at.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()