authenticate.js 2.3 KB
var async= require('async');

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

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

				logger.info("url:"+rest.getBaseUrl('auth/tokens','uaa'));
				logger.info("params",tempParams);
				console.log(tempParams)
				rest.restful.postJson(rest.getBaseUrl('auth/tokens','uaa'),tempParams,{
					headers: { 'Content-Type': 'application/json',"Accept": "application/json" }})
					.on('success',function(data,response){
						logger.info("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);
						}
					}).on('error',function(err,response){
					//	logger.info("tokens-error",data);
						var err = new Error('name or pass err');
							callback(err,response);
					}).on('fail',function(data,response){
						logger.info("tokens-fail",data);
						var err = new Error('name or pass err');
							callback(data,response);
				});
			}],function(err,result){
				logger.info(err);
				if(err){
					return done(null,false,err);
				}else{
					return done(null,user);
				}
		});
    }

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

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

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

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