├── .babelrc ├── .env ├── .gitignore ├── .postcssrc ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── public ├── favicon.ico └── index.html └── src ├── App.vue ├── assets └── logo.png ├── components ├── ArticleList.vue └── Confirm.vue ├── main.js ├── plugins └── confirm.js ├── router.js ├── services ├── http.js └── utils.js ├── store ├── ability.js ├── articles.js ├── index.js ├── notifications.js └── storage.js ├── validation └── index.js └── views ├── Article.vue ├── EditArticle.vue ├── Home.vue └── Login.vue /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@vue/app" 4 | ] 5 | } -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | VUE_APP_API_URL=http://localhost:3000/api -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /dist 4 | 5 | # local env files 6 | .env.local 7 | .env.*.local 8 | 9 | # Log files 10 | npm-debug.log* 11 | yarn-debug.log* 12 | yarn-error.log* 13 | 14 | # Editor directories and files 15 | .idea 16 | .vscode 17 | *.suo 18 | *.ntvs* 19 | *.njsproj 20 | *.sln 21 | -------------------------------------------------------------------------------- /.postcssrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": { 3 | "autoprefixer": {} 4 | } 5 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Sergii Stotskyi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CASL integration example with Vue + Vuex + REST API 2 | 3 | ## DEPRECATED 4 | 5 | The example has been moved to https://github.com/stalniy/casl-examples/tree/master/packages/vue-blog 6 | 7 | ---- 8 | 9 | This example shows how to integrate [CASL](https://github.com/stalniy/casl) auhorization in more or less real [Vue](https://vuejs.org) application with Vuex and REST API. Read [CASL and Cancan](https://medium.com/dailyjs/casl-and-cancan-permissions-sharing-between-ui-and-api-5f1fa8b4bec) for details 10 | 11 | > Generate with vue-cli 12 | 13 | ## Installation 14 | 15 | ``` bash 16 | # install dependencies 17 | npm ci 18 | 19 | # serve with hot reload at localhost:8080 20 | npm run serve 21 | ``` 22 | 23 | ## Description 24 | 25 | This application is a basic Blog application with possibility to login, logout and manage articles. User abilities are received from REST API and later stored in localStorage. 26 | 27 | `Ability` plugin for Vuex store can be found in [src/store/ability.js](src/store/ability.js). 28 | When user successfully login (i.e., `createSession` mutation is dispatched in store), ability is updated and when user logout (i.e., `destroySession` mutation is dispatched) ability is reset to read-only mode. 29 | 30 | `http` service is built on top of Fetch API with some hacky code (it is not important for this example). 31 | Also this example uses [vuetify](https://vuetifyjs.com/en/) as UI library 32 | 33 | ## Server side 34 | 35 | REST API is expected to be available at `http://localhost:3000/api` and support CORS headers. 36 | This example was tested and implemented together with [Rails5 + Cancan](https://github.com/stalniy/rails-cancan-api-example) but API can be implemented in whatever language you want. 37 | It's just a showcase that CASL can be seamlessly integrated with awesome [Cancan](https://github.com/CanCanCommunity/cancancan) ruby gem 38 | 39 | If you setup rails application, there are 2 users available: 40 | * admin - admin@freaksidea.com / 123456 41 | * member - member@freaksidea.com / 123456 42 | 43 | ## Alternative Server side API 44 | 45 | You can use [Express based API](https://github.com/stalniy/casl-express-example/tree/vue-api) together with this UI. Pay attention to the branch name, it should be `vue-api`. 46 | This API uses MongoDB as a database, so you will need to have one running on localhost or you can change the connection string in [src/app.js](https://github.com/stalniy/casl-express-example/blob/vue-api/src/app.js#L36) 47 | 48 | Also you will need to change API URL in `.env` file to `http://localhost:3030`. 49 | 50 | There are 3 users available: 51 | * admin@casl.io / 123456 52 | * another.writer@casl.io / 123456 53 | * writer@casl.io / 123456 54 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "casl-vue-api-example", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "serve": "vue-cli-service serve", 7 | "build": "vue-cli-service build" 8 | }, 9 | "dependencies": { 10 | "@casl/ability": "^3.2.0", 11 | "@casl/vue": "^0.4.3", 12 | "vue": "^2.5.13", 13 | "vue-router": "^3.0.1", 14 | "vuetify": "^1.0.11", 15 | "vuex": "^3.0.1" 16 | }, 17 | "devDependencies": { 18 | "@vue/cli-plugin-babel": "^4.0.5", 19 | "@vue/cli-service": "^4.0.5", 20 | "node-sass": "^4.13.0", 21 | "sass-loader": "^8.0.0", 22 | "vue-template-compiler": "^2.5.13" 23 | }, 24 | "browserslist": [ 25 | "> 1%", 26 | "last 2 versions", 27 | "not ie <= 8" 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stalniy/casl-vue-api-example/638114bba5740e1b177c797ca5adf5efb941dbbc/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | CASL Vue + API 10 | 11 | 12 | 15 |
16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 69 | 70 | 97 | -------------------------------------------------------------------------------- /src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stalniy/casl-vue-api-example/638114bba5740e1b177c797ca5adf5efb941dbbc/src/assets/logo.png -------------------------------------------------------------------------------- /src/components/ArticleList.vue: -------------------------------------------------------------------------------- 1 | 21 | 22 | 67 | 68 | 81 | -------------------------------------------------------------------------------- /src/components/Confirm.vue: -------------------------------------------------------------------------------- 1 | 16 | 17 | 56 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Vuetify from 'vuetify' 3 | import { abilitiesPlugin } from '@casl/vue' 4 | import { confirmPlugin } from './plugins/confirm' 5 | import App from './App' 6 | import router from './router' 7 | import http from './services/http' 8 | import { store } from './store' 9 | import 'vuetify/dist/vuetify.min.css' 10 | 11 | Vue.config.productionTip = false 12 | Vue.use(Vuetify) 13 | Vue.use(confirmPlugin) 14 | Vue.use(abilitiesPlugin, store.getters.ability) 15 | 16 | http.token = store.state.token 17 | http.onError = (response) => { 18 | if (response.status === 403) { 19 | store.dispatch('forbidden', response) 20 | return true 21 | } 22 | 23 | if (response.status === 401) { 24 | store.dispatch('sessionExpired', response) 25 | return true 26 | } 27 | } 28 | 29 | 30 | new Vue({ 31 | el: '#app', 32 | router, 33 | store, 34 | render: h => h(App) 35 | }) 36 | -------------------------------------------------------------------------------- /src/plugins/confirm.js: -------------------------------------------------------------------------------- 1 | import Confirm from '../components/Confirm' 2 | 3 | export function confirmPlugin(Vue) { 4 | const ConfirmComponent = Vue.extend(Confirm) 5 | 6 | Vue.prototype.$confirm = function(message, title, params = {}) { 7 | const dialog = new ConfirmComponent({ 8 | parent: this.$root, 9 | propsData: { 10 | message, 11 | title, 12 | params 13 | } 14 | }) 15 | dialog.$mount() 16 | document.body.appendChild(dialog.$el) 17 | dialog.open() 18 | 19 | return new Promise((resolve) => { 20 | dialog.$once('close', (isAccepted) => { 21 | document.body.removeChild(dialog.$el) 22 | resolve(isAccepted) 23 | }) 24 | }) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/router.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Router from 'vue-router' 3 | 4 | import Home from './views/Home' 5 | import Login from './views/Login' 6 | import EditArticle from './views/EditArticle' 7 | import Article from './views/Article' 8 | 9 | Vue.use(Router) 10 | 11 | export default new Router({ 12 | routes: [ 13 | { 14 | path: '/', 15 | name: 'home', 16 | component: Home 17 | }, 18 | { 19 | path: '/login', 20 | name: 'login', 21 | component: Login 22 | }, 23 | { 24 | path: '/articles/:id/edit', 25 | name: 'editArticle', 26 | component: EditArticle 27 | }, 28 | { 29 | path: '/articles/new', 30 | name: 'newArticle', 31 | component: EditArticle 32 | }, 33 | { 34 | path: '/articles/:id', 35 | name: 'article', 36 | component: Article 37 | }, 38 | ] 39 | }) 40 | -------------------------------------------------------------------------------- /src/services/http.js: -------------------------------------------------------------------------------- 1 | export default function http(url, { headers, data, ...options } = {}) { 2 | if (data) { 3 | options.body = JSON.stringify(data) 4 | } 5 | 6 | const requestHeaders = { 7 | Accept: 'application/json', 8 | 'Content-Type': 'application/json', 9 | ...headers 10 | } 11 | 12 | if (http.token) { 13 | requestHeaders.Authorization = http.token 14 | } 15 | 16 | return fetch(`${process.env.VUE_APP_API_URL}${url}`, { 17 | headers: requestHeaders, 18 | ...options 19 | }).then(response => { 20 | return response.json().then(body => ({ 21 | body, 22 | status: response.status 23 | })) 24 | }).then(response => { 25 | if (response.status >= 200 && response.status < 300) { 26 | return response 27 | } 28 | 29 | if (!http.onError(response)) { 30 | throw new Error(response.body.message || response.body.errors.join('\n')) 31 | } 32 | }) 33 | } 34 | 35 | http.onError = () => {} 36 | -------------------------------------------------------------------------------- /src/services/utils.js: -------------------------------------------------------------------------------- 1 | export const TYPE_KEY = Symbol('resourceType') 2 | 3 | export function typeAs(type) { 4 | return (item) => { 5 | item[TYPE_KEY] = type 6 | return item 7 | } 8 | } -------------------------------------------------------------------------------- /src/store/ability.js: -------------------------------------------------------------------------------- 1 | export default (store) => { 2 | const ability = store.getters.ability 3 | 4 | ability.update(store.state.rules) 5 | 6 | return store.subscribe((mutation) => { 7 | switch (mutation.type) { 8 | case 'createSession': 9 | ability.update(mutation.payload.rules) 10 | break 11 | case 'destroySession': 12 | ability.update([{ actions: 'read', subject: 'all' }]) 13 | break 14 | } 15 | }) 16 | } 17 | -------------------------------------------------------------------------------- /src/store/articles.js: -------------------------------------------------------------------------------- 1 | import http from '../services/http' 2 | import { typeAs } from '../services/utils' 3 | 4 | export default { 5 | namespaced: true, 6 | 7 | actions: { 8 | find() { 9 | return http('/articles') 10 | .then((response) => { 11 | return response.body.items.map(typeAs('Article')) 12 | }) 13 | }, 14 | 15 | findById(_, id) { 16 | return http(`/articles/${id}`) 17 | .then(response => response.body.item) 18 | .then(typeAs('Article')) 19 | }, 20 | 21 | destroy(_, article) { 22 | return http(`/articles/${article.id}`, { method: 'DELETE' }) 23 | .then(response => response.body.item) 24 | }, 25 | 26 | save(_, { id, action, published, ...data }) { 27 | if (action === 'publish') { 28 | data.published = published 29 | } 30 | 31 | const request = id 32 | ? http(`/articles/${id}`, { method: 'PATCH', data }) 33 | : http('/articles', { method: 'POST', data }) 34 | 35 | return request.then(response => response.body.item) 36 | }, 37 | 38 | publish({ dispatch }, article) { 39 | return dispatch('save', { 40 | id: article.id, 41 | published: true, 42 | action: 'publish' 43 | }) 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/store/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Vuex from 'vuex' 3 | import { Ability } from '@casl/ability' 4 | import storage from './storage' 5 | import abilityPlugin from './ability' 6 | import notifications from './notifications' 7 | import articles from './articles' 8 | import http from '../services/http' 9 | import router from '../router' 10 | import { TYPE_KEY } from '../services/utils' 11 | 12 | Vue.use(Vuex) 13 | 14 | export const store = new Vuex.Store({ 15 | plugins: [ 16 | storage({ 17 | storedKeys: ['token', 'rules', 'email'], 18 | destroyOn: ['destroySession'] 19 | }), 20 | abilityPlugin 21 | ], 22 | 23 | modules: { 24 | notifications, 25 | articles 26 | }, 27 | 28 | state: { 29 | token: '', 30 | email: '', 31 | rules: [], 32 | pageTitle: 'CASL + VUE + VUEX + REST API' 33 | }, 34 | 35 | getters: { 36 | isLoggedIn(state) { 37 | return !!state.token 38 | }, 39 | 40 | ability() { 41 | return new Ability([], { 42 | subjectName(subject) { 43 | return !subject || typeof subject === 'string' 44 | ? subject 45 | : subject[TYPE_KEY] 46 | } 47 | }) 48 | } 49 | }, 50 | 51 | mutations: { 52 | createSession(state, session) { 53 | state.token = session.token 54 | state.rules = session.rules 55 | state.email = session.email 56 | http.token = session.token 57 | }, 58 | 59 | destroySession(state) { 60 | state.token = '' 61 | state.rules = [] 62 | state.email = '' 63 | http.token = null 64 | } 65 | }, 66 | 67 | actions: { 68 | login({ commit }, data) { 69 | return http('/session', { method: 'POST', data }) 70 | .then(response => commit('createSession', response.body)) 71 | }, 72 | 73 | logout({ commit }) { 74 | commit('destroySession') 75 | }, 76 | 77 | setTitle({ state }, value) { 78 | state.pageTitle = value 79 | }, 80 | 81 | sessionExpired({ dispatch, commit }) { 82 | dispatch('notifications/info', 'Session has been expired') 83 | commit('destroySession') 84 | router.push('/login') 85 | }, 86 | 87 | forbidden({ dispatch }, response) { 88 | dispatch('notifications/error', response.body.message) 89 | router.back() 90 | } 91 | } 92 | }) -------------------------------------------------------------------------------- /src/store/notifications.js: -------------------------------------------------------------------------------- 1 | let COUNTER = 0 2 | 3 | export default { 4 | namespaced: true, 5 | 6 | state: { 7 | stack: [] 8 | }, 9 | 10 | mutations: { 11 | add(state, message) { 12 | message.id = message.id || ++COUNTER 13 | state.stack.push(message) 14 | }, 15 | 16 | remove(state, message) { 17 | state.stack = state.stack.filter(m => m !== message) 18 | } 19 | }, 20 | 21 | actions: { 22 | info({ commit }, message) { 23 | commit('add', { 24 | timeout: 3000, 25 | type: 'info', 26 | message 27 | }) 28 | }, 29 | 30 | error({ commit }, message) { 31 | commit('add', { 32 | timeout: 3000, 33 | type: 'error', 34 | message 35 | }) 36 | }, 37 | 38 | remove({ commit }, message) { 39 | commit('remove', message) 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/store/storage.js: -------------------------------------------------------------------------------- 1 | const STATE_KEY = 'vuex-state' 2 | 3 | export default (options) => (store) => { 4 | const rawStoredState = localStorage[STATE_KEY] 5 | 6 | if (rawStoredState) { 7 | const storedState = JSON.parse(rawStoredState) 8 | store.replaceState(Object.assign(store.state, storedState)) 9 | } 10 | 11 | return store.subscribe((mutation, state) => { 12 | if (options.destroyOn && options.destroyOn.includes(mutation.type)) { 13 | return localStorage.removeItem(STATE_KEY) 14 | } 15 | 16 | const newState = options.storedKeys.reduce((map, key) => { 17 | map[key] = state[key] 18 | return map 19 | }, {}) 20 | 21 | localStorage[STATE_KEY] = JSON.stringify(newState) 22 | }) 23 | } 24 | -------------------------------------------------------------------------------- /src/validation/index.js: -------------------------------------------------------------------------------- 1 | export const required = v => !!v || 'is required' 2 | export const minLength = number => v => (v || '').length >= number || `should have more than ${number} characters` 3 | export const maxLength = number => v => (v || '').length <= number || `should have less than ${number} characters` 4 | export const email = v => /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'is not a valid email' 5 | -------------------------------------------------------------------------------- /src/views/Article.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 38 | -------------------------------------------------------------------------------- /src/views/EditArticle.vue: -------------------------------------------------------------------------------- 1 | 13 | 14 | 75 | -------------------------------------------------------------------------------- /src/views/Home.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 19 | -------------------------------------------------------------------------------- /src/views/Login.vue: -------------------------------------------------------------------------------- 1 | 22 | 23 | 66 | --------------------------------------------------------------------------------