login.js 18.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
/* eslint no-unused-vars: ["error", { "args": "none" }] */
/**
 * 登录
 * @author: Bi Kai<kai.bi@yoho.cn>
 * @date: 2016/05/09
 */
'use strict';
const _ = require('lodash');
const passport = require('passport');

const uuid = require('uuid');
const url = require('url');
const moment = require('moment');
const cookie = global.yoho.cookie;
const helpers = global.yoho.helpers;
const log = global.yoho.logger;
const config = global.yoho.config;
const cache = global.yoho.cache;
const utils = require(global.utils);
const AuthHelperModel = require('../models/auth-helper');
const thirdAccount = require('../data/third-account.json');
const loginPage = `${config.siteUrl}/signin.html`;
const FROM = require('../../../config/from');

function doPassportCallback(openId, nickname, sourceType, req, res) {
    let shoppingKey = cookie.getShoppingKey(req);
    let refer = req.cookies.refer;
    let from = req.cookies.from || 'yohobuy';

    if (refer) {
        refer = decodeURI(req.cookies.refer);
    } else {
        refer = `${config.siteUrl}/home`;
    }

    if (/signin|login/.test(refer)) {
        refer = `${config.siteUrl}/home`;
    }

    refer = utils.refererLimit(refer);

    if (openId && nickname) {
        return req.ctx(AuthHelperModel).signinByOpenID({
            nickname, openId, sourceType, shoppingKey, from
        }).then((result) => {
            if (result.code !== 200) {
                return Promise.reject(result);
            }
            if (result.data['is_bind'] && result.data['is_bind'] === 'N') { //eslint-disable-line
                return helpers.urlFormat('/passport/bind/index', {
                    openId: openId,
                    sourceType: sourceType,
                    nickname: nickname,
                    refer: refer
                });
            } else if (result.code === 200 && result.data.uid) {
                return req.ctx(AuthHelperModel).syncUserSession(result.data.uid, req, res, result.data.session_key)
                    .then((authData) => {
                        return _.get(authData, 'refer') || refer;
                    });
            }
        }).then((redirectTo) => {
            return res.redirect(redirectTo);
        });
    } else {
        log.error(`missing third party login openId or nickname, url:${req.url}`);
        return res.redirect(loginPage);
    }
}

const common = {
    // 第三方登录有货逻辑
    thirdLogin(req, res, next) {
        let refer = req.get('referer');
        let thirdRefer = req.cookies.third_refer;

        if (thirdRefer && !/signin|login|passport\/international/.test(refer)) {
            res.clearCookie('third_refer', {
                domain: 'yohobuy.com'
            });
        }

        // TODO 记录token并验证有效期或者实现oauth
        if (req.query.yh_type &&
            req.query.yh_sign &&
            req.query.yh_time &&
            req.query.yh_backurl) {
            let reqTime = moment(req.query.yh_time);
            let timeDiff = moment().diff(reqTime);

            if (!reqTime.isValid() ||
                timeDiff >= 1000 * 60 * 5 || // 如果服务器之间大于5分钟验证失败
                timeDiff < 0) {

                return res.json({
                    code: 401,
                    message: 'yh_time已过期或者格式错误'
                });
            }
            let account = thirdAccount[req.query.yh_type];

            if (!account) {
                return res.json({
                    code: 401,
                    message: 'yh_type验证失败'
                });
            }
            let backurl = url.parse(req.query.yh_backurl);
            let regDomain = new RegExp(`${account.domain.replace(/\./g, '\\.')}$`);

            if (!regDomain.test(backurl.host || '')) {
                return res.json({
                    code: 401,
                    message: 'yh_backurl回调域名验证失败'
                });
            }
            let signStr = req.ctx(AuthHelperModel).thirdSign(req.query, account.clientSecret);

            if (signStr.toLowerCase() !== req.query.yh_sign.toLowerCase()) {
                return res.json({
                    code: 401,
                    message: 'yh_sign签名验证错误'
                });
            }
            res.cookie('third_refer', refer, {
                domain: 'yohobuy.com'
            });
            res.cookie('third_type', req.query.yh_type, {
                domain: 'yohobuy.com'
            });
            res.cookie('third_backurl', req.query.yh_backurl, {
                domain: 'yohobuy.com'
            });

            req.query.from = req.query.yh_type;
        }
        next();
    },
    beforeLogin: (req, res, next) => {
        if (req.session.passwordWeak) {
            return res.redirect('/passport/password/resetpage');
        }

        let refer = req.query.refer;

        if (!refer) {
            refer = req.get('Referer') || req.cookies.refer;
        }

        refer = utils.refererLimit(refer);

        refer && !/signin|login|passport/.test(refer) && res.cookie('refer', encodeURI(refer), {
            domain: 'yohobuy.com'
        });

        let from = req.query.from;

        if (from && FROM[from]) {
            res.cookie('from', from, {
                domain: 'yohobuy.com',
                expires: new Date(Date.now() + 10 * 60 * 1000)
            });
        }

        if (req.yoho.isApp) {
            return next({
                code: 401,
                message: 'weblogin',
                refer
            });
        }
        next();
    },
    weixinCheck: (req, res, next) => {
        let passLogin = _.get(req, 'cookies._WX_PASS_LOGIN', false);

        if (req.yoho.isWechat && !passLogin) {
            return res.redirect(helpers.urlFormat('/passport/login/wechat', {
                refer: req.query.refer || req.get('Referer') || '/',
                from: req.query.from
            }));
        }
        next();
    },
    wechatQuickLoginCheck: (req, res, next) => {
        let refer = req.query.refer;

        // 仅yoluck业务展示快捷登陆引导页
        if (req.yoho.isWechat && refer && refer.indexOf('activity/yoluck') > 0) {
            _.assign(res.locals, {
                wechatQuickLoginRefer: encodeURIComponent(refer),
                useWechatQuickLogin: true
            });
        }

        next();
    },
    clearCookie: (req, res, next) => {
        res.clearCookie('_SESSION_KEY', {
            domain: 'yohobuy.com'
        });
        res.clearCookie('_UID', {
            domain: 'yohobuy.com'
        });
        res.clearCookie('_TOKEN', {
            domain: 'yohobuy.com'
        });

        if (req.session2 && req.session2.reset) {
            req.session2.reset();
        }

        if (req.session && req.session.regenerate && req.sessionStore) {
            return req.session.regenerate(() => {
                return next();
            });
        } else {
            return next();
        }

        // if (req.session) {
        //     delete req.session.SESSION_KEY;
        //     delete req.session.AVATAR;
        //     delete req.session.USER;
        //     delete req.session.TOKEN;
        //     delete req.session.LOGIN_UID_;
        // }
    },
    isLoginUser: (req, res, next) => {
        // 微信里边已经登录的时候,不再跳转登录
        if (req.user.uid) {
            req.ctx(AuthHelperModel).profile(req.user.uid).then(function(result) {
                if (result.code !== 200) {
                    return next();
                }
                let refer = req.query.refer || decodeURI(req.cookies.refer) || config.siteUrl;

                if (/sign|login/.test(refer)) {
                    refer = `${config.siteUrl}/home`;
                }

                refer = utils.refererLimit(refer);
                return res.redirect(refer);
            }).catch(() => {
                return next();
            });
        } else {
            return next();
        }
    },
    check: (req, res, next) => {
        let refer = req.query.refer;

        // 短信推广的链接强制检查登录
        if (req.user.uid) {
            req.ctx(AuthHelperModel).profile(req.user.uid).then(function(result) {
                if (result && result.code === 200) {
                    return res.redirect(refer);
                }

                return res.redirect(helpers.urlFormat('/signin.html', {
                    refer: refer
                }));
            }).catch(() => {
                return res.redirect(helpers.urlFormat('/signin.html', {
                    refer: refer
                }));
            });
        } else {
            return res.redirect(helpers.urlFormat('/signin.html', {
                refer: refer
            }));
        }
    }
};


