예제 #1
0
    async def create_group(cls, szGroup, szDesc=""):
        dictGroup = await cls.get_group_by_name(szGroup)
        if dictGroup is not None:
            return dictGroup

        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor() as cur:
                        await cur.execute(
                            "INSERT INTO "
                            "  t_thinkauth_group(`name`, description) "
                            "VALUES "
                            "  (%s, %s)", (szGroup, szDesc))

                        await conn.commit()

                        dictRet = await cls.get_group_by_name(szGroup)
                        return dictRet
                except Exception as e:
                    g_logger.error(e)
                    return None
                finally:
                    conn.close()
        except Exception as e:
            g_logger.error(e)
            return None
예제 #2
0
    async def group_has_permission(cls, nGID, nPID):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor(aiomysql.cursors.DictCursor) as cur:
                        await cur.execute(
                            "SELECT                                                              "
                            "	1                                                                  "
                            "FROM                                                                "
                            "	t_thinkauth_group_permission AS a                                  "
                            "	LEFT JOIN t_thinkauth_group AS b ON a.group_id = b.id              "
                            "	LEFT JOIN t_thinkauth_permission AS c ON a.permission_id = c.id    "
                            "WHERE                                                               "
                            "	c.id = %s                                             "
                            "	AND b.id = %s                                                  ",
                            (nPID, nGID))

                        rows = await cur.fetchall()
                        if rows is None or len(rows) <= 0:
                            return False

                        return True
                except Exception as e:
                    g_logger.error(e)
                    return False
                finally:
                    conn.close()

        except Exception as e:
            g_logger.error(e)
            return False
예제 #3
0
    async def get_group_by_name(cls, szGroup):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor(aiomysql.cursors.DictCursor) as cur:
                        await cur.execute(
                            "SELECT "
                            "  * "
                            "FROM "
                            "  t_thinkauth_group "
                            "WHERE "
                            "  `name` = %s "
                            "  "
                            "LIMIT 1 ", (szGroup, ))

                        rows = await cur.fetchall()
                        if len(rows) <= 0:
                            return None

                        rows[0]["members"] = await cls.get_group_members(
                            rows[0]["id"])
                        return rows[0]
                except Exception as e:
                    g_logger.error(e)
                    return None
                finally:
                    conn.close()

        except Exception as e:
            g_logger.error(e)
            return None
    async def get_user_groups_by_username(cls, szUser):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor(aiomysql.cursors.DictCursor) as cur:
                        await cur.execute(
                            "SELECT                                                    "
                            "	 c.*                                                     "
                            "FROM                                                      "
                            "	 t_thinkauth_user_group AS a                             "
                            "	 left join t_thinkauth_user as b on a.user_id = b.id     "
                            "	 left join t_thinkauth_group as c on a.group_id = c.id   "
                            "where                                                     "
                            "	 b.username = %s                                         ",
                            (szUser, ))

                        rows = await cur.fetchall()
                        if len(rows) <= 0:
                            return []

                        return rows
                except Exception as e:
                    g_logger.error(e)
                    return []
                finally:
                    conn.close()

        except Exception as e:
            g_logger.error(e)
            return []
    async def check_token(cls, nUID, szToken):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor(aiomysql.cursors.DictCursor) as cur:
                        await cur.execute(
                            "SELECT "
                            "  1 "
                            "FROM "
                            "  t_thinkauth_user_token "
                            "WHERE "
                            "  user_id = %s "
                            "  AND token = %s "
                            "  AND date_expire >= %s"
                            "LIMIT 1 ",
                            (nUID, szToken, get_current_time_str()))

                        rows = await cur.fetchall()
                        if len(rows) <= 0:
                            return False

                        return True
                except Exception as e:
                    g_logger.error(e)
                    return False
                finally:
                    conn.close()

        except Exception as e:
            g_logger.error(e)
            return False
    async def change_password(cls, nUID, szPwd):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor() as cur:
                        await cur.execute(
                            "UPDATE "
                            "  t_thinkauth_user "
                            "SET "
                            "  password = %s "
                            "WHERE "
                            "  id = %s", (szPwd, nUID))

                        await conn.commit()

                        dictUser = await cls.get_user(nUID)
                        return dictUser
                except Exception as e:
                    g_logger.error(e)
                    return None
                finally:
                    conn.close()
        except Exception as e:
            g_logger.error(e)
            return None
    async def login(cls, szUserName, szPwd, nExpireDays=180):
        dictUser = await cls.get_user_by_username_password(szUserName, szPwd)
        if dictUser is None:
            return (-1, szUserName, None)

        # make token and insert
        szToken = str(uuid.uuid4()).replace("-", "")
        szExpire = "{} 23:59:59".format(diff_day(nExpireDays))

        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor() as cur:
                        await cur.execute(
                            "INSERT INTO "
                            "  t_thinkauth_user_token(user_id, token, date_expire) "
                            "VALUES "
                            "  (%s, %s, %s)",
                            (dictUser["id"], szToken, szExpire))

                        await conn.commit()
                        return (dictUser["id"], szUserName, szToken)
                except Exception as e:
                    g_logger.error(e)
                    return (-1, szUserName, None)
                finally:
                    conn.close()
        except Exception as e:
            g_logger.error(e)
            return (-1, szUserName, None)
