- updated SendReq

- If Server Down the login msg error corrected.
This commit is contained in:
Paolo Arena
2019-02-06 18:47:54 +01:00
parent cb941568e2
commit cb62d46048
11 changed files with 278 additions and 190 deletions

View File

@@ -0,0 +1,18 @@
import { UserStore } from "../store/Modules";
import messages from "../statics/i18n";
function translate(params) {
let msg = params.split('.')
let lang = UserStore.state.lang
let stringa = messages[lang]
let ris = stringa
msg.forEach(param => {
ris = ris[param]
})
return ris
}
export default translate

View File

@@ -27,4 +27,5 @@ export interface IUserState {
tokenforgot?: string
servercode?: number
x_auth_token?: string
}

View File

@@ -48,6 +48,10 @@ const messages = {
}
}
},
fetch: {
errore_generico: 'Errore Generico',
errore_server: 'Impossibile accedere al Server. Riprovare Grazie',
},
reg: {
incorso: 'Registrazione in corso...',
richiesto: 'Campo Richiesto',
@@ -165,6 +169,10 @@ const messages = {
}
}
},
fetch: {
errore_generico: 'Generic Error',
errore_server: 'Unable to access to the Server. Retry. Thank you.',
},
reg: {
incorso: 'Registration please wait...',
richiesto: 'Field Required',

View File

@@ -1,10 +1,15 @@
import Request from './Instance'
import sendRequest from './Inst-Pao'
export * from './ApiTypes'
import axios from 'axios'
export {addAuthHeaders, removeAuthHeaders, API_URL} from './Instance'
export { addAuthHeaders, removeAuthHeaders, API_URL } from './Instance'
// import {AlgoliaSearch} from './AlgoliaController'
import Paths from '@paths'
import { rescodes } from '@src/store/Modules/rescodes'
import { UserStore } from '@modules'
// const algoliaApi = new AlgoliaSearch()
@@ -12,19 +17,24 @@ export namespace ApiTool {
export async function post(path: string, payload?: any) {
return await Request('post', path, payload)
}
export async function postFormData(path: string, payload?: any) {
return await Request('postFormData', path, payload)
}
export async function get(path: string, payload?: any) {
return await Request('get', path, payload)
}
export async function put(path: string, payload?: any) {
return await Request('put', path, payload)
}
export async function Delete(path: string, payload: any) {
return await Request('delete', path, payload)
}
export async function checkSession({token, refresh_token}) {
export async function checkSession({ token, refresh_token }) {
return await axios.post(process.env.API_URL + Paths.TOKEN_REFRESH, {
refresh_token
}, {
@@ -34,9 +44,69 @@ export namespace ApiTool {
})
}
export async function SendReq(url: string, lang: string, mytok: string, method: string, mydata: any) {
return await sendRequest(url, lang, mytok, method, mydata)
export async function SendReq(url: string, lang: string, mytok: string, method: string, mydata: any, noAuth: boolean = false) {
UserStore.mutations.setServerCode(rescodes.EMPTY)
UserStore.mutations.setAuth('')
return await new Promise(function (resolve, reject) {
let ricevuto = false
sendRequest(url, lang, mytok, method, mydata)
.then(resreceived => {
ricevuto = true
let res = resreceived
console.log('SendReq RES=', res)
let x_auth_token = ''
if (res.status === 200) {
try {
if (!noAuth) {
x_auth_token = String(res.headers.get('x-auth'))
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) {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setAuth(x_auth_token)
}
return reject(e)
}
return res.json()
.then((body) => {
return resolve({res, body})
})
.catch(e => {
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
return reject(e)
})
} else {
return resolve({res, body: res.body})
}
})
.catch(error => {
if (process.env.DEV) {
console.log('ERROR using', url, error, 'ricevuto=', ricevuto)
}
if (!ricevuto) {
UserStore.mutations.setServerCode(rescodes.ERR_SERVERFETCH)
} else {
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
}
return reject(error)
})
})
}
}
export default ApiTool

View File

@@ -3,6 +3,8 @@ import { storeBuilder } from './Store/Store'
import Vue from 'vue'
import translate from './../../globalroutines/util'
import urlBase64ToUint8Array from '../../js/utility'
import messages from '../../statics/i18n'
@@ -124,14 +126,17 @@ namespace Actions {
console.log('context', context)
const options = {
title: t('notification.title_subscribed'),
content: t('notification.subscribed'),
title: translate('notification.title_subscribed'),
content: translate('notification.subscribed'),
openUrl: '/'
}
let myres = {
options: { ...options },
subs: newSub
subs: newSub,
others: {
userId: UserStore.state.userId
}
}
return fetch(process.env.MONGODB_HOST + '/subscribe', {
@@ -158,7 +163,6 @@ namespace Actions {
})
return ris
}
function prova(context) {

View File

@@ -170,13 +170,11 @@ namespace Actions {
state.networkDataReceived = false
let ris = await Api.SendReq(call, UserStore.state.lang, token, 'GET', null)
.then((res) => {
return res.json()
}).then((resData) => {
.then(({resData, body}) => {
state.networkDataReceived = true
// console.log('******* UPDATE TODOS.STATE.TODOS !:', resData.todos)
state.todos = [...resData.todos]
state.todos = [...body.todos]
Todos.state.todos_changed++
console.log('state.todos', state.todos, 'checkPending', checkPending)
@@ -186,12 +184,8 @@ namespace Actions {
return rescodes.OK
})
.catch((error) => {
if (process.env.DEV) {
// console.log('dbLoadTodo ERRORE', error)
}
// If error network connection, take the data from IndexedDb
return rescodes.ERR_GENERICO
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
console.log('fine della funz...')
@@ -266,30 +260,22 @@ namespace Actions {
const token = UserStore.state.idToken
let res = await Api.SendReq(call, UserStore.state.lang, token, method, itemtodo)
.then(function (response) {
if (response)
return response.json()
else
return null
}).then(newItem => {
console.log('RESDATA =', newItem)
if (newItem) {
const newId = newItem._id
.then(({res, body}) => {
console.log('RESDATA =', body)
if (body.newItem) {
const newId = body.newItem._id
// if (method === 'PATCH') {
// newItem = newItem.todo
// }
// Update ID on local
UpdateNewIdFromDB(itemtodo, newItem, method)
UpdateNewIdFromDB(itemtodo, body.newItem, method)
}
})
.catch((error) => {
if (process.env.DEV) {
console.log('ERRORE FETCH', 'dbInsertSaveTodo', method)
console.log(error)
}
return rescodes.ERR_GENERICO
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
return res
@@ -302,7 +288,7 @@ namespace Actions {
const token = UserStore.state.idToken
let res = await Api.SendReq(call, UserStore.state.lang, token, 'DELETE', item)
.then(function (res) {
.then(function ({res, body}) {
// Delete Item in to Array
state.todos.splice(state.todos.indexOf(item), 1)
@@ -310,10 +296,8 @@ namespace Actions {
return rescodes.OK
})
.catch((error) => {
if (process.env.DEV) {
console.log('ERRORE FETCH', 'dbDeleteTodo')
}
return rescodes.ERR_GENERICO
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
return res

View File

@@ -9,6 +9,8 @@ import { rescodes } from '../Modules/rescodes'
import { GlobalStore, UserStore, Todos } from '@store'
import globalroutines from './../../globalroutines/index'
import translate from './../../globalroutines/util'
const bcrypt = require('bcryptjs')
// State
@@ -23,7 +25,9 @@ const state: IUserState = {
idToken: '',
tokens: [],
verifiedEmail: false,
categorySel: 'personal'
categorySel: 'personal',
servercode: 0,
x_auth_token: ''
}
@@ -52,15 +56,31 @@ namespace Getters {
}
}, 'tok')
const isServerError = b.read(state => {
return (state.servercode === rescodes.ERR_SERVERFETCH)
}, 'isServerError')
const getServerCode = b.read(state => {
return state.servercode
}, 'getServerCode')
export const getters = {
get lang() {
return lang()
},
get tok() {
return tok()
},
get isServerError() {
return isServerError()
},
get getServerCode() {
return getServerCode()
}
}
}
@@ -102,6 +122,10 @@ namespace Mutations {
state.servercode = num
}
function setAuth(state: IUserState, x_auth_token: string) {
state.x_auth_token = x_auth_token
}
function clearAuthData(state: IUserState) {
state.userId = ''
state.username = ''
@@ -111,6 +135,33 @@ namespace Mutations {
state.categorySel = 'personal'
}
function setErrorCatch(state: IUserState, err: number) {
if (state.servercode !== rescodes.ERR_SERVERFETCH) {
state.servercode = err
}
}
function getMsgError(state: IUserState, err: number) {
let msgerrore = ''
if (err !== rescodes.OK) {
msgerrore = 'Error [' + state.servercode + ']: '
if (state.servercode === rescodes.ERR_SERVERFETCH) {
msgerrore = translate('fetch.errore_server')
} else {
msgerrore = translate('fetch.errore_generico')
}
if (process.env.DEV) {
console.log('ERROREEEEEEEEE: ', msgerrore, ' (', err, ')')
}
}
// return { code: state.servercode, msg: msgerrore }
return msgerrore
}
export const mutations = {
authUser: b.commit(authUser),
setpassword: b.commit(setpassword),
@@ -118,16 +169,20 @@ namespace Mutations {
setlang: b.commit(setlang),
UpdatePwd: b.commit(UpdatePwd),
setServerCode: b.commit(setServerCode),
clearAuthData: b.commit(clearAuthData)
setAuth: b.commit(setAuth),
clearAuthData: b.commit(clearAuthData),
setErrorCatch: b.commit(setErrorCatch),
getMsgError: b.commit(getMsgError)
}
}
namespace Actions {
async function sendUserEdit(context, form: Object) {
try {
const {data} = await Api.postFormData('profile/edit', form)
const { data } = await Api.postFormData('profile/edit', form)
console.log(data)
// return new ApiSuccess({data})
@@ -136,7 +191,7 @@ namespace Actions {
}
}
async function resetpwd (context, paramquery: IUserState) {
async function resetpwd(context, paramquery: IUserState) {
let call = process.env.MONGODB_HOST + '/updatepwd'
console.log('CALL ' + call)
@@ -151,36 +206,18 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING)
let myres
let x_auth_token: string = ''
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => {
console.log(res)
myres = res
x_auth_token = String(res.headers.get('x-auth'))
if (myres.status === 200) {
return myres.json()
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return { code: rescodes.ERR_GENERICO, msg: 'Errore: ' + myres.status, resetpwd: true }
})
.then((body) => {
Mutations.mutations.UpdatePwd({ idToken: x_auth_token })
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
.then(({ res, body }) => {
return { code: body.code, msg: body.msg }
}).catch((err) => {
console.log('ERROR: ' + err)
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return { code: rescodes.ERR_GENERICO, msg: 'Errore' }
})
.catch((error) => {
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
}
async function requestpwd (context, paramquery: IUserState) {
async function requestpwd(context, paramquery: IUserState) {
let call = process.env.MONGODB_HOST + '/requestnewpwd'
console.log('CALL ' + call)
@@ -194,30 +231,17 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING)
let myres
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => {
console.log(res)
myres = res
if (myres.status === 200) {
return myres.json()
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return { code: rescodes.ERR_GENERICO, msg: 'Errore: ' + myres.status, resetpwd: true }
})
.then((body) => {
.then(({ res, body }) => {
return { code: body.code, msg: body.msg }
}).catch((err) => {
console.log('ERROR: ' + err)
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return { code: rescodes.ERR_GENERICO, msg: 'Errore' }
}).catch((error) => {
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
}
async function vreg (context, paramquery: ILinkReg) {
async function vreg(context, paramquery: ILinkReg) {
let call = process.env.MONGODB_HOST + '/vreg'
console.log('CALL ' + call)
@@ -230,20 +254,8 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING)
let myres
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => {
console.log(res)
myres = res
if (myres.status === 200) {
return myres.json()
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return { code: rescodes.ERR_GENERICO, msg: 'Errore: ' + myres.status }
})
.then((body) => {
.then(({ res, body }) => {
// console.log("RITORNO 2 ");
// mutations.setServerCode(myres);
if (body.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) {
@@ -253,14 +265,13 @@ namespace Actions {
console.log('Risultato di vreg: ', body.code)
}
return { code: body.code, msg: body.msg }
}).catch((err) => {
console.log('ERROR: ' + err)
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return { code: rescodes.ERR_GENERICO, msg: 'Errore' }
}).catch((error) => {
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
}
async function signup (context, authData: ISignupOptions) {
async function signup(context, authData: ISignupOptions) {
let call = process.env.MONGODB_HOST + '/users'
console.log('CALL ' + call)
@@ -289,16 +300,8 @@ namespace Actions {
let x_auth_token: string = ''
return Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => {
.then(({ res, body }) => {
myres = res
x_auth_token = String(res.headers.get('x-auth'))
if (x_auth_token) {
return res.json()
} else {
return { status: 400, code: rescodes.ERR_GENERICO }
}
})
.then((body) => {
if (process.env.DEV) {
console.log('RISULTATO ')
console.log('STATUS ' + myres.status + ' ' + (myres.statusText))
@@ -348,17 +351,13 @@ namespace Actions {
}
})
.catch((error) => {
if (process.env.DEV) {
console.log('signup ERROREEEEEEEEE')
console.log(error)
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return rescodes.ERR_GENERICO
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
})
}
async function signin (context, authData: ISigninOptions) {
async function signin(context, authData: ISigninOptions) {
let call = process.env.MONGODB_HOST + '/users/login'
console.log('LOGIN ' + call)
@@ -378,24 +377,12 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING)
let x_auth_token: string = ''
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => {
.then(({ res, body }) => {
myres = res
x_auth_token = String(res.headers.get('x-auth'))
let injson = res.json()
if (x_auth_token || injson) {
return injson
} else {
return { status: 400, code: rescodes.ERR_GENERICO }
}
})
.then((body) => {
if (process.env.DEV) {
console.log('RISULTATO ')
console.log('STATUS ' + myres.status + ' ' + (myres.statusText))
console.log('STATUS ' + res.status + ' ' + (res.statusText))
console.log('BODY:')
console.log(body)
}
@@ -417,7 +404,7 @@ namespace Actions {
Mutations.mutations.authUser({
userId: userId,
username: username,
idToken: x_auth_token,
idToken: state.x_auth_token,
verifiedEmail: verifiedEmail
})
}
@@ -427,7 +414,7 @@ namespace Actions {
const expirationDate = new Date(now.getTime() * 1000)
localStorage.setItem(rescodes.localStorage.userId, userId)
localStorage.setItem(rescodes.localStorage.username, username)
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
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())
@@ -450,15 +437,12 @@ namespace Actions {
}
})
.catch((error) => {
if (process.env.DEV) {
console.log('signin ERRORE', error)
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return rescodes.ERR_GENERICO
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
}
async function logout (context) {
async function logout(context) {
let call = process.env.MONGODB_HOST + '/users/me/token'
console.log('CALL ' + call)
@@ -470,14 +454,13 @@ namespace Actions {
console.log(usertosend)
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'DELETE', usertosend)
.then(
(res) => {
.then(({ res, body }) => {
console.log(res)
}
).catch((err) => {
console.log('ERROR: ' + err)
}).then(() => {
Mutations.mutations.clearAuthData()
}).catch((error) => {
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
localStorage.removeItem(rescodes.localStorage.expirationDate)
@@ -504,7 +487,7 @@ namespace Actions {
}
async function autologin (context) {
async function autologin(context) {
try {
console.log('*** Autologin ***')
// INIT

View File

@@ -1,7 +1,10 @@
export const rescodes = {
EMPTY: 0,
CALLING: 10,
OK: 20,
ERR_GENERICO: -1,
ERR_SERVERFETCH: -2,
ERR_AUTHENTICATION: -5,
DUPLICATE_EMAIL_ID: 11000,
DUPLICATE_USERNAME_ID: 11100,

View File

@@ -77,6 +77,11 @@ export default class Signin extends Vue {
} else if (riscode === serv_constants.RIS_CODE_LOGIN_ERR) {
this.showNotif(this.$t('login.errato'))
this.$router.push('/signin')
} else if (riscode === rescodes.ERR_SERVERFETCH) {
this.showNotif(this.$t('fetch.errore_server'))
} else if (riscode === rescodes.ERR_GENERICO) {
let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode)
this.showNotif(msg)
} else {
this.showNotif('Errore num ' + riscode)
}
@@ -117,6 +122,7 @@ export default class Signin extends Vue {
console.log(this.signin)
UserStore.actions.signin(this.signin)
.then((riscode) => {
console.log('riscode=', riscode)
if (riscode === rescodes.OK) {
router.push('/signin')
globalroutines(this, 'loadapp', '')
@@ -127,6 +133,8 @@ export default class Signin extends Vue {
this.$q.loading.hide()
}).catch(error => {
console.log('ERROR = ' + error)
this.checkErrors(error)
this.$q.loading.hide()
})

View File

@@ -8,6 +8,7 @@
</div>
<!--Prova URL : {{env('PROVA_PAOLO')}}-->
<form>
<q-field
:error="$v.signin.username.$error"
@@ -54,6 +55,7 @@
<q-btn rounded size="lg" color="primary" @click="submit" :disable="$v.$error">{{$t('login.enter')}}
</q-btn>
</div>
</form>
</q-page>
</div>
</template>

View File

@@ -124,11 +124,16 @@ export default class Signup extends Vue {
}
checkErrors(riscode: number) {
// console.log("RIS = " + riscode);
console.log('checkErrors', riscode)
if (riscode === rescodes.DUPLICATE_EMAIL_ID) {
this.showNotif(this.$t('reg.err.duplicate_email'))
} else if (riscode === rescodes.DUPLICATE_USERNAME_ID) {
this.showNotif(this.$t('reg.err.duplicate_username'))
} else if (riscode === rescodes.ERR_SERVERFETCH) {
this.showNotif(this.$t('fetch.errore_server'))
} else if (riscode === rescodes.ERR_GENERICO) {
let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode)
this.showNotif(msg)
} else if (riscode === rescodes.OK) {
this.$router.push('/signin')
this.showNotif({type: 'warning', textColor: 'black', message: this.$t('components.authentication.email_verification.link_sent')})
@@ -136,6 +141,8 @@ export default class Signup extends Vue {
this.showNotif('Errore num ' + riscode)
}
}
public submitOk() {