- Manage multiple login, in different browsers... Multi Token...

- visualization of the Connection State (Online, Offline) using fetch.
This commit is contained in:
Paolo Arena
2019-02-09 18:04:49 +01:00
parent b65d0a2386
commit 4d5cea1c17
20 changed files with 393 additions and 209 deletions

View File

@@ -16,18 +16,21 @@ async function sendRequest(url: string, lang: string, mytok: string, method: str
configInit = {
method: method,
cache: 'no-cache',
mode: 'cors',
headers: authHeader
}
} else if (method === 'DELETE') {
configInit = {
method: method,
cache: 'no-cache',
mode: 'cors',
headers: authHeader
}
} else {
configInit = {
method: method,
cache: 'no-cache',
mode: 'cors',
body: JSON.stringify(mydata),
headers: authHeader
}

View File

@@ -9,8 +9,10 @@ export { addAuthHeaders, removeAuthHeaders, API_URL } from './Instance'
import Paths from '@paths'
import { rescodes } from '@src/store/Modules/rescodes'
import { UserStore } from '@modules'
import { GlobalStore, UserStore } from '@modules'
import globalroutines from './../../globalroutines/index'
import { serv_constants } from '@src/store/Modules/serv_constants'
import router from '@router'
// const algoliaApi = new AlgoliaSearch()
@@ -45,53 +47,68 @@ export namespace ApiTool {
})
}
export async function SendReq(url: string, lang: string, mytok: string, method: string, mydata: any, noAuth: boolean = false) {
export async function SendReq(url: string, lang: string, mytok: string, method: string, mydata: any, setAuthToken: boolean = false) {
UserStore.mutations.setServerCode(rescodes.EMPTY)
UserStore.mutations.setResStatus(0)
UserStore.mutations.setAuth('')
return await new Promise(function (resolve, reject) {
let ricevuto = false
sendRequest(url, lang, mytok, method, mydata)
return sendRequest(url, lang, mytok, method, mydata)
.then(resreceived => {
console.log('resreceived', resreceived)
ricevuto = true
let res = resreceived.clone()
if (process.env.DEV) {
console.log('SendReq RES [', res.status, ']', res)
}
let x_auth_token = ''
UserStore.mutations.setResStatus(res.status)
if (res.status === 200) {
let x_auth_token = ''
try {
if (!noAuth) {
if (setAuthToken) {
x_auth_token = String(res.headers.get('x-auth'))
if (x_auth_token === '') {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
}
UserStore.mutations.setAuth(x_auth_token)
if (url === process.env.MONGODB_HOST + '/updatepwd') {
UserStore.mutations.UpdatePwd({ idToken: x_auth_token })
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
}
if (x_auth_token === '') {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
}
}
UserStore.mutations.setServerCode(rescodes.OK)
UserStore.mutations.setAuth(x_auth_token)
} catch (e) {
if (!noAuth) {
if (setAuthToken) {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setAuth(x_auth_token)
UserStore.mutations.setAuth('')
}
return reject(e)
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
return reject({ code: rescodes.ERR_AUTHENTICATION, status: res.status })
}
} else if (res.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
// Forbidden
// You probably is connectiong with other page...
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setAuth('')
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
router.push('/signin')
return reject({ code: rescodes.ERR_AUTHENTICATION, status: res.status })
}
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
return res.json()
.then((body) => {
return resolve({ res, body })
})
.catch(e => {
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
return reject(e)
return reject({ code: rescodes.ERR_GENERICO, status: res.status })
})
})
@@ -104,7 +121,10 @@ export namespace ApiTool {
} else {
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
}
return reject(error)
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
return reject({ code: error, status: 0 })
})
})
}
@@ -129,50 +149,56 @@ export namespace ApiTool {
headers.append('Accept', 'application/json')
headers.append('x-auth', token)
console.log('A1) INIZIO.............................................................')
// console.log('A1) INIZIO.............................................................')
await globalroutines(null, 'readall', table, null)
.then(function (alldata) {
const myrecs = [...alldata]
console.log('----------------------- LEGGO QUALCOSA ')
if (myrecs) {
for (let rec of myrecs) {
// console.log('syncing', table, '', rec.descr)
let link = process.env.MONGODB_HOST + '/todos'
const myrecs = [...alldata]
// console.log('----------------------- LEGGO QUALCOSA ')
if (myrecs) {
for (let rec of myrecs) {
// console.log('syncing', table, '', rec.descr)
let link = process.env.MONGODB_HOST + '/todos'
if (method !== 'POST')
link += '/' + rec._id
if (method !== 'POST')
link += '/' + rec._id
console.log(' [Alternative] ++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:')
console.log(' [Alternative] ++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:')
// Insert/Delete/Update table to the server
fetch(link, {
method: method,
headers: headers,
mode: 'cors', // 'no-cors',
body: JSON.stringify(rec)
})
.then(function (resData) {
// console.log('Result CALL ', method, ' OK? =', resData.ok);
let lettoqualcosa = false
// Anyway Delete this, otherwise in some cases will return error, but it's not a problem.
// for example if I change a record and then I deleted ...
// if (resData.ok) {
// deleteItemFromData(table, rec._id);
globalroutines(null, 'delete', table, null, rec._id)
console.log('DELETE: ', mystrparam)
// deleteItemFromData('swmsg', mystrparam)
globalroutines(null, 'delete', 'swmsg', null, mystrparam)
// Insert/Delete/Update table to the server
return fetch(link, {
method: method,
headers: headers,
cache: 'no-cache',
mode: 'cors', // 'no-cors',
body: JSON.stringify(rec)
}).then(resData => {
lettoqualcosa = true
console.log('Clear', table, rec._id)
return globalroutines(null, 'delete', table, null, rec._id)
})
.catch(function (err) {
console.log(' [Alternative] !!!!!!!!!!!!!!! Error while sending data', err)
})
.then((ris) => {
console.log('Clear', 'swmsg', method)
GlobalStore.mutations.setStateConnection(lettoqualcosa ? 'online' : 'offline')
// deleteItemFromData('swmsg', mystrparam)
return globalroutines(null, 'delete', 'swmsg', null, mystrparam)
})
.catch(function (err) {
console.log(' [Alternative] !!!!!!!!!!!!!!! Error while sending data', err)
GlobalStore.mutations.setStateConnection(lettoqualcosa ? 'online' : 'offline')
})
}
}
}
).catch(e => {
console.log('ERROR:', e)
})
console.log(' [Alternative] A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!! err=')
}
}
}

View File

@@ -1,4 +1,4 @@
import { IGlobalState } from 'model'
import { IGlobalState, StateConnection } from 'model'
import { storeBuilder } from './Store/Store'
import Vue from 'vue'
@@ -8,7 +8,10 @@ import translate from './../../globalroutines/util'
import urlBase64ToUint8Array from '../../js/utility'
import messages from '../../statics/i18n'
import { UserStore } from "@store"
import { UserStore } from '@store'
import globalroutines from './../../globalroutines/index'
const allTables = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg']
const state: IGlobalState = {
conta: 0,
@@ -18,6 +21,7 @@ const state: IGlobalState = {
mobileMode: false,
menuCollapse: true,
leftDrawerOpen: true,
stateConnection: 'online',
category: 'personal',
posts: [],
listatodo: [
@@ -65,11 +69,18 @@ namespace Mutations {
state.category = cat
}
function setStateConnection(state: IGlobalState, stateconn: StateConnection) {
if (state.stateConnection !== stateconn) {
console.log('INTERNET ', stateconn)
state.stateConnection = stateconn
}
}
export const mutations = {
setConta: b.commit(setConta),
setleftDrawerOpen: b.commit(setleftDrawerOpen),
setCategorySel: b.commit(setCategorySel)
setCategorySel: b.commit(setCategorySel),
setStateConnection: b.commit(setStateConnection)
}
}
@@ -109,9 +120,10 @@ namespace Actions {
}
})
.then(function (newSub) {
// console.log('newSub', newSub)
if (newSub) {
saveNewSubscriptionToServer(context, newSub)
mystate.isSubscribed = true;
mystate.isSubscribed = true
}
return null
})
@@ -174,8 +186,17 @@ namespace Actions {
}
function loadAfterLogin (context) {
async function clearDataAfterLogout (context) {
// Clear all data from the IndexedDB
allTables.forEach(table => {
globalroutines(null, 'clearalldata', table, null)
})
}
async function loadAfterLogin (context) {
actions.clearDataAfterLogout()
}
@@ -183,6 +204,7 @@ namespace Actions {
setConta: b.dispatch(setConta),
createPushSubscription: b.dispatch(createPushSubscription),
loadAfterLogin: b.dispatch(loadAfterLogin),
clearDataAfterLogout: b.dispatch(clearDataAfterLogout),
prova: b.dispatch(prova)
}
@@ -202,4 +224,3 @@ const GlobalModule = {
export default GlobalModule

View File

@@ -6,6 +6,7 @@ import { rescodes } from './rescodes'
import { GlobalStore, Todos, UserStore } from '@store'
import globalroutines from './../../globalroutines/index'
import { Mutation } from "vuex-module-decorators"
import { serv_constants } from "@src/store/Modules/serv_constants"
const state: ITodosState = {
@@ -73,7 +74,7 @@ namespace Actions {
let something = false
if ('serviceWorker' in navigator) {
console.log(' -------- sendSwMsgIfAvailable')
// console.log(' -------- sendSwMsgIfAvailable')
let count = await checkPendingMsg(null)
if (count > 0) {
@@ -135,7 +136,7 @@ namespace Actions {
async function waitAndRefreshData(context) {
await aspettansec(3000)
console.log('waitAndRefreshData')
// console.log('waitAndRefreshData')
return await dbLoadTodo(context, false)
}
@@ -186,33 +187,38 @@ namespace Actions {
state.todos = [...body.todos]
Todos.mutations.setTodos_changed()
console.log('state.todos', state.todos, 'checkPending', checkPending)
console.log('********** resData', resData, 'state.todos', state.todos, 'checkPending', checkPending)
// After Login will store into the indexedDb...
return rescodes.OK
})
.catch((error) => {
console.log('error=', error)
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
console.log('fine della funz...')
console.log('ris FUNZ: ', ris.code, 'status', ris.status)
if (!Todos.state.networkDataReceived) {
console.log('NETWORK UNREACHABLE ! (Error in fetch)')
consolelogpao('NETWORK UNREACHABLE ! (Error in fetch)')
if (ris.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
consolelogpao('UNAUTHORIZING... TOKEN EXPIRED... !! ')
} else {
consolelogpao('NETWORK UNREACHABLE ! (Error in fetch)', UserStore.getters.getServerCode, ris.code)
}
// Read all data from IndexedDB Store into Memory
await updateArrayInMemory(context)
} else {
if (ris === rescodes.OK && checkPending) {
if (ris.code === rescodes.OK && checkPending) {
waitAndcheckPendingMsg(context)
}
}
}
async function updateArrayInMemory(context) {
console.log('Update the array in memory, from todos table from IndexedDb')
// console.log('Update the array in memory, from todos table from IndexedDb')
await globalroutines(null, 'updateinMemory', 'todos', null)
.then(() => {
// console.log('updateArrayInMemory! ')
@@ -246,8 +252,8 @@ namespace Actions {
}
function UpdateNewIdFromDB(oldItem, newItem, method) {
console.log('PRIMA state.todos', state.todos)
console.log('ITEM', newItem)
// console.log('PRIMA state.todos', state.todos)
// console.log('ITEM', newItem)
if (method === 'POST') {
state.todos.push(newItem)
Todos.mutations.setTodos_changed()
@@ -260,7 +266,7 @@ namespace Actions {
}
console.log('DOPO state.todos', state.todos)
// console.log('DOPO state.todos', state.todos)
}
async function dbInsertSaveTodo(context, itemtodo: ITodo, method) {
@@ -290,7 +296,7 @@ namespace Actions {
}
async function dbDeleteTodo(context, item: ITodo) {
console.log('dbDeleteTodo', item)
// console.log('dbDeleteTodo', item)
let call = process.env.MONGODB_HOST + '/todos/' + item._id
const token = UserStore.state.idToken

View File

@@ -121,6 +121,10 @@ namespace Mutations {
state.servercode = num
}
function setResStatus(state: IUserState, status: number) {
state.resStatus = status
}
function setAuth(state: IUserState, x_auth_token: string) {
state.x_auth_token = x_auth_token
}
@@ -168,6 +172,7 @@ namespace Mutations {
setlang: b.commit(setlang),
UpdatePwd: b.commit(UpdatePwd),
setServerCode: b.commit(setServerCode),
setResStatus: b.commit(setResStatus),
setAuth: b.commit(setAuth),
clearAuthData: b.commit(clearAuthData),
setErrorCatch: b.commit(setErrorCatch),
@@ -205,7 +210,7 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING)
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend, true)
.then(({ res, body }) => {
return { code: body.code, msg: body.msg }
})
@@ -259,7 +264,7 @@ namespace Actions {
// mutations.setServerCode(myres);
if (body.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) {
console.log('VERIFICATO !!')
localStorage.setItem(rescodes.localStorage.verifiedEmail, '1')
localStorage.setItem(rescodes.localStorage.verified_email, String(true))
} else {
console.log('Risultato di vreg: ', body.code)
}
@@ -326,7 +331,7 @@ namespace Actions {
localStorage.setItem(rescodes.localStorage.username, username)
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.verifiedEmail, '0')
localStorage.setItem(rescodes.localStorage.verified_email, String(false))
state.isLogged = true
// dispatch('storeUser', authData);
// dispatch('setLogoutTimer', myres.data.expiresIn);
@@ -363,7 +368,7 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING)
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend, true)
.then(({ res, body }) => {
myres = res
if (res.code === serv_constants.RIS_CODE_LOGIN_ERR) {
@@ -375,36 +380,41 @@ namespace Actions {
if (myres.status === 200) {
let myuser: IUserState = body.usertosend
let userId = myuser.userId
let username = authData.username
let verifiedEmail = myuser.verified_email === true
if (process.env.DEV) {
console.log('USERNAME = ' + username)
console.log('IDUSER= ' + userId)
Mutations.mutations.authUser({
userId: userId,
username: username,
idToken: state.x_auth_token,
verified_email: verifiedEmail
})
if (myuser) {
let userId = myuser.userId
let username = authData.username
let verified_email = myuser.verified_email
if (process.env.DEV) {
console.log('USERNAME = ' + username)
console.log('IDUSER= ' + userId)
console.log('state.x_auth_token= ' + state.x_auth_token)
Mutations.mutations.authUser({
userId,
username,
idToken: state.x_auth_token,
verified_email
})
}
const now = new Date()
// const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000);
const expirationDate = new Date(now.getTime() * 1000)
localStorage.setItem(rescodes.localStorage.userId, userId)
localStorage.setItem(rescodes.localStorage.username, username)
localStorage.setItem(rescodes.localStorage.token, state.x_auth_token)
localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.isLogged, String(true))
localStorage.setItem(rescodes.localStorage.verified_email, String(verified_email))
setGlobal()
// dispatch('storeUser', authData);
// dispatch('setLogoutTimer', myres.data.expiresIn);
return rescodes.OK
} else {
return rescodes.ERR_GENERICO
}
const now = new Date()
// const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000);
const expirationDate = new Date(now.getTime() * 1000)
localStorage.setItem(rescodes.localStorage.userId, userId)
localStorage.setItem(rescodes.localStorage.username, username)
localStorage.setItem(rescodes.localStorage.token, state.x_auth_token)
localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.isLogged, String(true))
localStorage.setItem(rescodes.localStorage.verifiedEmail, Number(verifiedEmail).toString())
setGlobal()
// dispatch('storeUser', authData);
// dispatch('setLogoutTimer', myres.data.expiresIn);
return rescodes.OK
} else if (myres.status === 404) {
} else if (myres.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
if (process.env.DEV) {
console.log('CODE = ' + body.code)
}
@@ -449,31 +459,35 @@ namespace Actions {
localStorage.removeItem(rescodes.localStorage.username)
localStorage.removeItem(rescodes.localStorage.isLogged)
// localStorage.removeItem(rescodes.localStorage.leftDrawerOpen)
localStorage.removeItem(rescodes.localStorage.verifiedEmail)
localStorage.removeItem(rescodes.localStorage.verified_email)
localStorage.removeItem(rescodes.localStorage.categorySel)
router.push('/signin')
GlobalStore.actions.clearDataAfterLogout()
// this.$router.push('/signin')
}
function setGlobal() {
async function setGlobal() {
state.isLogged = true
GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(rescodes.localStorage.leftDrawerOpen) === 'true')
GlobalStore.mutations.setCategorySel(localStorage.getItem(rescodes.localStorage.categorySel))
GlobalStore.actions.loadAfterLogin()
Todos.actions.dbLoadTodo(true)
await GlobalStore.actions.loadAfterLogin()
.then(() => {
Todos.actions.dbLoadTodo(true)
})
}
async function autologin(context) {
async function autologin_FromLocalStorage(context) {
try {
console.log('*** Autologin ***')
console.log('*** autologin_FromLocalStorage ***')
// INIT
UserStore.mutations.setlang(process.env.LANG_DEFAULT)
// ++Todo: Estrai la Lang dal Localstorage
// Estrai la Lang dal Localstorage
const lang = localStorage.getItem('lang')
if (lang) {
UserStore.mutations.setlang(lang)
@@ -492,7 +506,7 @@ namespace Actions {
}
const userId = String(localStorage.getItem(rescodes.localStorage.userId))
const username = String(localStorage.getItem(rescodes.localStorage.username))
const verifiedEmail = localStorage.getItem(rescodes.localStorage.verifiedEmail) === '1'
const verified_email = localStorage.getItem(rescodes.localStorage.verified_email) === 'true'
console.log('autologin userId', userId)
@@ -500,10 +514,10 @@ namespace Actions {
userId: userId,
username: username,
idToken: token,
verified_email: verifiedEmail
verified_email: verified_email
})
setGlobal()
await setGlobal()
console.log('autologin userId STATE ', state.userId)
@@ -522,7 +536,7 @@ namespace Actions {
signup: b.dispatch(signup),
signin: b.dispatch(signin),
logout: b.dispatch(logout),
autologin: b.dispatch(autologin)
autologin_FromLocalStorage: b.dispatch(autologin_FromLocalStorage)
}
}

View File

@@ -12,7 +12,7 @@ export const rescodes = {
LIST_START: '0',
localStorage: {
verifiedEmail: 'vf',
verified_email: 'vf',
categorySel: 'cs',
isLogged: 'ilog',
expirationDate: 'expdate',

View File

@@ -6,10 +6,11 @@ export const serv_constants = {
RIS_CODE_EMAIL_VERIFIED: 1,
RIS_CODE_LOGIN_ERR_GENERIC: -20,
RIS_CODE_LOGIN_ERR: -10,
RIS_CODE_OK: 1,
RIS_CODE_LOGIN_OK: 1,
RIS_CODE_LOGIN_OK: 1
RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN: 403
}