예제 #8
0
    async def select_permission(cls, szName):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor(aiomysql.cursors.DictCursor) as cur:
                        await cur.execute(
                            "SELECT "
                            "  * "
                            "FROM "
                            "  t_thinkauth_permission "
                            "WHERE "
                            "  `permission_name` = %s "
                            "   "
                            "LIMIT 1 ", (szName, ))

                        rows = await cur.fetchall()
                        if rows is None or len(rows) <= 0:
                            return None

                        return rows[0]
                except Exception as e:
                    g_logger.error(e)
                    return None
                finally:
                    conn.close()

        except Exception as e:
            g_logger.error(e)
            return None
    async def create_user(cls, szUserName, szPwd, nSuperUser=0, nActive=1):
        dictUser = await cls.get_user_by_username(szUserName)
        if dictUser is not None:
            return None

        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor() as cur:
                        await cur.execute(
                            "INSERT INTO "
                            "  t_thinkauth_user(username, password, is_superuser, is_active) "
                            "VALUES "
                            "  (%s, %s, %s, %s)",
                            (szUserName, szPwd, nSuperUser, nActive))

                        await conn.commit()

                        dictUser = await cls.get_user_by_username(szUserName)
                        return dictUser
                except Exception as e:
                    g_logger.error(e)
                    return None
                finally:
                    conn.close()
        except Exception as e:
            g_logger.error(e)
            return None
    async def get_user_by_username_password(cls, szUserName, szPwd):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor(aiomysql.cursors.DictCursor) as cur:
                        await cur.execute(
                            "SELECT "
                            "  * "
                            "FROM "
                            "  t_thinkauth_user "
                            "WHERE "
                            "  username = %s "
                            "  AND password = %s "
                            "LIMIT 1 ", (szUserName, szPwd))

                        rows = await cur.fetchall()
                        if len(rows) <= 0:
                            return None

                        return rows[0]
                except Exception as e:
                    g_logger.error(e)
                    return None
                finally:
                    conn.close()

        except Exception as e:
            g_logger.error(e)
            return None
예제 #11
0
    async def grant_permission_to_group(cls, nPID, nGID):

        bHasPermission = await cls.group_has_permission(nGID, nPID)
        if bHasPermission:
            return True

        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor() as cur:
                        await cur.execute(
                            "INSERT INTO "
                            "  t_thinkauth_group_permission(group_id, permission_id) "
                            "VALUES "
                            "  (%s, %s)", (nGID, nPID))

                        await conn.commit()

                        return True
                except Exception as e:
                    g_logger.error(e)
                    return False
                finally:
                    conn.close()
        except Exception as e:
            g_logger.error(e)
            return False
