1
0
forked from a/lifeto-shop
lifeto-shop/src/lib/session.ts

126 lines
3.3 KiB
TypeScript
Raw Normal View History

2022-07-01 01:27:18 +00:00
import axios from "axios";
import qs from "qs";
import { getCookie, removeCookie } from "typescript-cookie";
export interface Session {
user:string
xsrf:string
csrf:string
lto:string
}
export const API_ROOT = "/lifeto/"
const endpoint = (name:string)=>{
return API_ROOT + name
}
export class LoginHelper {
user:string
pass:string
csrf?:string
constructor(user:string, pass:string){
this.user = user;
this.pass = pass;
}
login = async ():Promise<TokenSession> =>{
removeCookie("XSRF-TOKEN")
removeCookie("lifeto_session", {path:'/'})
await sleep(1000)
return axios.get(endpoint("login"),{withCredentials:false})
.then(async (x)=>{
console.log(x)
if(x.data){
try{
this.csrf = x.data.split("csrf-token")[1].split('\">')[0].replace("\" content=\"",'')
}catch(e){
}
}
return axios.post(endpoint("login"),{
login:this.user,
password:this.pass,
redirectTo:"lifeto"
},{withCredentials:false})
.then(async (x)=>{
await sleep(100)
let xsrf= getCookie("XSRF-TOKEN")
let lifeto = getCookie("lifeto_session")
return new TokenSession(this.user,this.csrf!, xsrf!, lifeto!)
})
})
}
}
const sleep= async(ms:number)=> {
return new Promise(resolve => setTimeout(resolve, ms))
}
export class TokenSession {
csrf:string
xsrf:string
lto:string
user:string
constructor(name:string, csrf:string, xsrf: string, lifeto:string){
this.user = name
this.csrf = csrf
this.xsrf = xsrf;
this.lto = lifeto;
}
authed_request = async (verb:string,url:string,data:any) => {
let promise
switch (verb){
case "post":
promise = axios.post(endpoint(url),data,this.genHeaders())
break;
case "postraw":
const querystring = qs.stringify(data)
promise = axios.post(endpoint(url),querystring,this.genHeaders())
break;
case "get":
default:
promise = axios.get(endpoint(url),this.genHeaders())
}
return promise.then(x=>{
if(x.data){
try{
this.xsrf = x.data.split("xsrf-token")[1].split('\">')[0].replace("\" content=\"",'')
}catch(e){
}
}
if(x.headers['set-cookie']){
const cookies = x.headers['set-cookie'].map((y)=>{
return y.split("=")[1].split(";")[0];
})
this.xsrf = cookies[0]
this.lto = cookies[1]
}
return x
})
}
genHeaders = ()=>{
const out = {
headers:{
Cookie:`XSRF-TOKEN=${this.xsrf}; lifeto_session=${this.lto}`,
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
Connection: "keep-alive",
"X-Requested-With":"XMLHttpRequest",
Host: "beta.lifeto.co",
"Alt-Used": "beta.lifeto.co",
"Update-Insecure-Requests": 1,
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0",
"Sec-Fetch-Mode":"navigate",
"Sec-Fetch-Dest":"document",
"Sec-Fetch-Site":"same-origin",
"Sec-Fetch-User":"?1",
"TE":"trailers"
},
withCredentials:true
}
if(this.xsrf){
(out.headers as any)["X-XSRF-TOKEN"] = this.xsrf.replace("%3D","=")
}
return out
}
}