const local = {
    login: (req, res, next) => {
        // 是否关闭账号登录
        let closePassword = _.get(req.app.locals.wap, 'close.passwordLogin', false);

        if (closePassword) {
            return res.json({
                code: 403,
                message: '请使用快速登录'
            });
        }

        passport.authenticate('local', (err, user) => {
            if (err || !user) {
                if (_.get(err, 'code') === 4189) {
                    let obj = {
                        code: 4189,
                        message: err || '登录出错请重试',
                        url: '//m.yohobuy.com/passport/sms_login'
                    };

                    return res.json(obj);
                } else if (_.get(err, 'code', 400) === 50004) {
                    // 强制绑定手机号需要邮箱和密码
                    req.session.bindEmail = req.body.account;
                    req.session.bindPassword = req.body.password;
                    return res.json(Object.assign(err, {
                        url: '//m.yohobuy.com/passport/bind/forceBindMobile'
                    }));
                } else {
                    let obj = {
                        code: 400,
                        message: err || '登录出错请重试',
                        data: '',
                        captchaShow: true
                    };

                    cache.set(`loginErrorIp:${req.yoho.clientIp}`, true, 3600 * 24).catch(log.error);
                    return res.json(obj);
                }
            } else {
                let refer = req.cookies.refer;

                if (refer) {
                    refer = decodeURI(req.cookies.refer);
                } else {
                    refer = `${config.siteUrl}/home`;
                }

                if (/sign|login/.test(refer)) {
                    refer = `${config.siteUrl}/home`;
                }

                refer = utils.refererLimit(refer);

                user.session = refer;
                user.href = refer;
                res.cookie('_LOGIN_TYPE', 0, {
                    domain: 'm.yohobuy.com'
                });

                // 弱密码返回数据
                let passwordWeakReturn;

                if (user.weakPassword) {
                    req.session.passwordWeak = user;
                    passwordWeakReturn = {
                        code: 510,
                        url: '/passport/password/resetpage',
                        pwdTip: _.get(user, 'pwdTip', '密码应为6-20位字母、数字的组合'),
                        uid: _.get(user, 'uid', '')
                    };
                }

                // 不可以跳过,不登录用户
                if (user.weakPassword && user.canSkip !== 'Y') {
                    return res.json(passwordWeakReturn);
                }

                req.ctx(AuthHelperModel).syncUserSession(user.uid, req, res, user.session_key).then((authData) => {
                    if (user.weakPassword) {
                        return res.json(passwordWeakReturn);
                    } else {
                        user.href = _.get(authData, 'refer', user.href);
                        res.json({
                            code: 200,
                            data: user
                        });
                    }
                }).catch(next);
            }
        })(req, res, next);
    },
    logout: (req, res) => {
        res.clearCookie('_SPK');
        res.cookie('_WX_PASS_LOGIN', true, {
            domain: 'm.yohobuy.com'
        });
        let refer = req.get('Referer') || config.siteUrl;

        refer = utils.refererLimit(refer);
        res.redirect(refer);
    }
};

const wechat = {
    login: (req, res, next) => {
        // 设置为原链接标识originalUrl
        req.session.originalUrl = 'true';
        req.session.authState = uuid.v4();
        res.clearCookie('_WX_PASS_LOGIN', {
            domain: 'm.yohobuy.com'
        });
        return passport.authenticate('weixin', {
            state: req.session.authState
        })(req, res, next);
    },
    callback: (req, res, next) => {
        if (req.session && req.session.authState && req.session.authState === req.query.state) {
            passport.authenticate('weixin', (err, user) => {
                if (err || !user) {
                    log.error(`wechat authenticate error : ${JSON.stringify(err)}`);
                    return res.redirect(loginPage);
                }
                let nickname = user._json.nickname || user.displayName;
                let openId = user._json.unionid || user.id;

                res.cookie('_WX_OPENID', _.get(user, '_json.openid'), {
                    domain: 'm.yohobuy.com'
                });
                res.cookie('_WX_UNIONID', _.get(user, '_json.unionid'), {
                    domain: 'm.yohobuy.com'
                });
                res.cookie('_LOGIN_TYPE', 4, {
                    domain: 'm.yohobuy.com'
                });
                doPassportCallback(openId, nickname, 'wechat', req, res).catch(next);
            })(req, res, next);
        } else {
            log.error('Auth State Mismatch:' + req.originalUrl);
            return res.redirect(loginPage);
        }
    },
    redirect: (req, res, next) => {
        const redirectUrl = req.query.redirectUrl;

        passport.authenticate('weixin', (err, user) => {
            if (err || !user) {
                log.error(`wechat authenticate error : ${JSON.stringify(err)}`);
                return res.json({
                    message: 'wechat authenticate error.'
                });
            }
            let nickname = user._json.nickname || user.displayName;
            let openId = user._json.unionid || user.id;
            let headImg = user._json.headimgurl || user.profileUrl;

            return res.status(302).redirect(
                `${redirectUrl}?openId=${openId}&nickname=${nickname}&headImg=${encodeURIComponent(headImg)}`);
        })(req, res, next);

    }
};

