Last active
September 19, 2017 03:12
-
-
Save liujingyu/5dadd3674a57ced74e28a5017baac6c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
worker_processes 1; # we could enlarge this setting on a multi-core machine | |
error_log logs/error.log warn; | |
events { | |
worker_connections 2048; | |
} | |
http { | |
lua_package_path 'conf/?.lua;;'; | |
server { | |
listen 8080; | |
server_name localhost; | |
#lua_code_cache on; | |
location /test { | |
access_by_lua_block { | |
local jwt = require "resty.jwt" | |
local foo = require "foo" | |
local err_msg = { | |
x_token = {err = "set x-token in request, please!"}, | |
payload = {err = "payload not found"}, | |
user_key = {err = "用户配置信息有问题"}, | |
password = {err = "密码已修改,请重新登录"}, | |
ok = {ok = "this is my own error page content"}, | |
} | |
-- 判断token是否传递 | |
local req_headers = ngx.req.get_headers() | |
if req_headers.x_token == nil then | |
foo:response_json(422, err_msg.x_token) | |
return | |
end | |
local jwt_obj = jwt:load_jwt(req_headers.x_token) | |
local redis = require "resty.redis" | |
local red = redis:new() | |
red:set_timeout(1000) -- 1 sec | |
local ok, err = red:connect("127.0.0.1", 6379) | |
if not ok then | |
ngx.say("failed to connect: ", err) | |
return | |
end | |
-- 请注意这里 auth 的调用过程 | |
local count | |
count, err = red:get_reused_times() | |
if 0 == count then | |
ok, err = red:auth("test123456") | |
if not ok then | |
ngx.say("failed to auth: ", err) | |
return | |
end | |
elseif err then | |
ngx.say("failed to get reused times: ", err) | |
return | |
end | |
if jwt_obj.payload == nil then | |
foo:response_json(422, err_msg.payload) | |
return | |
end | |
local sub = jwt_obj.payload.sub | |
user_key, err = red:get('user:' .. sub) | |
if user_key == ngx.null then | |
foo:response_json(500, err_msg.user_key) | |
return | |
elseif tonumber(user_key) > 3 then | |
foo:response_json(401, err_msg.password) | |
return | |
else | |
foo:response_json(200, err_msg.ok) | |
return | |
end | |
-- 连接池大小是100个,并且设置最大的空闲时间是 10 秒 | |
local ok, err = red:set_keepalive(10000, 200) | |
if not ok then | |
ngx.say("failed to set keepalive: ", err) | |
return | |
end | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment