Browse Source

redis ok

release_0.0.1
yuan_yi 3 years ago
parent
commit
0c3cc7ab25
  1. 11
      code/api/.vscode/launch.json
  2. 14
      code/api/app/lib/controllers/auth/index.js
  3. 3
      code/api/app/lib/index.js
  4. 15
      code/api/app/lib/middlewares/authenticator.js
  5. 2
      code/api/app/lib/models/user.js
  6. 44
      code/api/app/lib/service/redis.js
  7. 22
      code/api/config.js
  8. 5
      code/api/package.json
  9. 63
      code/api/yarn.lock

11
code/api/.vscode/launch.json

@ -13,12 +13,11 @@
"NODE_ENV": "development"
},
"args": [
"-p 14000",
"-f http://localhost:14000",
// "-g postgres://postgres:123@10.8.30.32:5432/yinjiguanli",
// "-g postgres://postgres:123456@221.230.55.27:5432/yinjiguanli",
// "-g postgres://FashionAdmin:123456@10.8.30.156:5432/SmartEmergency",
"-g postgres://postgres:Mantis1921@116.63.50.139:54327/smartYingji"
"-p 4200",
"-f http://localhost:4200",
"-g postgres://postgres:123@10.8.30.32:5432/iot_auth",
"--redisHost 127.0.0.1",
"--redisPort 6379"
]
},
{

14
code/api/app/lib/controllers/auth/index.js

@ -25,7 +25,7 @@ async function login (ctx, next) {
ctx.body = {
"message": "账号或密码错误"
}
} else if (!userRes.enable) {
} else if (!userRes.enabled) {
ctx.status = 400;
ctx.body = { message: "该用户已被禁用" }
} else {
@ -39,11 +39,17 @@ async function login (ctx, next) {
}
);
await models.UserToken.create({
let tokenMsg = {
token: token,
userInfo: userRslt,
expired: moment().add(30, 'days').format()
});
}
await models.UserToken.create(tokenMsg);
tokenMsg.userInfo = JSON.stringify(tokenMsg.userInfo)
tokenMsg.expired = moment(tokenMsg.expired).format()
await ctx.redis.hmset(token, tokenMsg);
ctx.status = 200;
ctx.body = userRslt;
@ -70,6 +76,8 @@ async function logout (ctx) {
},
});
await ctx.redisTools.hdelall(token);
ctx.status = 204;
} catch (error) {
ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);

3
code/api/app/lib/index.js

