ngx_lua访问数据库

https://github.com/openresty/lua-resty-mysql 张宜春大师写的mysql链接模块

利用大神的模块,下面是我写的一个验证的函数,通过用户session判断这次访问是否合法。

function F.check_session()
    local uid = args["uid"]
    local session = args["session"]
    local mysql = require "mysql"

    if uid == nil or uid == 0 then
        ngx.exit(403)
    end

    local db, err = mysql:new()
    if not db then
        ngx.say("failed to instantiate mysql: ", err)
        return
    end
    db:set_timeout(1000) -- 1 sec

    local ok, err, errno, sqlstate = db:connect{
        host = "127.0.0.1",
        port = 3306,
        database = "xxx",
        user = "root",
        password = "xxx",
        max_packet_size = 1024 * 1024
    }

    if not ok then
        ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate)
        return
    end

    sql = "SELECT * FROM `sessions` WHERE `uid` =  ".. uid .. " and `session_id` = " .."\"" .. session .."\""
    res, err, errno, sqlstate = db:query(sql)
    if not res then
        ngx.header["ID_Error"] = "sql error"
        ngx.exit(403)
    elseif #(res) > 0 then
        --local cjson = require "cjson"
        local time_now = os.time()
        local last_time = tonumber(res[1]["last_activity"]) + tonumber(res[1]["life_time"])

        if last_time <= time_now then
            ngx.exit(403)
        end

        --[[
        local session = args["session"]
        local session_id = res[1]["session_id"]

        if session ~= session_id then
            ngx.header["ID_Error"] = "error session"
            ngx.exit(403)
        end
        --]]
    else
        ngx.header["ID_Error"] = "sqldate error"
        ngx.exit(403)
    end
end

你可能感兴趣的:(LUA,MYSQL,linux运维)