passport.js 5.26 KB

const _ = require('lodash');
const url = require('url');
const uuid = require('uuid');
const passport = require('passport');
const TaobaoStrategy = require('./passport-taobao');
const authcode = require('../../utils/authcode');
const aes = require('./aes');

const log = global.yoho.logger;
const sign = global.yoho.sign;
const crypto = global.yoho.crypto;
const config = global.yoho.config;

const loginPage = `${config.siteUrl}/signin.html`;
const bindPage = `/xianyu/passport/bind`;

// taobao 登录
passport.use('taobao', new TaobaoStrategy({
    clientID: '27930297',
    clientSecret: '29b30287153a02f531c160df17da8078',
    callbackURL: `http://127.0.0.1:6001/xianyu/passport/callback/taobao`,
    requireState: false
}, (accessToken, refreshToken, profile, done) => {
    done(null, profile);
}));

class signModel extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);
    }
    signinByOpenID({ nickname, openId, sourceType, businessLine}) {
        let param = {
            nickname: nickname || '',
            openId: openId,
            source_type: sourceType, // esline-disable-line
            method: 'app.passport.signinByOpenID'
        };

        if (businessLine) {
            param.business_line = businessLine;
        }

        return this.get({ data: param }).then(res => {
            console.log(res);
            return res;
        });
    }
    syncUserSession({uid, sessionKey, req, res}) {
        let userId = {
            toString: () => {
                return uid;
            }
        };

        if (sessionKey) {
            req.session.LOGIN_UID_ = uid;
            req.session.SESSION_KEY = sessionKey;
            res.cookie('_SESSION_KEY', authcode(sessionKey, '_SESSION_KEY', 2592000000, 'encode'), {
                domain: 'yohobuy.com',
                expires: new Date(Date.now() + 2592000000), // 有效期一年
                httpOnly: true
            });
            userId.sessionKey = sessionKey;
        }

        return this.get({
            data: {
                uid,
                method: 'app.passport.profile'
            }
        }).then((userInfo) => {
            let salt = uuid.v4().substr(0, 8);
            let saltedUid = uid + salt;

            let saltedToken = sign.makeToken(saltedUid);
            let publicToken = saltedToken + salt;

            let data = userInfo.data;
            let encryptionUid = aes.encryptionUid(uid);

            if (data) {
                data.profile_name = (data.profile_name || '').replace(/::/g, '');

                let uidCookie = `${data.profile_name}::${encryptionUid}::${data.vip_info && data.vip_info.title}::${saltedToken}`;

                res.cookie('_UID', uidCookie, {
                    domain: 'yohobuy.com',
                    expires: new Date(Date.now() + 2592000000) // 有效期一年
                });

                req.session.AVATAR = data.head_ico;
                _.set(req.session, 'USER.AVATAR', data.head_ico);
                _.set(req.session, 'USER.NAME', data.profile_name);
            }

            req.session.TOKEN = publicToken;
            req.session.LOGIN_UID_ = uid;

            _.set(req.session, 'USER.ENCRYPTION_UID', encryptionUid);

            res.cookie('_TOKEN', publicToken, {
                httpOnly: true,
                domain: 'yohobuy.com',
                expires: new Date(Date.now() + 2592000000) // 有效期一年
            });
        });
    }
};

const login = {
    taobaoLogin: (req, res, next) => {
        req.session.authState = uuid.v4();

        return passport.authenticate('taobao', {
            state: req.session.authState,
            failWithError: true
        })(req, res, next);
    },
    taobaoCallback: (req, res, next) => {
        passport.authenticate('taobao', (err, user) => {
            if (err || !user) {
                log.error(`taobao authenticate error : ${JSON.stringify(err)}`);
                return res.redirect(loginPage);
            }

            const model = req.ctx(signModel);

            return model.signinByOpenID({
                openId: user.open_uid,
                sourceType: 'taobao'
            }).then(result => {
                let redirectUrl = loginPage;

                if (result.code === 200) {
                    if (_.get(result, 'data.is_bind') === 'N') {
                        redirectUrl = req.cookies.third_backurl ? url.parse(req.cookies.third_backurl) : '/xianyu/passport/bind';

                        if (redirectUrl.indexOf('?')) {
                            redirectUrl += '&bind_code' + crypto.dynamicEncryption(user.open_uid);
                        }
                    } else if (+_.get(result, 'data.uid') > 0) {
                        return model.syncUserSession({
                            uid: result.data.uid,
                            sessionKey: result.data.session_key,
                            req,
                            res
                        }).finally(() => {
                            let refer = req.cookies.third_backurl ? url.parse(req.cookies.third_backurl) : '';

                            return res.redirect(refer);
                        });
                    }
                }

                return res.redirect(redirectUrl);
            })
        })(req, res, next);
    }
}

module.exports = {
    login
};