authenticate.js 2.8 KB
/*
 * @Descripttion: 
 * @version: 0.0.0
 * @Author: genglw
 * @Date: 2022-01-21 15:31:14
 * @LastEditors: genglw
 * @LastEditTime: 2022-02-12 16:57:36
 */
var async = require('async');

exports = module.exports = function (logger, rest) {

	function strategy(req, username, password, done) {
		var user = {
			refreshToken: "",
			token: "",
			yxly_token: "",
			service_catalog: {},
			user_info: {},
			err: null
		};
		async.waterfall([
			function (callback) {//get temp token
				logger.debug("get temp token");
				var tempParams = {
					"grant_type": req.body.grant_type,
					"username": req.body.username,
					"scope": req.body.scope,
					"password": req.body.password,
					"img_code": req.body.img_code,
				};
				if (req.body.smscode)
					tempParams['sms_code'] = req.body.smscode;

				logger.debug("url:" + rest.getBaseUrl('auth/tokens', 'uaa'));
				logger.debug("params", tempParams);
				var url = rest.getBaseUrl('auth/tokens', 'uaa');
				var headers = rest.addHeaders({ 'Content-Type': 'application/json', "Accept": "application/json" },req);
				rest.restful.postJson(url, tempParams, {
					headers: headers
				})
					.on('success', function (data, response) {
						logger.debug("tokens-success", data);
						if (data.access_token) {
							user.token = data.access_token;
							user.refreshToken = data.refresh_token;
							user.user_info = {
								'user': data.user,
								'tenant': data.tenant,
								'perms': [],
								'scope': data.scope,
								'oss': {}
							};
							user.service_catalog = data.service_catalog
							callback(null, data)
						} else {
							var err = new Error('name or pass err');
							user.err = data.message;
							callback(err, data);
						}
						rest.proxyLog(data,response,req,{headers,'data':tempParams,url})
					}).on('error', function (err, response) {
						//	logger.debug("tokens-error",data);
						var err = new Error('name or pass err');
						rest.proxyLog(err,response,req,{headers,'data':tempParams,url})
						callback(err, response);
					}).on('fail', function (data, response) {
						logger.debug("tokens-fail", data);
						var err = new Error('name or pass err');
						rest.proxyLog(data,response,req,{headers,'data':tempParams,url})
						callback(data, response);
					});
			}], function (err, result) {
				if (err) {
					return done(null, false, err);
				} else {
					return done(null, user);
				}
			});
	}

	function serializeUser(user, done) {
		logger.debug("passport.serializeUser");
		done(null, user);
	}

	function deserializeUser(user, done) {
		var user = {
			refreshToken: "",
			token: "",
			info: {},
			err: null
		};
		logger.debug("passport.deserializeUser");
		done(null, user);
	}

	return {
		strategy: strategy,
		serializeUser: serializeUser,
		deserializeUser: deserializeUser
	};
};

exports['@singleton'] = true;
exports['@require'] = ['igloo/logger', 'utils/rest'];