예제 #12
0
    async def create_permission(cls, szName, szDescription=""):
        dictPermission = await cls.select_permission(szName)
        if dictPermission is not None:
            return dictPermission

        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor() as cur:
                        await cur.execute(
                            "INSERT INTO "
                            "  t_thinkauth_permission(`permission_name`, description) "
                            "VALUES "
                            "  (%s, %s)", (szName, szDescription))

                        await conn.commit()

                        dictRet = await cls.select_permission(szName)
                        return dictRet
                except Exception as e:
                    g_logger.error(e)
                    return None
                finally:
                    conn.close()
        except Exception as e:
            g_logger.error(e)
            return None
예제 #13
0
    async def get_group_members_by_name(cls, szGroup):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor(aiomysql.cursors.DictCursor) as cur:
                        await cur.execute(
                            "SELECT                                                   "
                            "	 c.*                                                    "
                            "FROM                                                     "
                            "	 t_thinkauth_user_group as a                            "
                            "	 left JOIN t_thinkauth_group as b on a.group_id = b.id  "
                            "	 LEFT JOIN t_thinkauth_user as c on a.user_id = c.id    "
                            "WHERE                                                    "
                            "	 b.`name` = %s                                          "
                            " ", (szGroup, ))

                        rows = await cur.fetchall()
                        if len(rows) <= 0:
                            return []

                        return rows
                except Exception as e:
                    g_logger.error(e)
                    return []
                finally:
                    conn.close()

        except Exception as e:
            g_logger.error(e)
            return []
예제 #14
0
def create_table_group():
    conn = ThinkMysql.get_conn_pool().connection()
    try:
        cur = conn.cursor(pymysql.cursors.DictCursor)
        szSql = '''
        DROP TABLE IF EXISTS t_thinkauth_group;
        
        CREATE TABLE t_thinkauth_group (
            `id` bigint(0) UNSIGNED NOT NULL AUTO_INCREMENT
            , `name` varchar(256) NOT NULL 
            , PRIMARY KEY (`id`)
            , `date_added` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
            , `description` varchar(256) 
        );
            
        alter table t_thinkauth_group AUTO_INCREMENT=10000001;
        ALTER TABLE `db_thinkutils`.`t_thinkauth_group` ADD INDEX `IX_group_name`(`name`) USING BTREE;
        
        insert into t_thinkauth_group(name) VALUES ('admin');
        insert into t_thinkauth_group(name) VALUES ('guest');
        '''

        for statement in szSql.split(';'):
            if len(statement.strip()) > 0:
                cur.execute(statement + ';')

        conn.commit()

    except Exception as e:
        g_logger.error(e)
    finally:
        conn.close()
예제 #15
0
 def run(self):
     while True:
         time.sleep(3)
         try:
             self.on_start()
         except Exception as e:
             g_logger.error(e)
             pass
예제 #16
0
    def expire_time(cls, szToken):
        try:
            dictToken = cls.parse_token(szToken)
            if dictToken is None:
                return 0

            r = redis.StrictRedis(
                connection_pool=ThinkRedis.get_conn_pool_ex())

            szKey = "login_tokens:{}".format(dictToken["login_user_key"])
            return r.ttl(szKey)

        except Exception as ex:
            g_logger.error(ex)
            return 0
예제 #17
0
    def get_info(cls, szToken):
        try:
            szUrl = "{}{}".format(TokenUtils.g_szHost, "/ruoyi-api/getInfo")
            dictHeader = {"Authorization": "Bearer {}".format(szToken)}

            resp = requests.get(szUrl, headers=dictHeader)
            if 200 != resp.status_code:
                return None

            dictRet = json.loads(resp.text)
            if 200 != dictRet["code"]:
                return None

            return dictRet
        except Exception as ex:
            g_logger.error(ex)
            return None
