Skip to content

Instantly share code, notes, and snippets.

@vouill
vouill / app.js
Created Apr 29, 2019
Preparing SQL queries
View app.js
// before
db.all(`SELECT * FROM POSTS WHERE ID = ${req.params.id};`, function(
err,
row
) {
res.send(row);
});
// after
@vouill
vouill / app.js
Created Dec 4, 2017
app.vue mehtod handling unauthorize
View app.js
created: function () {
axios.interceptors.response.use(undefined, function (err) {
return new Promise(function (resolve, reject) {
if (err.status === 401 && err.config && !err.config.__isRetryRequest) {
// if you ever get an unauthorized, logout the user
this.$store.dispatch(AUTH_LOGOUT)
// you can also redirect to /login if needed !
}
throw err;
});
View main.js
const token = localStorage.getItem('user-token')
if (token) {
axios.defaults.headers.common['Authorization'] = token
}
@vouill
vouill / router.js
Last active Jan 30, 2018
router auth
View router.js
import store from '../store' // your vuex store
const ifNotAuthenticated = (to, from, next) => {
if (!store.getters.isAuthenticated) {
next()
return
}
next('/')
}
View auth.module.js
const actions = {
[AUTH_REQUEST]: ({commit, dispatch}, user) => {
return new Promise((resolve, reject) => {
commit(AUTH_REQUEST)
axios({url: 'auth', data: user, method: 'POST' })
.then(resp => {
const token = resp.data.token
localStorage.setItem('user-token', token)
// Add the following line:
axios.defaults.headers.common['Authorization'] = token
View logout.js
methods: {
logout: function () {
this.$store.dispatch(AUTH_LOGOUT)
.then(() => {
this.$router.push('/login')
})
}
},
@vouill
vouill / logout.js
Last active Dec 4, 2017
auth logout
View logout.js
const actions = {
...
[AUTH_LOGOUT]: ({commit, dispatch}) => {
return new Promise((resolve, reject) => {
commit(AUTH_LOGOUT)
localStorage.removeItem('user-token') // clear your user's token from localstorage
resolve()
})
@vouill
vouill / auth.module.js
Last active Dec 4, 2017
auth mutations
View auth.module.js
// basic mutations, showing loading, success, error to reflect the api call status and the token when loaded
const mutations = {
[AUTH_REQUEST]: (state) => {
state.status = 'loading'
},
[AUTH_SUCCESS]: (state, token) => {
state.status = 'success'
state.token = token
},
View auth.module.js
const actions = {
[AUTH_REQUEST]: ({commit, dispatch}, user) => {
return new Promise((resolve, reject) => { // The Promise used for router redirect in login
commit(AUTH_REQUEST)
axios({url: 'auth', data: user, method: 'POST' })
.then(resp => {
const token = resp.data.token
localStorage.setItem('user-token', token) // store the token in localstorage
commit(AUTH_SUCCESS, token)
// you have your token, now log in your user :)
View auth.module.js
const getters = {
isAuthenticated: state => !!state.token,
authStatus: state => state.status,
}
You can’t perform that action at this time.