更新cookie管理添加cookie逻辑

This commit is contained in:
whyour 2021-03-17 00:35:14 +08:00
parent 7f7d4d4f24
commit 8526a57caf
5 changed files with 112 additions and 116 deletions

View File

@ -16,10 +16,10 @@ export default (app: Router) => {
try { try {
if (req) { if (req) {
const cookieService = Container.get(CookieService); const cookieService = Container.get(CookieService);
const { shici } = await cookieService.getYiYan(); const { qrurl } = await cookieService.getQrUrl();
return res.status(200).json({ code: 200, data: shici }); return res.send({ code: 200, qrcode: qrurl });
} else { } else {
return res.status(200).json({ err: 1, msg: 'loginFaild' }); return res.send({ code: 1, msg: 'loginFaild' });
} }
} catch (e) { } catch (e) {
logger.error('🔥 error: %o', e); logger.error('🔥 error: %o', e);

View File

@ -3,7 +3,8 @@ import winston from 'winston';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import { getFileContentByName } from '../config/util'; import { getFileContentByName } from '../config/util';
import config from '../config'; import config from '../config';
import FormData from 'form-data'; import * as fs from 'fs';
import got from 'got';
enum Status { enum Status {
'正常', '正常',
@ -22,8 +23,10 @@ export default class CookieService {
private token: string = ''; private token: string = '';
constructor(@Inject('logger') private logger: winston.Logger) {} constructor(@Inject('logger') private logger: winston.Logger) {}
public async getYiYan(): Promise<any> { public async getQrUrl(): Promise<{ qrurl: string }> {
return { yiYan: 'test' }; await this.step1();
const qrurl = await this.step2();
return { qrurl };
} }
private async step1() { private async step1() {
@ -49,17 +52,18 @@ export default class CookieService {
Host: 'plogin.m.jd.com', Host: 'plogin.m.jd.com',
}, },
}); });
this.praseSetCookies(text); await this.praseSetCookies(text);
} catch (error) { } catch (error) {
this.logger.error(error.response.body); this.logger.error(error);
} }
} }
private async step2() { private async step2() {
try { try {
if (this.cookies == '') { if (this.cookies == '') {
return 0; return '';
} }
console.log(this.cookies);
let timeStamp = new Date().getTime(); let timeStamp = new Date().getTime();
let url = let url =
'https://plogin.m.jd.com/cgi-bin/m/tmauthreflogurl?s_token=' + 'https://plogin.m.jd.com/cgi-bin/m/tmauthreflogurl?s_token=' +
@ -67,7 +71,7 @@ export default class CookieService {
'&v=' + '&v=' +
timeStamp + timeStamp +
'&remember=true'; '&remember=true';
const response = await fetch(url, { const response: any = await fetch(url, {
method: 'post', method: 'post',
body: JSON.stringify({ body: JSON.stringify({
lang: 'chs', lang: 'chs',
@ -91,37 +95,28 @@ export default class CookieService {
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36',
Host: 'plogin.m.jd.com', Host: 'plogin.m.jd.com',
}, },
}).then((res) => res.json); });
// this.token = response.body.token const body = await response.json();
// this.okl_token = response.headers['set-cookie'][0] this.token = body.token;
// this.okl_token = this.okl_token.substring(this.okl_token.indexOf("=") + 1, this.okl_token.indexOf(";")) const setCookies = response.headers.get('set-cookie');
this.okl_token = setCookies.match(/okl_token=(.+?);/)[1];
var qrUrl = var qrUrl =
'https://plogin.m.jd.com/cgi-bin/m/tmauth?appid=300&client_type=m&token=' + 'https://plogin.m.jd.com/cgi-bin/m/tmauth?appid=300&client_type=m&token=' +
this.token; this.token;
return qrUrl; return qrUrl;
} catch (error) { } catch (error) {
console.log(error.response.body); console.log(error.response.body);
return 0; return '';
} }
} }
private praseSetCookies(response: any) { private async praseSetCookies(response: any) {
this.s_token = response.body.s_token; const body = await response.json();
this.guid = response.headers['set-cookie'][0]; this.s_token = body.s_token;
this.guid = this.guid.substring( const setCookies = response.headers.get('set-cookie');
this.guid.indexOf('=') + 1, this.guid = setCookies.match(/guid=(.+?);/)[1];
this.guid.indexOf(';'), this.lsid = setCookies.match(/lsid=(.+?);/)[1];
); this.lstoken = setCookies.match(/lstoken=(.+?);/)[1];
this.lsid = response.headers['set-cookie'][2];
this.lsid = this.lsid.substring(
this.lsid.indexOf('=') + 1,
this.lsid.indexOf(';'),
);
this.lstoken = response.headers['set-cookie'][3];
this.lstoken = this.lstoken.substring(
this.lstoken.indexOf('=') + 1,
this.lstoken.indexOf(';'),
);
this.cookies = this.cookies =
'guid=' + 'guid=' +
this.guid + this.guid +
@ -133,26 +128,14 @@ export default class CookieService {
} }
private getCookie(response: any) { private getCookie(response: any) {
var TrackerID = response.headers['set-cookie'][0]; const setCookies = response.headers['set-cookie'];
TrackerID = TrackerID.substring( var TrackerID = setCookies[0].match(/TrackerID=(.+?);/)[1];
TrackerID.indexOf('=') + 1, var pt_key = setCookies[1].match(/pt_key=(.+?);/)[1];
TrackerID.indexOf(';'), var pt_pin = setCookies[2].match(/pt_pin=(.+?);/)[1];
); var pt_token = setCookies[3].match(/pt_token=(.+?);/)[1];
var pt_key = response.headers['set-cookie'][1]; var pwdt_id = setCookies[4].match(/pwdt_id=(.+?);/)[1];
pt_key = pt_key.substring(pt_key.indexOf('=') + 1, pt_key.indexOf(';')); var s_key = setCookies[5].match(/s_key=(.+?);/)[1];
var pt_pin = response.headers['set-cookie'][2]; var s_pin = setCookies[6].match(/s_pin=(.+?);/)[1];
pt_pin = pt_pin.substring(pt_pin.indexOf('=') + 1, pt_pin.indexOf(';'));
var pt_token = response.headers['set-cookie'][3];
pt_token = pt_token.substring(
pt_token.indexOf('=') + 1,
pt_token.indexOf(';'),
);
var pwdt_id = response.headers['set-cookie'][4];
pwdt_id = pwdt_id.substring(pwdt_id.indexOf('=') + 1, pwdt_id.indexOf(';'));
var s_key = response.headers['set-cookie'][5];
s_key = s_key.substring(s_key.indexOf('=') + 1, s_key.indexOf(';'));
var s_pin = response.headers['set-cookie'][6];
s_pin = s_pin.substring(s_pin.indexOf('=') + 1, s_pin.indexOf(';'));
this.cookies = this.cookies =
'TrackerID=' + 'TrackerID=' +
TrackerID + TrackerID +
@ -177,19 +160,29 @@ export default class CookieService {
} }
public async addCookie() { public async addCookie() {
const cookie: any = await this.checkLogin(); const res: any = await this.checkLogin();
if (cookie.body.errcode == 0) { if (res.body.errcode === 0) {
let ucookie = this.getCookie(cookie); let ucookie = this.getCookie(res);
return ucookie; let content = getFileContentByName(config.confFile);
const regx = /.*Cookie[0-9]{1}\=\"(.+?)\"/g;
const lastCookie = (content.match(regx) as any[]).pop();
const cookieRegx = /Cookie([0-9]+)\=.+?/.exec(lastCookie);
if (cookieRegx) {
const num = parseInt(cookieRegx[1]) + 1;
const newCookie = `${lastCookie}\nCookie${num}="${ucookie}"`;
const result = content.replace(lastCookie, newCookie);
fs.writeFileSync(config.confFile, result);
}
return { cookie: ucookie };
} else { } else {
return ''; return res.body;
} }
} }
private async checkLogin() { private async checkLogin() {
try { try {
if (this.cookies == '') { if (this.cookies == '') {
return 0; return '';
} }
let timeStamp = new Date().getTime(); let timeStamp = new Date().getTime();
let url = let url =
@ -197,20 +190,15 @@ export default class CookieService {
this.token + this.token +
'&ou_state=0&okl_token=' + '&ou_state=0&okl_token=' +
this.okl_token; this.okl_token;
let payload = { return got.post(url, {
lang: 'chs', responseType: 'json',
appid: 300, form: {
returnurl: lang: 'chs',
'https://wqlogin2.jd.com/passport/LoginRedirect?state=1100399130787&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action', appid: 300,
source: 'wq_passport', returnurl:
}; 'https://wqlogin2.jd.com/passport/LoginRedirect?state=1100399130787&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action',
let form = new FormData(); source: 'wq_passport',
for (const key in payload) { },
form.append(key, (payload as any)[key] as any);
}
const response = await fetch(url, {
method: 'post',
body: form,
headers: { headers: {
Referer: Referer:
'https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wqlogin2.jd.com/passport/LoginRedirect?state=' + 'https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wqlogin2.jd.com/passport/LoginRedirect?state=' +
@ -224,10 +212,8 @@ export default class CookieService {
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36',
}, },
}); });
return response;
} catch (error) { } catch (error) {
console.log(error.response.body); console.log(error);
let res: any = {}; let res: any = {};
res.body = { check_ip: 0, errcode: 222, message: '出错' }; res.body = { check_ip: 0, errcode: 222, message: '出错' };
res.headers = {}; res.headers = {};
@ -278,10 +264,7 @@ export default class CookieService {
}, },
}, },
) )
.then((x) => { .then((x) => x.json())
console.log(x);
return x.json();
})
.then((x) => { .then((x) => {
console.log(x.data.userInfo); console.log(x.data.userInfo);
if (x.retcode === '0' && x.data && x.data.userInfo) { if (x.retcode === '0' && x.data && x.data.userInfo) {

View File

@ -40,6 +40,7 @@
"express-basic-auth": "^1.2.0", "express-basic-auth": "^1.2.0",
"express-jwt": "^6.0.0", "express-jwt": "^6.0.0",
"form-data": "^4.0.0", "form-data": "^4.0.0",
"got": "^11.8.2",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"lodash": "^4.17.20", "lodash": "^4.17.20",
"mailgun-js": "^0.22.0", "mailgun-js": "^0.22.0",

View File

@ -70,19 +70,24 @@ const Config = () => {
const getCookie = async (modal: { destroy: () => void }) => { const getCookie = async (modal: { destroy: () => void }) => {
for (let i = 0; i < 50; i++) { for (let i = 0; i < 50; i++) {
const result = await request.get(`${config.apiPrefix}cookie`); const {
console.log(i, result); data: { cookie, errcode, message },
if (result && result.cookie) { } = await request.get(`${config.apiPrefix}cookie`);
if (cookie) {
notification.success({ notification.success({
message: 'Cookie获取成功', message: 'Cookie获取成功',
}); });
modal.destroy(); modal.destroy();
Modal.success({ Modal.success({
title: '获取Cookie成功', title: '获取Cookie成功',
content: <div>{result.cookie}</div>, content: <div>{cookie}</div>,
}); });
break; break;
} }
if (errcode !== 176) {
notification.error({ message });
break;
}
await sleep(2000); await sleep(2000);
} }
}; };
@ -109,9 +114,6 @@ const Config = () => {
<Button key="1" type="primary" onClick={updateConfig}> <Button key="1" type="primary" onClick={updateConfig}>
</Button>, </Button>,
<Button key="2" type="primary" onClick={showQrCode}>
Cookie
</Button>,
]} ]}
header={{ header={{
style: { style: {

View File

@ -21,7 +21,7 @@ const columns = [
title: '用户名', title: '用户名',
dataIndex: 'pin', dataIndex: 'pin',
key: 'pin', key: 'pin',
align: 'center', align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return <span>{decodeURIComponent(text)}</span>; return <span>{decodeURIComponent(text)}</span>;
}, },
@ -30,13 +30,13 @@ const columns = [
title: '昵称', title: '昵称',
dataIndex: 'nickname', dataIndex: 'nickname',
key: 'nickname', key: 'nickname',
align: 'center', align: 'center' as const,
}, },
{ {
title: '值', title: '值',
dataIndex: 'cookie', dataIndex: 'cookie',
key: 'cookie', key: 'cookie',
align: 'center', align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return ( return (
<span <span
@ -55,7 +55,7 @@ const columns = [
title: '状态', title: '状态',
key: 'status', key: 'status',
dataIndex: 'status', dataIndex: 'status',
align: 'center', align: 'center' as const,
render: (text: string, record: any) => { render: (text: string, record: any) => {
return ( return (
<Space size="middle"> <Space size="middle">
@ -111,47 +111,57 @@ const Config = () => {
const showQrCode = () => { const showQrCode = () => {
request.get(`${config.apiPrefix}qrcode`).then(async (data) => { request.get(`${config.apiPrefix}qrcode`).then(async (data) => {
const modal = Modal.info({ if (data.qrcode) {
title: '二维码', const modal = Modal.info({
content: ( title: '二维码',
<div content: (
style={{ <div
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
marginLeft: -38,
}}
>
<QRCode
style={{ style={{
width: 200, display: 'flex',
height: 200, flexDirection: 'column',
marginBottom: 10, alignItems: 'center',
marginTop: 20, marginLeft: -38,
}} }}
value={data.qrcode} >
/> <QRCode
</div> style={{
), width: 200,
}); height: 200,
getCookie(modal); marginBottom: 10,
marginTop: 20,
}}
value={data.qrcode}
/>
</div>
),
});
getCookie(modal);
} else {
notification.error({ message: '获取二维码失败' });
}
}); });
}; };
const getCookie = async (modal: { destroy: () => void }) => { const getCookie = async (modal: { destroy: () => void }) => {
for (let i = 0; i < 50; i++) { for (let i = 0; i < 50; i++) {
const result = await request.get(`${config.apiPrefix}cookie`); const {
if (result && result.cookie) { data: { cookie, errcode, message },
} = await request.get(`${config.apiPrefix}cookie`);
if (cookie) {
notification.success({ notification.success({
message: 'Cookie获取成功', message: 'Cookie获取成功',
}); });
modal.destroy(); modal.destroy();
Modal.success({ Modal.success({
title: '获取Cookie成功', title: '获取Cookie成功',
content: <div>{result.cookie}</div>, content: <div>{cookie}</div>,
}); });
break; break;
} }
if (errcode !== 176) {
notification.error({ message });
break;
}
await sleep(2000); await sleep(2000);
} }
}; };
@ -199,7 +209,7 @@ const Config = () => {
columns={columns} columns={columns}
pagination={{ hideOnSinglePage: true }} pagination={{ hideOnSinglePage: true }}
dataSource={value} dataSource={value}
rowKey="value" rowKey="pin"
size="middle" size="middle"
bordered bordered
/> />