add mongo_db:auth

This commit is contained in:
Cloud Wu
2018-08-30 09:51:55 +08:00
committed by 云风
parent 1c8ed8a46e
commit 7e63080c03

View File

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