const sina = {
    login: (req, res, next) => {
        // 设置为原链接标识originalUrl
        req.session.originalUrl = 'true';
        req.session.authState = uuid.v4();
        return passport.authenticate('sina', {
            state: req.session.authState
        })(req, res, next);
    },
    callback: (req, res, next) => {
        if (req.session && req.session.authState && req.session.authState === req.query.state) {
            passport.authenticate('sina', (err, user) => {
                if (err || !user) {
                    log.error(`sina authenticate error : ${JSON.stringify(err)}`);
                    return res.redirect(loginPage);
                }
                let nickname = user.screen_name;
                let openId = user.id;

                res.cookie('_LOGIN_TYPE', 2, {
                    domain: 'm.yohobuy.com'
                });
                doPassportCallback(openId, nickname, 'sina', req, res).catch(next);
            })(req, res, next);
        } else {
            log.error('Auth State Mismatch:' + req.originalUrl);
            return res.redirect(loginPage);
        }
    },
    redirect: (req, res, next) => {
        const redirectUrl = req.query.redirectUrl;

        passport.authenticate('sina', (err, user) => {
            if (err || !user) {
                log.error(`sina authenticate error : ${JSON.stringify(err)}`);
                return res.json({
                    message: 'sina authenticate error.'
                });
            }
            let nickname = user.screen_name;
            let openId = user.id;
            let headImg = user._json.avatar_large || user.profile_image_url;

            return res.status(302).redirect(
                `${redirectUrl}?openId=${openId}&nickname=${nickname}&headImg=${encodeURIComponent(headImg)}`);
        })(req, res, next);
    }
};

const qq = {
    login: (req, res, next) => {
        // 设置为原链接标识originalUrl
        req.session.originalUrl = 'true';
        req.session.authState = uuid.v4();
        return passport.authenticate('qq', {
            state: req.session.authState
        })(req, res, next);
    },
    callback: (req, res, next) => {
        if (req.session && req.session.authState && req.session.authState === req.query.state) {
            passport.authenticate('qq', (err, user) => {
                if (err) {
                    log.error(`qq authenticate error : ${JSON.stringify(err)}`);
                    return res.redirect(loginPage);
                }

                let nickname = user.nickname;
                let openId = user.id;

                res.cookie('_LOGIN_TYPE', 1, {
                    domain: 'm.yohobuy.com'
                });
                doPassportCallback(openId, nickname, 'qq', req, res).catch(next);
            })(req, res, next);
        } else {
            log.error('Auth State Mismatch:' + req.originalUrl);
            return res.redirect(loginPage);
        }
    }
};

const alipay = {
    login: (req, res, next) => {
        // 设置为原链接标识originalUrl
        req.session.originalUrl = 'true';
        return passport.authenticate('alipay')(req, res, next);
    },
    callback: (req, res, next) => {
        passport.authenticate('alipay', (err, user) => {
            if (err || !user) {
                log.error(`alipay authenticate error : ${JSON.stringify(err)}`);
                return res.redirect(loginPage);
            }
            let nickname = user.realName;
            let openId = user.userId;

            res.cookie('_LOGIN_TYPE', 3, {
                domain: 'm.yohobuy.com'
            });
            doPassportCallback(openId, nickname, 'alipay', req, res).catch(next);
        })(req, res, next);
    }
};

exports.user = function(req, res, next) {
    let result = {
        code: 403,
        message: '未登录',
        data: ''
    };

    if (req.user.uid) {
        result.code = 200;
        result.message = '已登录';
        result.data = req.user.uid.toString();
    }
    res.jsonp(result);
};

exports.common = common;
exports.local = local;
exports.wechat = wechat;
exports.sina = sina;
exports.qq = qq;
exports.alipay = alipay;