├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .postcssrc.js ├── README.md ├── babel.config.js ├── build ├── build.js ├── check-versions.js ├── logo.png ├── utils.js ├── vue-loader.conf.js ├── webpack.base.conf.js ├── webpack.dev.conf.js ├── webpack.prod.conf.js └── webpack.test.conf.js ├── config ├── dev.env.js ├── index.js ├── prod.env.js └── test.env.js ├── index.html ├── package.json ├── src ├── App.vue ├── assets │ ├── dog-profile.jpeg │ └── logo.png ├── components │ ├── account │ │ └── index.vue │ ├── footer │ │ └── index.vue │ ├── home │ │ ├── fakeFeed.js │ │ ├── feedItem.vue │ │ └── index.vue │ ├── lib │ │ ├── center-container.vue │ │ └── loading.vue │ ├── login │ │ └── index.vue │ └── navigation │ │ └── index.vue ├── main.js ├── router │ └── index.js ├── store │ ├── actions │ │ ├── auth.js │ │ └── user.js │ ├── index.js │ └── modules │ │ ├── auth.js │ │ └── user.js └── utils │ └── api.js ├── static └── .gitkeep └── vue.config.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | /config/ 3 | /dist/ 4 | /*.js 5 | /test/unit/coverage/ 6 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | node: true 5 | }, 6 | extends: ["plugin:vue/essential", "@vue/prettier"], 7 | rules: { 8 | "no-console": process.env.NODE_ENV === "production" ? "error" : "off", 9 | "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off" 10 | }, 11 | parserOptions: { 12 | parser: "babel-eslint" 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | /dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | /test/unit/coverage/ 8 | /test/e2e/reports/ 9 | selenium-debug.log 10 | 11 | # Editor directories and files 12 | .idea 13 | .vscode 14 | *.suo 15 | *.ntvs* 16 | *.njsproj 17 | *.sln 18 | -------------------------------------------------------------------------------- /.postcssrc.js: -------------------------------------------------------------------------------- 1 | // https://github.com/michael-ciniawsky/postcss-load-config 2 | 3 | module.exports = { 4 | "plugins": { 5 | // to edit target browsers: use "browserslist" field in package.json 6 | "autoprefixer": {} 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vue-auth-handling 2 | 3 | ## The project 4 | 5 | This repo is a support for [this article](https://blog.sqreen.io/authentication-best-practices-vue/) and a [talk](https://docs.google.com/presentation/d/17e4U-XDMuVXGIj26OXndfAsXOpFjPjjb6QHhTJbBZnI/edit?usp=sharing) given to VueJS Paris meetup 6 | 7 | [Demo](https://vue-auth-example.netlify.com) of this repo. 8 | 9 | 10 | 11 | ## Build Setup 12 | 13 | ``` bash 14 | # install dependencies 15 | npm install 16 | 17 | # serve with hot reload at localhost:8080 18 | npm run serve 19 | 20 | # build for production with minification 21 | npm run build 22 | 23 | # build for production and view the bundle analyzer report 24 | npm run build --report 25 | 26 | # run unit tests 27 | npm run unit 28 | 29 | # run e2e tests 30 | npm run e2e 31 | 32 | # run all tests 33 | npm test 34 | ``` 35 | 36 | For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader). 37 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ["@vue/cli-plugin-babel/preset"] 3 | }; 4 | -------------------------------------------------------------------------------- /build/build.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | require('./check-versions')() 3 | 4 | process.env.NODE_ENV = 'production-2' 5 | 6 | const ora = require('ora') 7 | const rm = require('rimraf') 8 | const path = require('path') 9 | const chalk = require('chalk') 10 | const webpack = require('webpack') 11 | const config = require('../config') 12 | const webpackConfig = require('./webpack.prod.conf') 13 | 14 | const spinner = ora('building for production...') 15 | spinner.start() 16 | 17 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { 18 | if (err) throw err 19 | webpack(webpackConfig, function (err, stats) { 20 | spinner.stop() 21 | if (err) throw err 22 | process.stdout.write(stats.toString({ 23 | colors: true, 24 | modules: false, 25 | children: false, 26 | chunks: false, 27 | chunkModules: false 28 | }) + '\n\n') 29 | 30 | if (stats.hasErrors()) { 31 | console.log(chalk.red(' Build failed with errors.\n')) 32 | process.exit(1) 33 | } 34 | 35 | console.log(chalk.cyan(' Build complete.\n')) 36 | console.log(chalk.yellow( 37 | ' Tip: built files are meant to be served over an HTTP server.\n' + 38 | ' Opening index.html over file:// won\'t work.\n' 39 | )) 40 | }) 41 | }) 42 | -------------------------------------------------------------------------------- /build/check-versions.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const chalk = require('chalk') 3 | const semver = require('semver') 4 | const packageConfig = require('../package.json') 5 | const shell = require('shelljs') 6 | function exec (cmd) { 7 | return require('child_process').execSync(cmd).toString().trim() 8 | } 9 | 10 | const versionRequirements = [ 11 | { 12 | name: 'node', 13 | currentVersion: semver.clean(process.version), 14 | versionRequirement: packageConfig.engines.node 15 | } 16 | ] 17 | 18 | if (shell.which('npm')) { 19 | versionRequirements.push({ 20 | name: 'npm', 21 | currentVersion: exec('npm --version'), 22 | versionRequirement: packageConfig.engines.npm 23 | }) 24 | } 25 | 26 | module.exports = function () { 27 | const warnings = [] 28 | for (let i = 0; i < versionRequirements.length; i++) { 29 | const mod = versionRequirements[i] 30 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { 31 | warnings.push(mod.name + ': ' + 32 | chalk.red(mod.currentVersion) + ' should be ' + 33 | chalk.green(mod.versionRequirement) 34 | ) 35 | } 36 | } 37 | 38 | if (warnings.length) { 39 | console.log('') 40 | console.log(chalk.yellow('To use this template, you must update following to modules:')) 41 | console.log() 42 | for (let i = 0; i < warnings.length; i++) { 43 | const warning = warnings[i] 44 | console.log(' ' + warning) 45 | } 46 | console.log() 47 | process.exit(1) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /build/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sqreen/vue-authentication-example/f2d08f1b2113dada7ad52e15803b6a595e35fcee/build/logo.png -------------------------------------------------------------------------------- /build/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const config = require('../config') 4 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 5 | const pkg = require('../package.json') 6 | 7 | exports.assetsPath = function (_path) { 8 | const assetsSubDirectory = process.env.NODE_ENV === 'production' 9 | ? config.build.assetsSubDirectory 10 | : config.dev.assetsSubDirectory 11 | return path.posix.join(assetsSubDirectory, _path) 12 | } 13 | 14 | exports.cssLoaders = function (options) { 15 | options = options || {} 16 | 17 | const cssLoader = { 18 | loader: 'css-loader', 19 | options: { 20 | minimize: process.env.NODE_ENV === 'production', 21 | sourceMap: options.sourceMap 22 | } 23 | } 24 | 25 | var postcssLoader = { 26 | loader: 'postcss-loader', 27 | options: { 28 | sourceMap: options.sourceMap 29 | } 30 | } 31 | 32 | // generate loader string to be used with extract text plugin 33 | function generateLoaders (loader, loaderOptions) { 34 | const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] 35 | if (loader) { 36 | loaders.push({ 37 | loader: loader + '-loader', 38 | options: Object.assign({}, loaderOptions, { 39 | sourceMap: options.sourceMap 40 | }) 41 | }) 42 | } 43 | 44 | // Extract CSS when that option is specified 45 | // (which is the case during production build) 46 | if (options.extract) { 47 | return ExtractTextPlugin.extract({ 48 | use: loaders, 49 | fallback: 'vue-style-loader' 50 | }) 51 | } else { 52 | return ['vue-style-loader'].concat(loaders) 53 | } 54 | } 55 | 56 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html 57 | return { 58 | css: generateLoaders(), 59 | postcss: generateLoaders(), 60 | less: generateLoaders('less'), 61 | sass: generateLoaders('sass', { indentedSyntax: true }), 62 | scss: generateLoaders('sass'), 63 | stylus: generateLoaders('stylus'), 64 | styl: generateLoaders('stylus') 65 | } 66 | } 67 | 68 | // Generate loaders for standalone style files (outside of .vue) 69 | exports.styleLoaders = function (options) { 70 | const output = [] 71 | const loaders = exports.cssLoaders(options) 72 | for (const extension in loaders) { 73 | const loader = loaders[extension] 74 | output.push({ 75 | test: new RegExp('\\.' + extension + '$'), 76 | use: loader 77 | }) 78 | } 79 | return output 80 | } 81 | 82 | exports.createNotifierCallback = function () { 83 | const notifier = require('node-notifier') 84 | 85 | return (severity, errors) => { 86 | if (severity !== 'error') { 87 | return 88 | } 89 | const error = errors[0] 90 | 91 | const filename = error.file.split('!').pop() 92 | notifier.notify({ 93 | title: pkg.name, 94 | message: severity + ': ' + error.name, 95 | subtitle: filename || '', 96 | icon: path.join(__dirname, 'logo.png') 97 | }) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /build/vue-loader.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const utils = require('./utils') 3 | const config = require('../config') 4 | const isProduction = process.env.NODE_ENV === 'production' 5 | const sourceMapEnabled = isProduction 6 | ? config.build.productionSourceMap 7 | : config.dev.cssSourceMap 8 | 9 | 10 | module.exports = { 11 | loaders: utils.cssLoaders({ 12 | sourceMap: sourceMapEnabled, 13 | extract: isProduction 14 | }), 15 | cssSourceMap: sourceMapEnabled, 16 | transformToRequire: { 17 | video: 'src', 18 | source: 'src', 19 | img: 'src', 20 | image: 'xlink:href' 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const utils = require('./utils') 4 | const config = require('../config') 5 | const vueLoaderConfig = require('./vue-loader.conf') 6 | 7 | function resolve (dir) { 8 | return path.join(__dirname, '..', dir) 9 | } 10 | 11 | module.exports = { 12 | context: path.resolve(__dirname, '../'), 13 | entry: { 14 | app: './src/main.js' 15 | }, 16 | output: { 17 | path: config.build.assetsRoot, 18 | filename: '[name].js', 19 | publicPath: process.env.NODE_ENV === 'production' 20 | ? config.build.assetsPublicPath 21 | : config.dev.assetsPublicPath 22 | }, 23 | resolve: { 24 | extensions: ['.js', '.vue', '.json'], 25 | alias: { 26 | 'vue$': 'vue/dist/vue.esm.js', 27 | '@': resolve('src'), 28 | 'components': resolve('src/components'), 29 | 'actions': resolve('src/store/actions'), 30 | 'utils': resolve('src/utils'), 31 | }, 32 | }, 33 | module: { 34 | rules: [ 35 | ...(config.dev.useEslint? [{ 36 | test: /\.(js|vue)$/, 37 | loader: 'eslint-loader', 38 | enforce: 'pre', 39 | include: [resolve('src'), resolve('test')], 40 | options: { 41 | formatter: require('eslint-friendly-formatter'), 42 | emitWarning: !config.dev.showEslintErrorsInOverlay 43 | } 44 | }] : []), 45 | { 46 | test: /\.vue$/, 47 | loader: 'vue-loader', 48 | options: vueLoaderConfig 49 | }, 50 | { 51 | test: /\.js$/, 52 | loader: 'babel-loader', 53 | include: [resolve('src'), resolve('test')] 54 | }, 55 | { 56 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 57 | loader: 'url-loader', 58 | options: { 59 | limit: 10000, 60 | name: utils.assetsPath('img/[name].[hash:7].[ext]') 61 | } 62 | }, 63 | { 64 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, 65 | loader: 'url-loader', 66 | options: { 67 | limit: 10000, 68 | name: utils.assetsPath('media/[name].[hash:7].[ext]') 69 | } 70 | }, 71 | { 72 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 73 | loader: 'url-loader', 74 | options: { 75 | limit: 10000, 76 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]') 77 | } 78 | } 79 | ] 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const utils = require('./utils') 3 | const webpack = require('webpack') 4 | const config = require('../config') 5 | const merge = require('webpack-merge') 6 | const baseWebpackConfig = require('./webpack.base.conf') 7 | const HtmlWebpackPlugin = require('html-webpack-plugin') 8 | const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 9 | const portfinder = require('portfinder') 10 | 11 | const devWebpackConfig = merge(baseWebpackConfig, { 12 | module: { 13 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) 14 | }, 15 | // cheap-module-eval-source-map is faster for development 16 | devtool: config.dev.devtool, 17 | 18 | // these devServer options should be customized in /config/index.js 19 | devServer: { 20 | historyApiFallback: true, 21 | hot: true, 22 | host: process.env.HOST || config.dev.host, 23 | port: process.env.PORT || config.dev.port, 24 | open: config.dev.autoOpenBrowser, 25 | overlay: config.dev.errorOverlay ? { 26 | warnings: false, 27 | errors: true, 28 | } : false, 29 | publicPath: config.dev.assetsPublicPath, 30 | proxy: config.dev.proxyTable, 31 | quiet: true, // necessary for FriendlyErrorsPlugin 32 | watchOptions: { 33 | poll: config.dev.poll, 34 | } 35 | }, 36 | plugins: [ 37 | new webpack.DefinePlugin({ 38 | 'process.env': require('../config/dev.env') 39 | }), 40 | new webpack.HotModuleReplacementPlugin(), 41 | new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. 42 | new webpack.NoEmitOnErrorsPlugin(), 43 | // https://github.com/ampedandwired/html-webpack-plugin 44 | new HtmlWebpackPlugin({ 45 | filename: 'index.html', 46 | template: 'index.html', 47 | inject: true 48 | }), 49 | new FriendlyErrorsPlugin() 50 | ] 51 | }) 52 | 53 | module.exports = new Promise((resolve, reject) => { 54 | portfinder.basePort = process.env.PORT || config.dev.port 55 | portfinder.getPort((err, port) => { 56 | if (err) { 57 | reject(err) 58 | } else { 59 | // publish the new Port, necessary for e2e tests 60 | process.env.PORT = port 61 | // add port to devServer config 62 | devWebpackConfig.devServer.port = port 63 | 64 | // Add FriendlyErrorsPlugin 65 | devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ 66 | compilationSuccessInfo: { 67 | messages: [`Your application is running here: http://${config.dev.host}:${port}`], 68 | }, 69 | onErrors: config.dev.notifyOnErrors 70 | ? utils.createNotifierCallback() 71 | : undefined 72 | })) 73 | 74 | resolve(devWebpackConfig) 75 | } 76 | }) 77 | }) 78 | -------------------------------------------------------------------------------- /build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const utils = require('./utils') 4 | const webpack = require('webpack') 5 | const config = require('../config') 6 | const merge = require('webpack-merge') 7 | const baseWebpackConfig = require('./webpack.base.conf') 8 | const CopyWebpackPlugin = require('copy-webpack-plugin') 9 | const HtmlWebpackPlugin = require('html-webpack-plugin') 10 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 11 | const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 12 | 13 | const env = process.env.NODE_ENV === 'testing' 14 | ? require('../config/test.env') 15 | : require('../config/prod.env') 16 | 17 | const webpackConfig = merge(baseWebpackConfig, { 18 | module: { 19 | rules: utils.styleLoaders({ 20 | sourceMap: config.build.productionSourceMap, 21 | extract: true, 22 | usePostCSS: true 23 | }) 24 | }, 25 | devtool: config.build.productionSourceMap ? config.build.devtool : false, 26 | output: { 27 | path: config.build.assetsRoot, 28 | filename: utils.assetsPath('js/[name].[chunkhash].js'), 29 | chunkFilename: utils.assetsPath('js/[name].[chunkhash].js') 30 | }, 31 | plugins: [ 32 | // http://vuejs.github.io/vue-loader/en/workflow/production.html 33 | new webpack.DefinePlugin({ 34 | 'process.env': env 35 | }), 36 | // UglifyJs do not support ES6+, you can also use babel-minify for better treeshaking: https://github.com/babel/minify 37 | new webpack.optimize.UglifyJsPlugin({ 38 | compress: { 39 | warnings: false 40 | }, 41 | sourceMap: config.build.productionSourceMap, 42 | parallel: true 43 | }), 44 | // extract css into its own file 45 | new ExtractTextPlugin({ 46 | filename: utils.assetsPath('css/[name].[contenthash].css'), 47 | // set the following option to `true` if you want to extract CSS from 48 | // codesplit chunks into this main css file as well. 49 | // This will result in *all* of your app's CSS being loaded upfront. 50 | allChunks: false, 51 | }), 52 | // Compress extracted CSS. We are using this plugin so that possible 53 | // duplicated CSS from different components can be deduped. 54 | new OptimizeCSSPlugin({ 55 | cssProcessorOptions: config.build.productionSourceMap 56 | ? { safe: true, map: { inline: false } } 57 | : { safe: true } 58 | }), 59 | // generate dist index.html with correct asset hash for caching. 60 | // you can customize output by editing /index.html 61 | // see https://github.com/ampedandwired/html-webpack-plugin 62 | new HtmlWebpackPlugin({ 63 | filename: process.env.NODE_ENV === 'testing' 64 | ? 'index.html' 65 | : config.build.index, 66 | template: 'index.html', 67 | inject: true, 68 | minify: { 69 | removeComments: true, 70 | collapseWhitespace: true, 71 | removeAttributeQuotes: true 72 | // more options: 73 | // https://github.com/kangax/html-minifier#options-quick-reference 74 | }, 75 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin 76 | chunksSortMode: 'dependency' 77 | }), 78 | // keep module.id stable when vender modules does not change 79 | new webpack.HashedModuleIdsPlugin(), 80 | // enable scope hoisting 81 | new webpack.optimize.ModuleConcatenationPlugin(), 82 | // split vendor js into its own file 83 | new webpack.optimize.CommonsChunkPlugin({ 84 | name: 'vendor', 85 | minChunks: function (module) { 86 | // any required modules inside node_modules are extracted to vendor 87 | return ( 88 | module.resource && 89 | /\.js$/.test(module.resource) && 90 | module.resource.indexOf( 91 | path.join(__dirname, '../node_modules') 92 | ) === 0 93 | ) 94 | } 95 | }), 96 | // extract webpack runtime and module manifest to its own file in order to 97 | // prevent vendor hash from being updated whenever app bundle is updated 98 | new webpack.optimize.CommonsChunkPlugin({ 99 | name: 'manifest', 100 | minChunks: Infinity, 101 | }), 102 | // This instance extracts shared chunks from code splitted chunks and bundles them 103 | // in a separate chunk, similar to the vendor chunk 104 | // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk 105 | new webpack.optimize.CommonsChunkPlugin({ 106 | name: 'app', 107 | async: 'vendor-async', 108 | children: true, 109 | minChunks: 3, 110 | }), 111 | 112 | // copy custom static assets 113 | new CopyWebpackPlugin([ 114 | { 115 | from: path.resolve(__dirname, '../static'), 116 | to: config.build.assetsSubDirectory, 117 | ignore: ['.*'] 118 | } 119 | ]) 120 | ] 121 | }) 122 | 123 | if (config.build.productionGzip) { 124 | const CompressionWebpackPlugin = require('compression-webpack-plugin') 125 | 126 | webpackConfig.plugins.push( 127 | new CompressionWebpackPlugin({ 128 | asset: '[path].gz[query]', 129 | algorithm: 'gzip', 130 | test: new RegExp( 131 | '\\.(' + 132 | config.build.productionGzipExtensions.join('|') + 133 | ')$' 134 | ), 135 | threshold: 10240, 136 | minRatio: 0.8 137 | }) 138 | ) 139 | } 140 | 141 | if (config.build.bundleAnalyzerReport) { 142 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 143 | webpackConfig.plugins.push(new BundleAnalyzerPlugin()) 144 | } 145 | 146 | module.exports = webpackConfig 147 | -------------------------------------------------------------------------------- /build/webpack.test.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | // This is the webpack config used for unit tests. 3 | 4 | const utils = require('./utils') 5 | const webpack = require('webpack') 6 | const merge = require('webpack-merge') 7 | const baseWebpackConfig = require('./webpack.base.conf') 8 | 9 | const webpackConfig = merge(baseWebpackConfig, { 10 | // use inline sourcemap for karma-sourcemap-loader 11 | module: { 12 | rules: utils.styleLoaders() 13 | }, 14 | devtool: '#inline-source-map', 15 | resolveLoader: { 16 | alias: { 17 | // necessary to to make lang="scss" work in test when using vue-loader's ?inject option 18 | // see discussion at https://github.com/vuejs/vue-loader/issues/724 19 | 'scss-loader': 'sass-loader' 20 | } 21 | }, 22 | plugins: [ 23 | new webpack.DefinePlugin({ 24 | 'process.env': require('../config/test.env') 25 | }) 26 | ] 27 | }) 28 | 29 | // no need for app entry during tests 30 | delete webpackConfig.entry 31 | 32 | module.exports = webpackConfig 33 | -------------------------------------------------------------------------------- /config/dev.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const merge = require('webpack-merge') 3 | const prodEnv = require('./prod.env') 4 | 5 | module.exports = merge(prodEnv, { 6 | NODE_ENV: '"development"' 7 | }) 8 | -------------------------------------------------------------------------------- /config/index.js: -------------------------------------------------------------------------------- 1 | 2 | 'use strict' 3 | // Template version: 1.2.0 4 | // see http://vuejs-templates.github.io/webpack for documentation. 5 | 6 | const path = require('path') 7 | 8 | module.exports = { 9 | dev: { 10 | 11 | // Paths 12 | assetsSubDirectory: 'static', 13 | assetsPublicPath: '/', 14 | proxyTable: {}, 15 | 16 | // Various Dev Server settings 17 | host: 'localhost', // can be overwritten by process.env.HOST 18 | port: 8080, // can be overwritten by process.env.HOST, if port is in use, a free one will be determined 19 | autoOpenBrowser: false, 20 | errorOverlay: true, 21 | notifyOnErrors: true, 22 | poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- 23 | 24 | // Use Eslint Loader? 25 | // If true, your code will be linted during bundling and 26 | // linting errors and warings will be shown in the console. 27 | useEslint: true, 28 | // If true, eslint errors and warings will also be shown in the error overlay 29 | // in the browser. 30 | showEslintErrorsInOverlay: false, 31 | 32 | /** 33 | * Source Maps 34 | */ 35 | 36 | // https://webpack.js.org/configuration/devtool/#development 37 | devtool: 'eval-source-map', 38 | 39 | // If you have problems debugging vue-files in devtools, 40 | // set this to false - it *may* help 41 | // https://vue-loader.vuejs.org/en/options.html#cachebusting 42 | cacheBusting: true, 43 | 44 | // CSS Sourcemaps off by default because relative paths are "buggy" 45 | // with this option, according to the CSS-Loader README 46 | // (https://github.com/webpack/css-loader#sourcemaps) 47 | // In our experience, they generally work as expected, 48 | // just be aware of this issue when enabling this option. 49 | cssSourceMap: false, 50 | }, 51 | 52 | build: { 53 | // Template for index.html 54 | index: path.resolve(__dirname, '../dist/index.html'), 55 | 56 | // Paths 57 | assetsRoot: path.resolve(__dirname, '../dist'), 58 | assetsSubDirectory: 'static', 59 | assetsPublicPath: '/', 60 | 61 | /** 62 | * SourceMap 63 | */ 64 | productionSourceMap: true, 65 | // https://webpack.js.org/configuration/devtool/#production 66 | devtool: '#source-map', 67 | 68 | // Gzip off by default as many popular static hosts such as 69 | // Surge or Netlify already gzip all static assets for you. 70 | // Before setting to `true`, make sure to: 71 | // npm install --save-dev compression-webpack-plugin 72 | productionGzip: false, 73 | productionGzipExtensions: ['js', 'css'], 74 | 75 | // Run the build command with an extra argument to 76 | // View the bundle analyzer report after build finishes: 77 | // `npm run build --report` 78 | // Set to `true` or `false` to always turn it on or off 79 | bundleAnalyzerReport: process.env.npm_config_report 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /config/prod.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | module.exports = { 3 | NODE_ENV: '"production-2"' 4 | } 5 | -------------------------------------------------------------------------------- /config/test.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const merge = require('webpack-merge') 3 | const devEnv = require('./dev.env') 4 | 5 | module.exports = merge(devEnv, { 6 | NODE_ENV: '"testing"' 7 | }) 8 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | auth-handling 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "auth-handling", 3 | "version": "1.0.0", 4 | "description": "A Vue.js project", 5 | "author": "vouill ", 6 | "private": true, 7 | "scripts": { 8 | "serve": "vue-cli-service serve", 9 | "build": "vue-cli-service build", 10 | "lint": "vue-cli-service lint" 11 | }, 12 | "dependencies": { 13 | "core-js": "^3.4.4", 14 | "faker": "^4.1.0", 15 | "vue": "^2.6.10", 16 | "vue-router": "^3.1.3", 17 | "vuex": "^3.1.2" 18 | }, 19 | "devDependencies": { 20 | "@vue/cli-plugin-babel": "^4.1.0", 21 | "@vue/cli-plugin-eslint": "^4.1.0", 22 | "@vue/cli-plugin-router": "^4.1.0", 23 | "@vue/cli-plugin-vuex": "^4.1.0", 24 | "@vue/cli-service": "^4.1.0", 25 | "@vue/eslint-config-prettier": "^5.0.0", 26 | "babel-eslint": "^10.0.3", 27 | "eslint": "^5.16.0", 28 | "eslint-plugin-prettier": "^3.1.1", 29 | "eslint-plugin-vue": "^5.0.0", 30 | "node-sass": "^4.13.0", 31 | "prettier": "^1.19.1", 32 | "sass-loader": "^8.0.0", 33 | "vue-template-compiler": "^2.6.10" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 12 | 13 | 31 | 32 | 44 | 45 | 50 | -------------------------------------------------------------------------------- /src/assets/dog-profile.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sqreen/vue-authentication-example/f2d08f1b2113dada7ad52e15803b6a595e35fcee/src/assets/dog-profile.jpeg -------------------------------------------------------------------------------- /src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sqreen/vue-authentication-example/f2d08f1b2113dada7ad52e15803b6a595e35fcee/src/assets/logo.png -------------------------------------------------------------------------------- /src/components/account/index.vue: -------------------------------------------------------------------------------- 1 | /** * Created by vouill on 11/13/17. */ 2 | 3 | 14 | 15 | 26 | 27 | 35 | -------------------------------------------------------------------------------- /src/components/footer/index.vue: -------------------------------------------------------------------------------- 1 | /** * Created by vouill on 11/14/17. */ 2 | 3 | 8 | 9 | 24 | 25 | 30 | -------------------------------------------------------------------------------- /src/components/home/fakeFeed.js: -------------------------------------------------------------------------------- 1 | import faker from "faker"; 2 | 3 | function feedGenerator(nb) { 4 | let res = []; 5 | for (var i = 1; i <= nb; i++) { 6 | res.push(generateFeed()); 7 | } 8 | return res; 9 | } 10 | 11 | function generateFeed() { 12 | return { 13 | name: `${faker.name.firstName()} ${faker.name.lastName()}`, 14 | content: faker.random.words(20) 15 | }; 16 | } 17 | 18 | export default feedGenerator(10); 19 | -------------------------------------------------------------------------------- /src/components/home/feedItem.vue: -------------------------------------------------------------------------------- 1 | /** * Created by vouill on 11/13/17. */ 2 | 3 | 9 | 10 | 16 | 22 | -------------------------------------------------------------------------------- /src/components/home/index.vue: -------------------------------------------------------------------------------- 1 | /** * Created by vouill on 11/13/17. */ 2 | 3 | 19 | 20 | 27 | 28 | 51 | -------------------------------------------------------------------------------- /src/components/lib/center-container.vue: -------------------------------------------------------------------------------- 1 | /** * Created by vouill on 11/14/17. */ 2 | 3 | 8 | 9 | 16 | 17 | 22 | -------------------------------------------------------------------------------- /src/components/lib/loading.vue: -------------------------------------------------------------------------------- 1 | /** * Created by vouill on 11/13/17. */ 2 | 3 | 34 | 35 | 50 | 51 | 61 | -------------------------------------------------------------------------------- /src/components/login/index.vue: -------------------------------------------------------------------------------- 1 | /** * Created by vouill on 11/13/17. */ 2 | 3 | 21 | 22 | 30 | 31 | 52 | -------------------------------------------------------------------------------- /src/components/navigation/index.vue: -------------------------------------------------------------------------------- 1 | /** * Created by vouill on 11/13/17. */ 2 | 3 | 27 | 28 | 60 | 61 | 81 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | // The Vue build version to load with the `import` command 2 | // (runtime-only or standalone) has been set in webpack.base.conf with an alias. 3 | import Vue from "vue"; 4 | import App from "./App"; 5 | import router from "./router"; 6 | import store from "./store"; 7 | import Loading from "components/lib/loading"; 8 | import CenterContainer from "components/lib/center-container"; 9 | 10 | Vue.config.productionTip = false; 11 | 12 | Vue.component("loading", Loading); 13 | Vue.component("center-container", CenterContainer); 14 | /* eslint-disable no-new */ 15 | new Vue({ 16 | el: "#app", 17 | router, 18 | store, 19 | template: "", 20 | components: { App } 21 | }); 22 | -------------------------------------------------------------------------------- /src/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from "vue"; 2 | import Router from "vue-router"; 3 | import Home from "components/home"; 4 | import Account from "components/account"; 5 | import Login from "components/login"; 6 | import store from "../store"; 7 | 8 | Vue.use(Router); 9 | 10 | const ifNotAuthenticated = (to, from, next) => { 11 | if (!store.getters.isAuthenticated) { 12 | next(); 13 | return; 14 | } 15 | next("/"); 16 | }; 17 | 18 | const ifAuthenticated = (to, from, next) => { 19 | if (store.getters.isAuthenticated) { 20 | next(); 21 | return; 22 | } 23 | next("/login"); 24 | }; 25 | 26 | export default new Router({ 27 | mode: "history", 28 | routes: [ 29 | { 30 | path: "/", 31 | name: "Home", 32 | component: Home 33 | }, 34 | { 35 | path: "/account", 36 | name: "Account", 37 | component: Account, 38 | beforeEnter: ifAuthenticated 39 | }, 40 | { 41 | path: "/login", 42 | name: "Login", 43 | component: Login, 44 | beforeEnter: ifNotAuthenticated 45 | } 46 | ] 47 | }); 48 | -------------------------------------------------------------------------------- /src/store/actions/auth.js: -------------------------------------------------------------------------------- 1 | export const AUTH_REQUEST = "AUTH_REQUEST"; 2 | export const AUTH_SUCCESS = "AUTH_SUCCESS"; 3 | export const AUTH_ERROR = "AUTH_ERROR"; 4 | export const AUTH_LOGOUT = "AUTH_LOGOUT"; 5 | -------------------------------------------------------------------------------- /src/store/actions/user.js: -------------------------------------------------------------------------------- 1 | export const USER_REQUEST = "USER_REQUEST"; 2 | export const USER_SUCCESS = "USER_SUCCESS"; 3 | export const USER_ERROR = "USER_ERROR"; 4 | -------------------------------------------------------------------------------- /src/store/index.js: -------------------------------------------------------------------------------- 1 | import Vue from "vue"; 2 | import Vuex from "vuex"; 3 | import user from "./modules/user"; 4 | import auth from "./modules/auth"; 5 | Vue.use(Vuex); 6 | 7 | const debug = process.env.NODE_ENV !== "production"; 8 | 9 | export default new Vuex.Store({ 10 | modules: { 11 | user, 12 | auth 13 | }, 14 | strict: debug 15 | }); 16 | -------------------------------------------------------------------------------- /src/store/modules/auth.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable promise/param-names */ 2 | import { 3 | AUTH_REQUEST, 4 | AUTH_ERROR, 5 | AUTH_SUCCESS, 6 | AUTH_LOGOUT 7 | } from "../actions/auth"; 8 | import { USER_REQUEST } from "../actions/user"; 9 | import apiCall from "utils/api"; 10 | 11 | const state = { 12 | token: localStorage.getItem("user-token") || "", 13 | status: "", 14 | hasLoadedOnce: false 15 | }; 16 | 17 | const getters = { 18 | isAuthenticated: state => !!state.token, 19 | authStatus: state => state.status 20 | }; 21 | 22 | const actions = { 23 | [AUTH_REQUEST]: ({ commit, dispatch }, user) => { 24 | return new Promise((resolve, reject) => { 25 | commit(AUTH_REQUEST); 26 | apiCall({ url: "auth", data: user, method: "POST" }) 27 | .then(resp => { 28 | localStorage.setItem("user-token", resp.token); 29 | // Here set the header of your ajax library to the token value. 30 | // example with axios 31 | // axios.defaults.headers.common['Authorization'] = resp.token 32 | commit(AUTH_SUCCESS, resp); 33 | dispatch(USER_REQUEST); 34 | resolve(resp); 35 | }) 36 | .catch(err => { 37 | commit(AUTH_ERROR, err); 38 | localStorage.removeItem("user-token"); 39 | reject(err); 40 | }); 41 | }); 42 | }, 43 | [AUTH_LOGOUT]: ({ commit }) => { 44 | return new Promise(resolve => { 45 | commit(AUTH_LOGOUT); 46 | localStorage.removeItem("user-token"); 47 | resolve(); 48 | }); 49 | } 50 | }; 51 | 52 | const mutations = { 53 | [AUTH_REQUEST]: state => { 54 | state.status = "loading"; 55 | }, 56 | [AUTH_SUCCESS]: (state, resp) => { 57 | state.status = "success"; 58 | state.token = resp.token; 59 | state.hasLoadedOnce = true; 60 | }, 61 | [AUTH_ERROR]: state => { 62 | state.status = "error"; 63 | state.hasLoadedOnce = true; 64 | }, 65 | [AUTH_LOGOUT]: state => { 66 | state.token = ""; 67 | } 68 | }; 69 | 70 | export default { 71 | state, 72 | getters, 73 | actions, 74 | mutations 75 | }; 76 | -------------------------------------------------------------------------------- /src/store/modules/user.js: -------------------------------------------------------------------------------- 1 | import { USER_REQUEST, USER_ERROR, USER_SUCCESS } from "../actions/user"; 2 | import apiCall from "utils/api"; 3 | import Vue from "vue"; 4 | import { AUTH_LOGOUT } from "../actions/auth"; 5 | 6 | const state = { status: "", profile: {} }; 7 | 8 | const getters = { 9 | getProfile: state => state.profile, 10 | isProfileLoaded: state => !!state.profile.name 11 | }; 12 | 13 | const actions = { 14 | [USER_REQUEST]: ({ commit, dispatch }) => { 15 | commit(USER_REQUEST); 16 | apiCall({ url: "user/me" }) 17 | .then(resp => { 18 | commit(USER_SUCCESS, resp); 19 | }) 20 | .catch(() => { 21 | commit(USER_ERROR); 22 | // if resp is unauthorized, logout, to 23 | dispatch(AUTH_LOGOUT); 24 | }); 25 | } 26 | }; 27 | 28 | const mutations = { 29 | [USER_REQUEST]: state => { 30 | state.status = "loading"; 31 | }, 32 | [USER_SUCCESS]: (state, resp) => { 33 | state.status = "success"; 34 | Vue.set(state, "profile", resp); 35 | }, 36 | [USER_ERROR]: state => { 37 | state.status = "error"; 38 | }, 39 | [AUTH_LOGOUT]: state => { 40 | state.profile = {}; 41 | } 42 | }; 43 | 44 | export default { 45 | state, 46 | getters, 47 | actions, 48 | mutations 49 | }; 50 | -------------------------------------------------------------------------------- /src/utils/api.js: -------------------------------------------------------------------------------- 1 | const mocks = { 2 | auth: { POST: { token: "This-is-a-mocked-token" } }, 3 | "user/me": { GET: { name: "doggo", title: "sir" } } 4 | }; 5 | 6 | const apiCall = ({ url, method }) => 7 | new Promise((resolve, reject) => { 8 | setTimeout(() => { 9 | try { 10 | resolve(mocks[url][method || "GET"]); 11 | console.log(`Mocked '${url}' - ${method || "GET"}`); 12 | console.log("response: ", mocks[url][method || "GET"]); 13 | } catch (err) { 14 | reject(new Error(err)); 15 | } 16 | }, 1000); 17 | }); 18 | 19 | export default apiCall; 20 | -------------------------------------------------------------------------------- /static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sqreen/vue-authentication-example/f2d08f1b2113dada7ad52e15803b6a595e35fcee/static/.gitkeep -------------------------------------------------------------------------------- /vue.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | lintOnSave: false, 5 | runtimeCompiler: true, 6 | configureWebpack: { 7 | resolve: { 8 | alias: { 9 | components: path.resolve(__dirname, 'src/components/'), 10 | actions: path.resolve(__dirname, 'src/store/actions'), 11 | utils: path.resolve(__dirname, 'src/utils') 12 | } 13 | } 14 | } 15 | }; 16 | --------------------------------------------------------------------------------