-
-
Save rafaelkendrik/5c706c9d0451521c4bee55e2f11be32e to your computer and use it in GitHub Desktop.
help me bro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import store from '../store' | |
export default async (to, from, next) => { | |
console.log('logado', store.getters['auth/isAuthenticated']); | |
if (to.name !== 'Login' && !store.getters['auth/isAuthenticated']) next({ name: 'Login' }) | |
else next() | |
} | |
// uma review alternativo para a rota que você mandou bro.. | |
export default async (to, from, next) => { | |
// como 'Login' é usado duas vezes, seria bacana guarda-lo dentro de uma constante | |
const LOGIN_ROUTE_NAME = 'Login' | |
// seria ainda melhor exportar essa constante dá rota onde você definiu esse name, assim você também utiliza | |
// ela na rota, evita problemas de por acaso alguém mexer no nome e escrever de modificar aqui no beforeEach | |
// você pode criar duas consts aqui para melhorar a "narrativa" do teu código | |
// isso é importante por dois motivos: facilita a legibilidade | |
//e também você pode usar o estado guardado da verificação mais de uma vez | |
const isLoginTargetRoute = (to.name === LOGIN_ROUTE_NAME) | |
const isAuthenticated = store.getters['auth/isAuthenticated'] | |
// evite usar negativas em if quando ouver else, você reduz assim a complexidade da condicional | |
if (isAuthenticated || isLoginTargetRoute) { | |
next() | |
// um return é uma alternativa bacana para você não precisar de um else | |
return | |
} | |
next({ name: LOGIN_ROUTE_NAME }) | |
} | |
// uma outra coisa que é interressante você fazer é o seguinte, onde você define a rota, você pode passar uma prop | |
// no meta chamada publicAccess, ao inves de você precisar vir aqui e adicionar outra rota, como o caso do isLoginTargetRoute, | |
// você pode apenas validar se a rota é publica. | |
// https://router.vuejs.org/guide/advanced/meta.html#route-meta-fields | |
// nota: a doc sugere requiresAuth, eu acho ruim, pois ai você precisar atribuir esse campo em todas as rotas, | |
// chamando de publicAccess, você apenas precisa atruir a aquelas que são publicas. Se não for não precisa definir essa key | |
// ex: | |
// Arquivo de rota: | |
{ | |
name: LOGIN_ROUTE_NAME /* aqui é o proprio 'Login', com a constante que mencionei */, | |
component: LoginComponent, | |
meta: { | |
publicAccess: true | |
} | |
} | |
//assim você validaria a rota publica ao invés de ser a página de login: | |
export default async (to, from, next) => { | |
const LOGIN_ROUTE_NAME = 'Login' | |
const hasTargetPublicAccess = Boolean(to.meta.publicAccess) // adicionando um Boolean() sempre vai ser true ou false | |
const isAuthenticated = store.getters['auth/isAuthenticated'] | |
if (isAuthenticated || hasTargetPublicAccess) { | |
next() | |
return | |
} | |
next({ name: LOGIN_ROUTE_NAME }) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import http from '@/http' | |
export const doLogin = (userInfo) => { | |
return http().get(`/sanctum/csrf-cookie`).then(() => { | |
return http().post(`/api/v1/common/login`, { | |
email: userInfo.email, | |
password: userInfo.password | |
}).then((response) => { | |
return response; | |
}); | |
}) | |
}; | |
// apenas uma sugestão bro, se você estiver usando o babel, você pode usar o async await para simplificar esse código: | |
export const doLogin = async (userInfo) => { | |
await http().get(`/sanctum/csrf-cookie`) | |
const response = http().post(`/api/v1/common/login`, { | |
email: userInfo.email, | |
password: userInfo.password | |
}) | |
return response | |
}; | |
// mais algumas sugestões no mesmo código: | |
export const doLogin = async (userInfo) => { // você pode fazer o destruction do userInfo aqui, simplifica | |
//o objeto passado no post ({ email, password })caso você não opte por apssar o objeto inteiro para o post | |
await http().get('/sanctum/csrf-cookie') // é preferivel usar aspas simples caso você não use alguma variavel na string | |
const response = http().post('/api/v1/common/login', userInfo) // você pode passar diretamente o userInfo aqui, as keys são as mesmas | |
// const response = http().post('/api/v1/common/login', { email, password }) se você optar por fazer o destruction no começo | |
// particularmente, eu prefiro fazer o tratamento dos dados todo no service, assim a logica de status viria para cá | |
const isResponseStatusAuthorized = (response && response.status && response.status != 401) | |
if (isResponseStatusAuthorized) { | |
return response.data | |
} | |
} | |
export const doLogout = () => { | |
return http().post(`/api/v1/common/logout`).then((response) => { | |
return response.data; | |
}); | |
} | |
export const me = () => { | |
return http().get("api/v1/common/me").then((response) => { | |
console.log('me entrou'); // oloco kk, brincadeira irmão | |
return response; | |
}).catch(() => { | |
console.log('me falhou'); | |
return null; | |
}); | |
} | |
export default { | |
doLogin, | |
doLogout, | |
me, | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from 'vue' | |
import App from './App.vue' | |
import router from './router' | |
import store from './store' | |
import './registerServiceWorker'; | |
import './components/components' | |
import './plugins/chartist' | |
import './plugins/vee-validate' | |
import vuetify from './plugins/vuetify' | |
import VueSweetalert2 from 'vue-sweetalert2'; | |
Vue.use(VueSweetalert2); | |
Vue.config.productionTip = false | |
store.dispatch('auth/ActionMeLogin').then(() => { | |
console.log('teste 1'); | |
new Vue({ | |
vuetify, | |
router, | |
store, | |
render: h => h(App), | |
}).$mount('#app') | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// mutatitons: | |
const mutations = { | |
[types.SET_USER] (state, user) { | |
state.loggedUser = user | |
} | |
} | |
// getters: | |
const getters = { | |
isUserAuthenticated (state) { | |
const isObject = (x) => (Object(x) === x) // você pode usar validação de qualquer biblioteca | |
const hasLoggedUser = isObject(state.loggedUser) // se houver usuário, está authenticado | |
return hasLoggedUser | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import LoginService from '../services/LoginService' | |
import * as types from './mutation-types'; | |
export const ActionDoLogin = ({ commit }, payload) => { | |
// aqui uma sugestão é separar as regras de status para o service e eu descartaria um state para AUTHENTICATED | |
LoginService.doLogin(payload).then((response) => { | |
console.log('actionDoLogin'); | |
if (!response.status && response.status != 401) { | |
commit(types.SET_USER_AUTHENTICATED, true); | |
commit(types.SET_USER, response.data) | |
} else { | |
console.log('autenticado nao'); | |
commit(types.SET_USER_AUTHENTICATED, false); | |
store.dispatch('ActionSetUser', null); | |
} | |
}); | |
} | |
// no caso ficaria: | |
export const ActionDoLogin = async ({ commit }, userData) { | |
const user = await LoginService.doLogin(userData) | |
commit(types.SET_USER, user) | |
} | |
export const ActionDoLogout = ({ commit }, payload) => { | |
LoginService.doLogout(payload).then((response) => { | |
commit(types.SET_USER, {}) | |
commit(types.SET_USER_AUTHENTICATED, false); | |
}); | |
} | |
export const ActionMeLogin = ({ commit }, store, payload) => { //aqui pode ter um problema, a action apenas recebe dois argumentos | |
// você acessa o dispatch dentro da mesma chave do commit ActionMeLogin = ({ commit, dispatch }, payload) | |
LoginService.me(payload).then((response) => { | |
if (!response.status && response.status != 401) { | |
console.log('Me sim'); | |
commit(types.SET_USER_AUTHENTICATED, true); | |
console.log(response.data); | |
commit(types.SET_USER, response.data) | |
} else { | |
console.log('Me nao'); | |
commit(types.SET_USER_AUTHENTICATED, false); | |
store.dispatch('ActionSetUser', null); // aqui ficaria apenas dispatch('ActionSetUser', null) | |
} | |
}).catch(() => { | |
console.log('pipocou'); | |
return null; | |
});; | |
} | |
export const ActionMeLogin = ({ commit }, store, payload) => { | |
LoginService.me(payload).then((response) => { | |
if (!response.status && response.status != 401) { | |
console.log('Me sim'); | |
commit(types.SET_USER_AUTHENTICATED, true); | |
console.log(response.data); | |
commit(types.SET_USER, response.data) | |
} else { | |
console.log('Me nao'); | |
commit(types.SET_USER_AUTHENTICATED, false); | |
store.dispatch('ActionSetUser', null); | |
} | |
}).catch(() => { | |
console.log('pipocou'); | |
return null; | |
});; | |
} | |
// essa action não é necessaria, você pode chamar diretamento o commit | |
export const ActionSetUser = ({ commit }, payload) => { | |
commit(types.SET_USER, payload) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment