add mongo_db:auth

This commit is contained in:
Cloud Wu
2018-08-30 09:51:55 +08:00
parent e6e69ae805
commit c4334be9c3

View File

@@ -82,6 +82,8 @@ local function __parse_addr(addr)
return host, tonumber(port)
end
local auth_method = {}
local function mongo_auth(mongoc)
local user = rawget(mongoc, "username")
local pass = rawget(mongoc, "password")
@@ -95,7 +97,7 @@ local function mongo_auth(mongoc)
return function()
if user ~= nil and pass ~= nil then
-- autmod can be "mongodb_cr" or "scram_sha1"
local auth_func = mongoc[authmod]
local auth_func = auth_method[authmod]
assert(auth_func , "Invalid authmod")
assert(auth_func(authdb or mongoc, user, pass))
end
@@ -211,7 +213,7 @@ function mongo_client:runCommand(...)
return self.admin:runCommand(...)
end
function mongo_client:auth_mongodb_cr(user,password)
function auth_method:auth_mongodb_cr(user,password)
local password = md5.sumhexa(string.format("%s:mongo:%s",user,password))
local result= self:runCommand "getnonce"
if result.ok ~=1 then
@@ -234,7 +236,7 @@ local function salt_password(password, salt, iter)
return output
end
function mongo_client:auth_scram_sha1(username,password)
function auth_method:auth_scram_sha1(username,password)
local user = string.gsub(string.gsub(username, '=', '=3D'), ',' , '=2C')
local nonce = crypt.base64encode(crypt.randomkey())
local first_bare = "n=" .. user .. ",r=" .. nonce
@@ -305,6 +307,13 @@ function mongo_client:logout()
return result.ok == 1
end
function mongo_db:auth(user, pass)
local authmod = rawget(self.connection, "authmod") or "scram_sha1"
local auth_func = auth_method[authmod]
assert(auth_func , "Invalid authmod")
return auth_func(self, user, pass)
end
function mongo_db:runCommand(cmd,cmd_v,...)
local conn = self.connection
local request_id = conn:genId()