Merhabalar,
Bugün Vue.JS ile Json Web Tokens kullanarak web uygulamasında kullanıcı girişi yapmaya çalışacağım. Vuex kullanmak işlemlerimizi daha kolay yapmamızı sağlayacaktır. Vuex kullanmadan nasıl yapabiliriz kısmına da değineceğim.
Bu yazı Egehan GÜNDOĞDU’nun blogunda yer alan “Vue.js ve Django Rest Framework ile JWT Authentication” yazısından ilham aldı 🙂
JWT hakkında şuradan bilgi edinebilirsiniz: https://jwt.io/
Projemizde Axios kullandığımızı varsayalım(aynı işlemleri Fetch Api kullanarak da yapabiliyoruz)
Vuex ile Çözüm
İlk olarak Vuex State dosyasına token adında bir değişkeni ekliyorum ve localstorage’den tokeni çekmeye çalışıyoruz tabii ilk aşamada herhangi bir token olmayacaktır. (State kısmında tokeni tutmayıp sadece localstoragede de kullanabilirsiniz)
const state = { ... token:localStorage.getItem("accessToken") || null }
Şimdi tokenleri değiştirecek fonksiyonlarımızı mutations kısmına ekliyorum buna benzer fonksiyonlar olabilir:
RETRIEVE_TOKEN(state, token) { state.token = token }, DESTROY_TOKEN(state) { state.token = null }
Kullanıcının giriş yapıp yapmadığını anlayabilmemiz için bir getter ekliyorum:
loggedIn(state) { return state.token !== null },
Ve tokeni elde edeceğimiz fonksiyonu actions kısmına ekliyorum (actions kısmında yer almasının sebebi asenkron işlemleri orada yapabilmemiz):
retrieveToken(context, credentials) { return new Promise((resolve, reject) => { axios.post("api/login/", { email: credentials.email, password: credentials.password, }) .then(response => { const token = response.data.accessToken localStorage.setItem('accessToken', token) context.commit('RETRIEVE_TOKEN', token) resolve(response) }) .catch(error => { reject(error) }) }) },
Tokeni silmek istediğimiz zaman bir istek atmamıza gerek yok. Bunun için şöyle bir fonksiyon yazılabilir:
destroyToken(context) { if (context.getters.loggedIn) { localStorage.removeItem('accessToken') context.commit('DESTROY_TOKEN') } }
Artık projede vue dosyalarında retrieveToken adlı fonksiyonu çağrılabiliriz:
this.$store.dispatch('retrieveToken', { email: this.email, password: this.password, }) .then(response => { this.$router.push({ name: 'dashboard' }) })
Çıkış yapmak için ise:
this.$store.dispatch('destroyToken') .then(response => { this.$router.push({ name: 'page-login' }) })
Eğer giriş yapılmamış ise login sayfasına yönlendirmek istiyoruz main.js:
router.beforeEach((to, from, next) => { if (!store.getters.loggedIn) { next({name:'page-login'}) } else { next() } } else { next() } )
gibi bir kontrol yapabilirsiniz tabi bu senaryonuza göre değişecektir.
Vuex olmadan Çözüm
Eğer projemizde Vuex yer almıyorsa nasıl bir yol izlenebiliriz?
Herhangi bir Vue dosyasında şöyle bir metod oluşturup istek atabiliriz.
methods: { login() { this.$http .post("api/login/", { email: this.email, password: this.password, }) .then((response)=> { localStorage.setItem("accessToken",response.data.accessToken); this.$router.push(name="dashboard"); }) .catch((error)=> { console.log(error); }); } }
Tabi bu durumda her sayfa oluşturulduğunda localStorage kontrol edilmelidir.
Bir yanıt yazın