@ -3,6 +3,7 @@
const routes = require('./routes');
const authenticator = require('./middlewares/authenticator');
// const apiLog = require('./middlewares/api-log');
const redisConnect = require('./service/redis')
module.exports.entry = function (app, router, opts) {
app.fs.logger.log('info', '[FS-AUTH]', 'Inject auth and api mv into router.');
@ -11,6 +12,8 @@ module.exports.entry = function (app, router, opts) {
app.fs.api.authAttr = app.fs.api.authAttr || {};
app.fs.api.logAttr = app.fs.api.logAttr || {};
redisConnect(app, opts)
router.use(authenticator(app, opts));
// router.use(apiLog(app, opts));

15
code/api/app/lib/middlewares/authenticator.js

@ -13,13 +13,13 @@ class ExcludesUrls {
this.reload(opts);
}
sanitizePath(path) {
sanitizePath (path) {
if (!path) return '/';
const p = '/' + path.replace(/^\/+/i, '').replace(/\/+$/, '').replace(/\/{2,}/, '/');
return p;
}
reload(opts) {
reload (opts) {
// load all url
if (!this.allUrls) {
this.allUrls = opts;
@ -37,7 +37,7 @@ class ExcludesUrls {
}
}
isExcluded(path, method) {
isExcluded (path, method) {
return this.allUrls.some(function (url) {
return !url.auth
&& url.pregexp.test(path)
@ -72,13 +72,13 @@ let authorizeToken = async function (ctx, token) {
const tokenFormatRegexp = /^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$/g;
if (token && tokenFormatRegexp.test(token)) {
try {
const axyRes = await ctx.fs.dc.models.UserToken.findOne({
const tokenRes = await ctx.fs.dc.models.UserToken.findOne({
where: {
token: token,
expired: { $gte: moment().format('YYYY-MM-DD HH:mm:ss') }
}
});
const { userInfo, expired } = axyRes;
const { userInfo, expired } = tokenRes;
if (!expired || moment().valueOf() <= moment(expired).valueOf()) {
rslt = {
'authorized': userInfo.authorized,
@ -112,13 +112,14 @@ let isResourceAvailable = function (resources, options) {
return !authCode || (resources || []).some(code => code === authCode);
};
function factory(app, opts) {
return async function auth(ctx, next) {
function factory (app, opts) {
return async function auth (ctx, next) {
const { path, method, header, query } = ctx;
ctx.fs.logger.log('[AUTH] start', path, method);
ctx.fs.api = ctx.fs.api || {};
ctx.fs.port = opts.port;
ctx.redis = app.redis;
ctx.redisTools = app.redisTools;
let error = null;
if (path) {
if (!isPathExcluded(opts, path, method)) {

2
code/api/app/lib/models/user.js

@ -15,7 +15,7 @@ module.exports = dc => {
autoIncrement: true,
unique: "user_id_uindex"
},
name: {
username: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: null,

44
code/api/app/lib/service/redis.js

@ -0,0 +1,44 @@
'use strict';
const redis = require("ioredis")
const moment = require('moment')
module.exports = async function factory (app, opts) {
let client = new redis(opts.redis.port, opts.redis.host);
client.on("error", function (err) {
app.fs.logger.error('info', '[FS-AUTH-REDIS]', 'redis connect error.');
console.error("Error :", err);
process.exit(-1);
});
client.on('connect', function () {
console.log(`redis connect success ${opts.redis.host + ':' + opts.redis.port}`);
})
// 查询尚未过期token放入redis
const tokenRes = await app.fs.dc.models.UserToken.findAll({
where: {
expired: { $gte: moment().format('YYYY-MM-DD HH:mm:ss') }
}
});
for (let t of tokenRes) {
const { token, dataValues } = t
dataValues.userInfo = JSON.stringify(dataValues.userInfo)
dataValues.expired = moment(dataValues.expired).format()
await client.hmset(token, dataValues);
}
// token 2 redis end
// 自定义方法
async function hdelall (key) {
const obj = await client.hgetall(key);
const hkeys = Object.keys(obj)
await client.hdel(key, hkeys)
}
app.redis = client
app.redisTools = {
hdelall,
}
}

22
code/api/config.js

@ -11,13 +11,20 @@ const dev = process.env.NODE_ENV == 'development';
args.option(['p', 'port'], '启动端口');
args.option(['g', 'pg'], 'postgre服务URL');
args.option(['f', 'fileHost'], '文件中心本地化存储: WebApi 服务器地址(必填), 该服务器提供文件上传Web服务');
args.option('redisHost', 'redisHost');
args.option('redisPort', 'redisPort');
args.option('redisPswd', 'redisPassword');
const flags = args.parse(process.argv);
const IOT_VIDEO_ACCESS_DB = process.env.IOT_VIDEO_ACCESS_DB || flags.pg;
const IOT_VIDEO_ACCESS_LOCAL_SVR_ORIGIN = process.env.IOT_VIDEO_ACCESS_LOCAL_SVR_ORIGIN || flags.fileHost;
const IOT_AUTH_DB = process.env.IOT_AUTH_DB || flags.pg;
const IOT_AUTH_LOCAL_SVR_ORIGIN = process.env.IOT_AUTH_LOCAL_SVR_ORIGIN || flags.fileHost;
if (!IOT_VIDEO_ACCESS_DB) {
const IOTA_REDIS_SERVER_HOST = process.env.IOTA_REDIS_SERVER_HOST || flags.redisHost || "localhost";//redis IP
const IOTA_REDIS_SERVER_PORT = process.env.IOTA_REDIS_SERVER_PORT || flags.redisPort || "6379";//redis 端口
const IOTA_REDIS_SERVER_PWD = process.env.IOTA_REDIS_SERVER_PWD || flags.redisPswd || "";//redis 密码
if (!IOT_AUTH_DB || !IOTA_REDIS_SERVER_HOST || !IOTA_REDIS_SERVER_PORT) {
console.log('缺少启动参数,异常退出');
args.showHelp();
process.exit(-1);
@ -31,7 +38,7 @@ const product = {
entry: require('@fs/attachment').entry,
opts: {
local: {
origin: IOT_VIDEO_ACCESS_LOCAL_SVR_ORIGIN || `http://localhost:${flags.port || 8080}`,
origin: IOT_AUTH_LOCAL_SVR_ORIGIN || `http://localhost:${flags.port || 8080}`,
rootPath: 'static',
childPath: 'upload',
},
@ -41,11 +48,16 @@ const product = {
entry: require('./app').entry,
opts: {
exclude: [], // 不做认证的路由,也可以使用 exclude: ["*"] 跳过所有路由
redis: {
host: IOTA_REDIS_SERVER_HOST,
port: IOTA_REDIS_SERVER_PORT,
pwd: IOTA_REDIS_SERVER_PWD
},
}
}
],
dc: {
url: IOT_VIDEO_ACCESS_DB,
url: IOT_AUTH_DB,
opts: {
pool: {
max: 80,

5
code/api/package.json

@ -17,14 +17,13 @@
"crypto-js": "^4.0.0",
"file-saver": "^2.0.2",
"fs-web-server-scaffold": "^2.0.2",
"ioredis": "^4.19.4",
"ioredis": "^5.0.4",
"koa-convert": "^1.2.0",
"koa-proxy": "^0.9.0",
"moment": "^2.24.0",
"path": "^0.12.7",
"path-to-regexp": "^3.0.0",
"pg": "^7.9.0",
"redis": "^3.1.2",
"request": "^2.88.2",
"superagent": "^3.5.2",
"uuid": "^3.3.2"
@ -32,4 +31,4 @@
"devDependencies": {
"mocha": "^6.0.2"
}
}
}

63
code/api/yarn.lock

@ -13,6 +13,11 @@
superagent "^6.1.0"
uuid "^3.1.0"
"@ioredis/commands@^1.1.1":
version "1.1.1"
resolved "http://10.8.30.22:7000/@ioredis%2fcommands/-/commands-1.1.1.tgz#2ba4299ea624a6bfac15b35f6df90b0015691ec3"
integrity sha512-fsR4P/ROllzf/7lXYyElUJCheWdTJVJvOTps8v9IWKFATxR61ANOlnoPqhH099xYLrJGpc2ZQ28B3rMeUt5VQg==
"@tootallnate/once@1":
version "1.1.2"
resolved "http://10.8.30.22:7000/@tootallnate%2fonce/-/once-1.1.2.tgz#ccb91445360179a04e7fe6aff78c00ffc1eeaf82"
@ -582,7 +587,7 @@ debug@3.2.6:
dependencies:
ms "^2.1.1"
debug@4, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.2:
debug@4, debug@^4.1.0, debug@^4.1.1, debug@^4.3.2:
version "4.3.3"
resolved "http://10.8.30.22:7000/debug/-/debug-4.3.3.tgz#04266e0b70a98d4462e6e288e38259213332b664"
integrity sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==
@ -603,6 +608,13 @@ debug@^3.1.0, debug@^3.2.5:
dependencies:
ms "^2.1.1"
debug@^4.3.4:
version "4.3.4"
resolved "http://10.8.30.22:7000/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865"
integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==
dependencies:
ms "2.1.2"
decamelize@^1.2.0:
version "1.2.0"
resolved "http://10.8.30.22:7000/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290"
@ -652,10 +664,10 @@ delegates@^1.0.0:
resolved "http://10.8.30.22:7000/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a"
integrity sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=
denque@^1.1.0, denque@^1.5.0:
version "1.5.1"
resolved "http://10.8.30.22:7000/denque/-/denque-1.5.1.tgz#07f670e29c9a78f8faecb2566a1e2c11929c5cbf"
integrity sha1-B/Zw4pyaePj67LJWah4sEZKcXL8=
denque@^2.0.1:
version "2.0.1"
resolved "http://10.8.30.22:7000/denque/-/denque-2.0.1.tgz#bcef4c1b80dc32efe97515744f21a4229ab8934a"
integrity sha1-vO9MG4DcMu/pdRV0TyGkIpq4k0o=
depd@2.0.0, depd@^2.0.0, depd@~2.0.0:
version "2.0.0"
@ -1354,19 +1366,17 @@ internal-slot@^1.0.3:
has "^1.0.3"
side-channel "^1.0.4"
ioredis@^4.19.4:
version "4.28.5"
resolved "http://10.8.30.22:7000/ioredis/-/ioredis-4.28.5.tgz#5c149e6a8d76a7f8fa8a504ffc85b7d5b6797f9f"
integrity sha512-3GYo0GJtLqgNXj4YhrisLaNNvWSNwSS2wS4OELGfGxH8I69+XfNdnmV1AyN+ZqMh0i7eX+SWjrwFKDBDgfBC1A==
ioredis@^5.0.4:
version "5.0.4"
resolved "http://10.8.30.22:7000/ioredis/-/ioredis-5.0.4.tgz#0d4abfd818adfc5ef5029fddac4b8f503a1433b7"
integrity sha512-qFJw3MnPNsJF1lcIOP3vztbsasOXK3nDdNAgjQj7t7/Bn/w10PGchTOpqylQNxjzPbLoYDu34LjeJtSWiKBntQ==
dependencies:
"@ioredis/commands" "^1.1.1"
cluster-key-slot "^1.1.0"
debug "^4.3.1"
denque "^1.1.0"
debug "^4.3.4"
denque "^2.0.1"
lodash.defaults "^4.2.0"
lodash.flatten "^4.4.0"
lodash.isarguments "^3.1.0"
p-map "^2.1.0"
redis-commands "1.7.0"
redis-errors "^1.2.0"
redis-parser "^3.0.0"
standard-as-callback "^2.1.0"
@ -1741,11 +1751,6 @@ lodash.defaults@^4.2.0:
resolved "http://10.8.30.22:7000/lodash.defaults/-/lodash.defaults-4.2.0.tgz#d09178716ffea4dde9e5fb7b37f6f0802274580c"
integrity sha1-0JF4cW/+pN3p5ft7N/bwgCJ0WAw=
lodash.flatten@^4.4.0:
version "4.4.0"
resolved "http://10.8.30.22:7000/lodash.flatten/-/lodash.flatten-4.4.0.tgz#f31c22225a9632d2bbf8e4addbef240aa765a61f"
integrity sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=
lodash.isarguments@^3.1.0:
version "3.1.0"
resolved "http://10.8.30.22:7000/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a"
@ -2074,11 +2079,6 @@ p-locate@^3.0.0:
dependencies:
p-limit "^2.0.0"
p-map@^2.1.0:
version "2.1.0"
resolved "http://10.8.30.22:7000/p-map/-/p-map-2.1.0.tgz#310928feef9c9ecc65b68b17693018a665cea175"
integrity sha1-MQko/u+cnsxltosXaTAYpmXOoXU=
p-try@^2.0.0:
version "2.2.0"
resolved "http://10.8.30.22:7000/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6"
@ -2413,11 +2413,6 @@ readable-stream@^3.4.0, readable-stream@^3.6.0:
string_decoder "^1.1.1"
util-deprecate "^1.0.1"
redis-commands@1.7.0, redis-commands@^1.7.0:
version "1.7.0"
resolved "http://10.8.30.22:7000/redis-commands/-/redis-commands-1.7.0.tgz#15a6fea2d58281e27b1cd1acfb4b293e278c3a89"
integrity sha1-Fab+otWCgeJ7HNGs+0spPieMOok=
redis-errors@^1.0.0, redis-errors@^1.2.0:
version "1.2.0"
resolved "http://10.8.30.22:7000/redis-errors/-/redis-errors-1.2.0.tgz#eb62d2adb15e4eaf4610c04afe1529384250abad"
@ -2430,16 +2425,6 @@ redis-parser@^3.0.0:
dependencies:
redis-errors "^1.0.0"
redis@^3.1.2:
version "3.1.2"
resolved "http://10.8.30.22:7000/redis/-/redis-3.1.2.tgz#766851117e80653d23e0ed536254677ab647638c"
integrity sha1-dmhREX6AZT0j4O1TYlRnerZHY4w=
dependencies:
denque "^1.5.0"
redis-commands "^1.7.0"
redis-errors "^1.2.0"
redis-parser "^3.0.0"
request@*, request@^2.88.2:
version "2.88.2"
resolved "http://10.8.30.22:7000/request/-/request-2.88.2.tgz#d73c918731cb5a87da047e207234146f664d12b3"

Loading…
Cancel
Save