OpenResty学习笔记(十) 登录验证,openresty学习笔记


上一篇中我们已经可能搭起一个完整的nginx的环境,那现在我们就可以做点什么了吧,先从一个最开始的事做起:登录。
一般来说登录这个动作是基本上所有的系统都需要的,就拿这个练手吧,先顺一下流程。web端也不需要什么页面了,直接发一个http的get请示,把user跟pwd作为参数传过来,nginx接收,然后走一下数据库验证并给出返回,这应该是个简单得不能再简单的登录了吧。既然那么简单那么就直接上代码啦。
首先是Nginx的配置:

http {
    lua_package_path '/opt/nginx/openresty-test/lua/?.lua;/opt/nginx/openresty-test/lua/lualog/src/?.lua;;';

    lua_code_cache off;
    lua_shared_dict my_cache 128m;
    server {
        listen 6699;
        location / {
            root /opt/nginx/openresty-test/www;
            index index.html index.htm index.php;
        }
        location /login {
            access_by_lua_file  lua/access_check.lua;
            content_by_lua_file lua/login.lua;
        }
        location = /favicon.ico {
            log_not_found off;
        }
    }
}

有几点要说一下,首先
lua_package_path '/opt/nginx/openresty-test/lua/?.lua;/opt/nginx/openresty-test/lua/lualog/src/?.lua;;';
这个是指定nginx要去哪个地方去找lua文件的,因为下面的
access_by_lua_file lua/access_check.lua;
content_by_lua_file lua/login.lua;

都是给的相对路径,所以如果这个地方不设置的话可能会出现找不到lua文件的情况。
/opt/nginx/openresty-test/lua/这个是我lua文件的存放目录
/opt/nginx/openresty-test/lua/lualog/src/这个是一个lualogging的第三方库,用于打印日志的。至于为什么不用nginx自己的日志:1个是因为nginx的日志里面存了好多访问信息啊等各种东西,找起来太费劲。2个是很多时候需要单独调试lua文件,不需要走nginx这个时候的日志输出就是个问题了,所以就从网上找到了这个库,给大家发下git链接,有需要的可以去下。

 lua_code_cache off;

这一句会关掉Lua代码缓存,说明白点就是你改完lua程序之后不用reload nginx了。
继续贴代码

access_check.lua
local args = ngx.req.get_uri_args()

if not args.user or  not args.pwd then
    ngx.exit(ngx.HTTP_BAD_REQUEST)
    return
end

access_check.lua只做了一个简单的事情,检查一下参数是不是齐全,否则扔出一个HTTP_BAD_REQUEST错误
看一下效果

login.lua
require"logging.file"

local logger = logging.file("/tmp/login%s.log", "%Y-%m-%d")
local args = ngx.req.get_uri_args()
local mysql = require "resty.mysql"
local db, err = mysql:new()


if not db then
    ngx.say("failed to instantiate mysql: ", err)
    return
end

db:set_timeout(1000)
local ok, err, errno, sqlstate = db:connect{
    host = "192.168.1.168",
    port = 3306,
    database = "test",
    user = "root",
    password = "123456",
    max_packet_size = 1024 * 1024 }
if not ok then
    ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate)
    return
end

local args = ngx.req.get_uri_args()
opt_sql = string.format("select passwd from vp_operator where operid = '%s' limit 1",args.user)
res, err, errno, sqlstate = db:query(opt_sql)
if not res or next(res) == nil then
    ngx.say("no such user: ",args.user)
    return
end

passwd = res[1].passwd
if passwd == args.pwd then
    ngx.say("login success!")
else
    ngx.say("passwd error")
end

login.lua做的事情也很简单,创建一个mysql连接,获取用户名跟密码,验证然后给出返回。这里连接数据库使用了resty里面提供的mysql库,通过mysql:new()生成一个新的连接对象,可能调用connect{}来连接远程的数据库,query函数来执行sql语句,获取查询结果。看下运行结果:



这里只是最简单地实现了这个流程,当然我们说这有太多漏洞,密码没有加密显示明文,没有验证码,登录还有用get发请求的?这些都可以由读者自己去完善,本人也会更积极地去学习,本来是想加上md5验证的,不过resty.md5那个还没看明白,以后用到了会再回来完善的!

相关内容

    暂无相关文章