예제 #18
0
    def parse_token(cls, szToken):
        try:
            jwt_options = {
                'verify_signature': False,
                'verify_exp': True,
                'verify_nbf': False,
                'verify_iat': True,
                'verify_aud': False
            }

            dictToken = jwt.decode(szToken,
                                   TokenUtils.JWT_SALT,
                                   algorithms=["HS512"],
                                   options=jwt_options)
            return dictToken
        except Exception as ex:
            g_logger.error(ex)
            return None
예제 #19
0
    def auth_token(cls, szAppId, szSecret):
        try:
            szUrl = "{}{}".format(TokenUtils.g_szHost, "/ruoyi-api/auth/token")
            resp = requests.post(szUrl,
                                 data={
                                     "appid": szAppId,
                                     "secret": szSecret
                                 })

            if 200 != resp.status_code:
                return None

            dictRet = json.loads(resp.text)
            if 200 != dictRet["code"]:
                return None

            return dictRet["token"]
        except Exception as ex:
            g_logger.error(ex)
            return None
예제 #20
0
    async def add_user_to_group(cls, nUID, nGID):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor() as cur:
                        await cur.execute(
                            "INSERT INTO "
                            "  t_thinkauth_user_group(user_id, group_id) "
                            "VALUES "
                            "  (%s, %s)", (nUID, nGID))

                        await conn.commit()

                        return True
                except Exception as e:
                    g_logger.error(e)
                    return True
                finally:
                    conn.close()
        except Exception as e:
            g_logger.error(e)
            return True
예제 #21
0
    async def change_group_name(cls, nGID, szNewGroupName):
        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor() as cur:
                        await cur.execute(
                            "UPDATE t_thinkauth_group "
                            "  set `name` = %s "
                            "WHERE "
                            "  id = %s ", (szNewGroupName, nGID))

                        await conn.commit()

                        dictRet = await cls.get_group(nGID)
                        return dictRet
                except Exception as e:
                    g_logger.error(e)
                    return None
                finally:
                    conn.close()
        except Exception as e:
            g_logger.error(e)
            return None
예제 #22
0
    async def my_permission_list(cls, nUID):
        if nUID <= 0:
            return []

        try:
            conn_pool = await ThinkAioMysql.get_conn_pool()
            async with conn_pool.acquire() as conn:
                try:
                    async with conn.cursor(aiomysql.cursors.DictCursor) as cur:
                        await cur.execute(
                            "SELECT                                                 "
                            "	a.permission_name                                   "
                            "FROM                                                   "
                            "	t_thinkauth_permission AS a                           "
                            "WHERE                                                  "
                            "	EXISTS (                                              "
                            "		SELECT                                                 "
                            "			1                                                     "
                            "		FROM                                                   "
                            "			t_thinkauth_user_permission AS b                      "
                            "			LEFT JOIN t_thinkauth_user AS c ON b.user_id = c.id   "
                            "		WHERE                                                  "
                            "			b.permission_id = a.id                                "
                            "			AND c.id = %s                                   "
                            "			)                                                     "
                            "	OR EXISTS (                                           "
                            "		SELECT                                                 "
                            "			1                                                     "
                            "		FROM                                                   "
                            "			t_thinkauth_group_permission AS d                     "
                            "		WHERE                                                  "
                            "			d.group_id IN (                                       "
                            "				SELECT                                              "
                            "					f.group_id                                        "
                            "				FROM                                                "
                            "					t_thinkauth_user_group AS f                       "
                            "				WHERE                                               "
                            "					d.permission_id = a.id                            "
                            "					AND f.user_id = %s                          "
                            "				)                                                   "
                            "	)                                                     ",
                            (nUID, nUID))

                        rows = await cur.fetchall()
                        if rows is None or len(rows) <= 0:
                            return []

                        lstRet = []
                        for row in rows:
                            lstRet.append(row["permission_name"])

                        return lstRet
                except Exception as e:
                    g_logger.error(e)
                    return []
                finally:
                    conn.close()

        except Exception as e:
            g_logger.error(e)
            return []