Przeglądaj źródła

用户表,token验证

zhangnaiwen 2 lat temu
rodzic
commit
7aba3a5f26

+ 2 - 0
src/app/configs/config.py

@@ -0,0 +1,2 @@
+JWT_SECRET = ''
+JWT_EXPIRY = 3600

+ 5 - 0
src/app/defines/__init__.py

@@ -3,3 +3,8 @@ class StatesCode:
     UNKNOWN_ERROR = -1  # 未知错误
     PARA_MISSING = -2  # 参数缺失
     PARA_ERROR = -3  # 参数错误
+
+
+class MessageType:
+    ordinary_message = 1  # 普通消息
+    alert_messages = 2  # 提醒消息

+ 7 - 6
src/app/helpers/request_handlers.py

@@ -1,6 +1,7 @@
-from flask import request, abort
+from flask import request
 
-# from app.services.redis_service import get_uid_from_token
+from app.defines import StatesCode
+from app.utils.jwt_util import verify_jwt
 
 
 def configure(app):
@@ -12,8 +13,8 @@ def configure(app):
         """
         token = request.headers.get('token')
         if token:
-            # if get_uid_from_token(token):
-                abort(200)
-
+            payload = verify_jwt(token)
+            if payload is None:
+                return {"code": StatesCode.SUCCESS, "message": "无效的token"}
         else:
-            abort(403)
+            return {"code": StatesCode.SUCCESS, "message": "无效的token"}

+ 3 - 0
src/app/modle/__init__.py

@@ -0,0 +1,3 @@
+from sqlalchemy.orm import DeclarativeBase
+class Base(DeclarativeBase):
+    pass

+ 34 - 0
src/app/modle/users.py

@@ -0,0 +1,34 @@
+from datetime import time
+
+from sqlalchemy import String, Column, Integer, DateTime
+
+from app.modle import Base
+
+
+def cnNow():
+    """获取时间,年月日时分秒格式"""
+    # tz = pytz.timezone('Asia/Shanghai')
+    # return tz.fromutc(datetime.datetime.now() + datetime.timedelta(0, time.altzone))
+    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
+
+
+class User(Base):
+    """用户表"""
+    __tablename__ = "users"
+
+    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False, doc='用户id')
+    user_name = Column(String, nullable=False, unique=False, index=False, doc='用户名')
+    password = Column(String, nullable=False, unique=False, index=False, doc='密码')
+    photograph = Column(String, nullable=True, unique=False, index=False, doc='照片')
+    name = Column(String, nullable=True, unique=False, index=False, doc='姓名')
+    phone = Column(Integer, nullable=True, unique=False, index=False, doc='电话')
+    email = Column(String, nullable=True, unique=False, index=False, doc='邮箱')
+    company = Column(String, nullable=True, unique=False, index=False, doc='公司')
+    department = Column(String, nullable=True, unique=False, index=False, doc='部门')
+    role = Column(String, nullable=True, unique=False, index=False, doc='角色')
+    permission = Column(String, nullable=True, unique=False, index=False, doc='权限')
+    on_job_status = Column(String, nullable=True, unique=False, index=False, doc='在职状态')
+    duty = Column(String, nullable=True, unique=False, index=False, doc='职务')
+    account_status = Column(String, nullable=True, unique=False, index=False, doc='账户状态')
+    nationality = Column(String, nullable=True, unique=False, index=False, doc='国籍')
+    register_time = Column(DateTime, nullable=True, unique=False, index=False, default=cnNow(), doc='注册时间')

+ 0 - 28
src/app/services/redis_service.py

@@ -1,28 +0,0 @@
-import redis
-
-from app.configs.config import REDIS_HOST, REDIS_PORT, REDIS_DB
-
-# Redis使用连接池
-redis_pool = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
-r = redis.Redis(connection_pool=redis_pool)
-
-# Redis的键,方便统一管理
-# rk前缀表示redis_key
-rk_oauth_get_uid_from_token = 'access_token:{token}'
-
-
-def save_oauth_token_uid(access_token, user_id, expired=3600):
-    # if not expired:
-    # expired = int(current_app.config.get('OAUTH2_PROVIDER_TOKEN_EXPIRES_IN', 3600))
-    k = rk_oauth_get_uid_from_token.format(token=access_token)
-    r.set(k, user_id, ex=expired)
-
-
-def del_oauth_token_uid(access_token):
-    k = rk_oauth_get_uid_from_token.format(token=access_token)
-    r.delete(k)
-
-
-def get_uid_from_token(access_token):
-    k = rk_oauth_get_uid_from_token.format(token=access_token)
-    return int(r.get(k))

+ 41 - 0
src/app/utils/jwt_util.py

@@ -0,0 +1,41 @@
+import time
+
+import jwt
+from jwt import ExpiredSignatureError
+
+from app.configs.config import JWT_SECRET, JWT_EXPIRY
+
+headers = {
+    "alg": "HS256",
+    "typ": "JWT"
+}
+
+
+def generate_jwt(user_id):
+    """
+    生成jwt
+    :param user_id: 用户id
+    :return: jwt
+    """
+    payload = {
+        'user_id': user_id,
+        'exp': int(time.time() + JWT_EXPIRY)
+    }
+
+    token = jwt.encode(payload, JWT_SECRET, algorithm='HS256', headers=headers)
+    return token
+
+
+def verify_jwt(token):
+    """
+    检验jwt
+    :param token: jwt
+    :return: dict: payload
+    """
+
+    try:
+        payload = jwt.decode(token, JWT_SECRET, algorithm=['HS256'], headers=headers)
+    except ExpiredSignatureError:
+        payload = None
+
+    return payload