From c4334be9c3c3d840dfbc17f89284f40ed0531864 Mon Sep 17 00:00:00 2001 From: Cloud Wu Date: Thu, 30 Aug 2018 09:51:55 +0800 Subject: [PATCH] add mongo_db:auth --- lualib/skynet/db/mongo.lua | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/lualib/skynet/db/mongo.lua b/lualib/skynet/db/mongo.lua index 04b27805..ec8063a6 100644 --- a/lualib/skynet/db/mongo.lua +++ b/lualib/skynet/db/mongo.lua @@ -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()