├── .browserslistrc ├── .eslintrc.yml ├── .gitignore ├── .nvmrc ├── .rspec ├── .rubocop.yml ├── .ruby-version ├── Gemfile ├── Gemfile.lock ├── Procfile ├── README.md ├── Rakefile ├── app ├── assets │ ├── config │ │ └── manifest.js │ ├── images │ │ └── .keep │ ├── javascripts │ │ ├── application.js │ │ ├── cable.js │ │ └── channels │ │ │ └── .keep │ └── stylesheets │ │ └── application.scss ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── controllers │ ├── application_controller.rb │ ├── concerns │ │ └── .keep │ └── graphql_controller.rb ├── graphql │ ├── mutations │ │ ├── .keep │ │ ├── base_mutation.rb │ │ ├── mutation_result.rb │ │ ├── register_user.rb │ │ ├── sign_in.rb │ │ └── sign_out.rb │ ├── types │ │ ├── .keep │ │ ├── base_enum.rb │ │ ├── base_field.rb │ │ ├── base_input_object.rb │ │ ├── base_interface.rb │ │ ├── base_object.rb │ │ ├── base_scalar.rb │ │ ├── base_union.rb │ │ ├── mutation_type.rb │ │ ├── query_type.rb │ │ └── user_type.rb │ └── vue_graphql_auth_example_schema.rb ├── helpers │ └── application_helper.rb ├── javascript │ ├── components │ │ ├── application.vue │ │ ├── layout │ │ │ └── Navbar.vue │ │ └── shared │ │ │ └── alerts.vue │ ├── mixins │ │ └── applicationSettings.js │ ├── mutations │ │ ├── registerUser.js │ │ ├── signIn.js │ │ └── signOut.js │ ├── packs │ │ ├── application.js │ │ └── configuration │ │ │ ├── apolloProvider.js │ │ │ ├── appConstants.js │ │ │ └── router.js │ ├── pages │ │ ├── home │ │ │ └── show.vue │ │ ├── sign_in │ │ │ └── new.vue │ │ └── sign_up │ │ │ └── new.vue │ ├── router │ │ └── routes.js │ └── store │ │ ├── baseStore.js │ │ └── usersStore.js ├── jobs │ └── application_job.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── application_record.rb │ ├── concerns │ │ ├── .keep │ │ └── graph_ql │ │ │ └── interface.rb │ └── user.rb └── views │ └── layouts │ ├── application.html.erb │ ├── mailer.html.erb │ └── mailer.text.erb ├── bin ├── bundle ├── rails ├── rake ├── rspec ├── setup ├── spring ├── update ├── webpack ├── webpack-dev-server └── yarn ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers │ ├── application_controller_renderer.rb │ ├── assets.rb │ ├── backtrace_silencers.rb │ ├── content_security_policy.rb │ ├── cookies_serializer.rb │ ├── devise.rb │ ├── filter_parameter_logging.rb │ ├── inflections.rb │ ├── mime_types.rb │ └── wrap_parameters.rb ├── locales │ ├── devise.en.yml │ └── en.yml ├── puma.rb ├── routes.rb ├── spring.rb ├── storage.yml ├── webpack │ ├── custom.js │ ├── development.js │ ├── environment.js │ ├── loaders │ │ └── vue.js │ ├── production.js │ └── test.js └── webpacker.yml ├── db ├── migrate │ └── 20190625161516_devise_create_users.rb ├── schema.rb └── seeds.rb ├── demo.gif ├── lib ├── assets │ └── .keep └── tasks │ └── .keep ├── log └── .keep ├── package.json ├── postcss.config.js ├── public ├── 404.html ├── 422.html ├── 500.html ├── apple-touch-icon-precomposed.png ├── apple-touch-icon.png ├── favicon.ico └── robots.txt ├── spec ├── factories │ └── users.rb ├── graphql │ ├── mutations │ │ ├── base_mutation_spec.rb │ │ ├── mutation_result_spec.rb │ │ ├── register_user_spec.rb │ │ ├── sign_in_spec.rb │ │ └── sign_out_spec.rb │ ├── types │ │ └── user_type_spec.rb │ └── vue_graphql_auth_example_schema_spec.rb ├── models │ ├── concerns │ │ └── graph_ql │ │ │ └── interface_spec.rb │ └── user_spec.rb ├── rails_helper.rb ├── requests │ └── graphql_spec.rb ├── spec_helper.rb └── support │ ├── graphql_config.rb │ ├── graphql_support.rb │ └── request_spec_support.rb ├── storage └── .keep ├── test ├── application_system_test_case.rb ├── controllers │ └── .keep ├── fixtures │ ├── .keep │ ├── files │ │ └── .keep │ └── users.yml ├── helpers │ └── .keep ├── integration │ └── .keep ├── mailers │ └── .keep ├── models │ ├── .keep │ └── user_test.rb ├── system │ └── .keep └── test_helper.rb ├── tmp └── .keep ├── vendor └── .keep └── yarn.lock /.browserslistrc: -------------------------------------------------------------------------------- 1 | defaults 2 | -------------------------------------------------------------------------------- /.eslintrc.yml: -------------------------------------------------------------------------------- 1 | extends: ['eslint:recommended', 'plugin:vue/recommended'] 2 | env: 3 | amd: true 4 | browser: true 5 | es6: true 6 | jquery: true 7 | node: true 8 | globals: 9 | module: true 10 | Bloodhound: true 11 | parserOptions: 12 | ecmaVersion: 6 13 | sourceType: 'module' 14 | ecmaFeatures: 15 | experimentalObjectRestSpread: true 16 | rules: 17 | # the leading number is the warn level (1 = warn, 2 = error) 18 | semi: [1, "always"] 19 | max-len: [1, { "code": 80 }] 20 | quotes: [1, "single"] 21 | comma-dangle: [1, "always-multiline"] 22 | no-unused-vars: 1 23 | vue/html-quotes: [1, "double"] 24 | vue/max-attributes-per-line: [1, { 25 | "singleline": 1, 26 | "multiline": { 27 | "max": 1, 28 | "allowFirstLine": true 29 | } 30 | }] 31 | vue/html-self-closing: "never" 32 | vue/attribute-hyphenation: "never" 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore the default SQLite database. 11 | /db/*.sqlite3 12 | /db/*.sqlite3-journal 13 | 14 | # Ignore all logfiles and tempfiles. 15 | /log/* 16 | /tmp/* 17 | !/log/.keep 18 | !/tmp/.keep 19 | 20 | # Ignore uploaded files in development 21 | /storage/* 22 | !/storage/.keep 23 | 24 | /node_modules 25 | /yarn-error.log 26 | 27 | /public/assets 28 | .byebug_history 29 | 30 | # Ignore master key for decrypting credentials and more. 31 | /config/master.key 32 | 33 | /public/packs 34 | /public/packs-test 35 | /node_modules 36 | /yarn-error.log 37 | yarn-debug.log* 38 | .yarn-integrity 39 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 12.4.0 2 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --require spec_helper 2 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | AllCops: 2 | Exclude: 3 | - ./db/schema.rb 4 | 5 | Metrics/BlockLength: 6 | Exclude: 7 | - ./**/*_spec*.rb 8 | - config/routes.rb 9 | 10 | Metrics/MethodLength: 11 | Exclude: 12 | - db/migrate/*.rb 13 | 14 | Metrics/AbcSize: 15 | Exclude: 16 | - db/migrate/*.rb 17 | 18 | Rails/LexicallyScopedActionFilter: 19 | Exclude: 20 | - app/controllers/application_controller.rb 21 | 22 | Layout/MultilineMethodCallIndentation: 23 | EnforcedStyle: indented 24 | 25 | Rails/DynamicFindBy: 26 | Whitelist: 27 | - find_by_gql_id 28 | - find_by_gql_ids 29 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.6.3 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source "https://rubygems.org" 4 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 5 | 6 | ruby File.read("./.ruby-version").strip 7 | 8 | gem "bootsnap", ">= 1.1.0", require: false 9 | gem "bootstrap", ">= 4.3.1" 10 | gem "coffee-rails", "~> 4.2" 11 | gem "devise" 12 | gem "devise-token_authenticatable" 13 | gem "foreman" 14 | gem "graphql" 15 | gem "jbuilder", "~> 2.5" 16 | gem "pg" 17 | gem "puma", "~> 3.11" 18 | gem "rails", "5.2.3" 19 | gem "sass-rails", "~> 5.0" 20 | gem "sprockets", "~> 3.7.2" # version 3.7.1 has a known vulnerability 21 | gem "turbolinks", "~> 5" 22 | gem "uglifier", ">= 1.3.0" 23 | gem "webpacker", "~> 4.0.7" 24 | 25 | group :development do 26 | gem "graphiql-rails" 27 | gem "listen", ">= 3.0.5", "< 3.2" 28 | gem "pry" 29 | gem "pry-nav" 30 | gem "spring" 31 | gem "spring-watcher-listen", "~> 2.0.0" 32 | gem "web-console", ">= 3.3.0" 33 | end 34 | 35 | group :test do 36 | gem "capybara", ">= 2.15" 37 | gem "factory_bot_rails" 38 | gem "rspec-rails" 39 | gem "selenium-webdriver" 40 | end 41 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (5.2.3) 5 | actionpack (= 5.2.3) 6 | nio4r (~> 2.0) 7 | websocket-driver (>= 0.6.1) 8 | actionmailer (5.2.3) 9 | actionpack (= 5.2.3) 10 | actionview (= 5.2.3) 11 | activejob (= 5.2.3) 12 | mail (~> 2.5, >= 2.5.4) 13 | rails-dom-testing (~> 2.0) 14 | actionpack (5.2.3) 15 | actionview (= 5.2.3) 16 | activesupport (= 5.2.3) 17 | rack (~> 2.0) 18 | rack-test (>= 0.6.3) 19 | rails-dom-testing (~> 2.0) 20 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 21 | actionview (5.2.3) 22 | activesupport (= 5.2.3) 23 | builder (~> 3.1) 24 | erubi (~> 1.4) 25 | rails-dom-testing (~> 2.0) 26 | rails-html-sanitizer (~> 1.0, >= 1.0.3) 27 | activejob (5.2.3) 28 | activesupport (= 5.2.3) 29 | globalid (>= 0.3.6) 30 | activemodel (5.2.3) 31 | activesupport (= 5.2.3) 32 | activerecord (5.2.3) 33 | activemodel (= 5.2.3) 34 | activesupport (= 5.2.3) 35 | arel (>= 9.0) 36 | activestorage (5.2.3) 37 | actionpack (= 5.2.3) 38 | activerecord (= 5.2.3) 39 | marcel (~> 0.3.1) 40 | activesupport (5.2.3) 41 | concurrent-ruby (~> 1.0, >= 1.0.2) 42 | i18n (>= 0.7, < 2) 43 | minitest (~> 5.1) 44 | tzinfo (~> 1.1) 45 | addressable (2.6.0) 46 | public_suffix (>= 2.0.2, < 4.0) 47 | arel (9.0.0) 48 | ast (2.4.0) 49 | autoprefixer-rails (9.6.0) 50 | execjs 51 | bcrypt (3.1.13) 52 | bindex (0.7.0) 53 | bootsnap (1.4.4) 54 | msgpack (~> 1.0) 55 | bootstrap (4.3.1) 56 | autoprefixer-rails (>= 9.1.0) 57 | popper_js (>= 1.14.3, < 2) 58 | sassc-rails (>= 2.0.0) 59 | builder (3.2.3) 60 | capybara (3.24.0) 61 | addressable 62 | mini_mime (>= 0.1.3) 63 | nokogiri (~> 1.8) 64 | rack (>= 1.6.0) 65 | rack-test (>= 0.6.3) 66 | regexp_parser (~> 1.5) 67 | xpath (~> 3.2) 68 | childprocess (1.0.1) 69 | rake (< 13.0) 70 | coderay (1.1.2) 71 | coffee-rails (4.2.2) 72 | coffee-script (>= 2.2.0) 73 | railties (>= 4.0.0) 74 | coffee-script (2.4.1) 75 | coffee-script-source 76 | execjs 77 | coffee-script-source (1.12.2) 78 | concurrent-ruby (1.1.5) 79 | crass (1.0.4) 80 | devise (4.6.2) 81 | bcrypt (~> 3.0) 82 | orm_adapter (~> 0.1) 83 | railties (>= 4.1.0, < 6.0) 84 | responders 85 | warden (~> 1.2.3) 86 | devise-token_authenticatable (1.1.0) 87 | devise (>= 4.0.0, < 5.0.0) 88 | diff-lcs (1.3) 89 | erubi (1.8.0) 90 | execjs (2.7.0) 91 | factory_bot (5.0.2) 92 | activesupport (>= 4.2.0) 93 | factory_bot_rails (5.0.2) 94 | factory_bot (~> 5.0.2) 95 | railties (>= 4.2.0) 96 | ffi (1.11.1) 97 | foreman (0.85.0) 98 | thor (~> 0.19.1) 99 | globalid (0.4.2) 100 | activesupport (>= 4.2.0) 101 | graphiql-rails (1.7.0) 102 | railties 103 | sprockets-rails 104 | graphql (1.9.7) 105 | i18n (1.6.0) 106 | concurrent-ruby (~> 1.0) 107 | jaro_winkler (1.5.3) 108 | jbuilder (2.9.1) 109 | activesupport (>= 4.2.0) 110 | listen (3.1.5) 111 | rb-fsevent (~> 0.9, >= 0.9.4) 112 | rb-inotify (~> 0.9, >= 0.9.7) 113 | ruby_dep (~> 1.2) 114 | loofah (2.2.3) 115 | crass (~> 1.0.2) 116 | nokogiri (>= 1.5.9) 117 | mail (2.7.1) 118 | mini_mime (>= 0.1.1) 119 | marcel (0.3.3) 120 | mimemagic (~> 0.3.2) 121 | method_source (0.9.2) 122 | mimemagic (0.3.3) 123 | mini_mime (1.0.1) 124 | mini_portile2 (2.4.0) 125 | minitest (5.11.3) 126 | msgpack (1.3.0) 127 | nio4r (2.3.1) 128 | nokogiri (1.10.3) 129 | mini_portile2 (~> 2.4.0) 130 | orm_adapter (0.5.0) 131 | parallel (1.17.0) 132 | parser (2.6.3.0) 133 | ast (~> 2.4.0) 134 | pg (1.1.4) 135 | popper_js (1.14.5) 136 | powerpack (0.1.2) 137 | pry (0.12.2) 138 | coderay (~> 1.1.0) 139 | method_source (~> 0.9.0) 140 | pry-nav (0.3.0) 141 | pry (>= 0.9.10, < 0.13.0) 142 | public_suffix (3.1.1) 143 | puma (3.12.1) 144 | rack (2.0.7) 145 | rack-proxy (0.6.5) 146 | rack 147 | rack-test (1.1.0) 148 | rack (>= 1.0, < 3) 149 | rails (5.2.3) 150 | actioncable (= 5.2.3) 151 | actionmailer (= 5.2.3) 152 | actionpack (= 5.2.3) 153 | actionview (= 5.2.3) 154 | activejob (= 5.2.3) 155 | activemodel (= 5.2.3) 156 | activerecord (= 5.2.3) 157 | activestorage (= 5.2.3) 158 | activesupport (= 5.2.3) 159 | bundler (>= 1.3.0) 160 | railties (= 5.2.3) 161 | sprockets-rails (>= 2.0.0) 162 | rails-dom-testing (2.0.3) 163 | activesupport (>= 4.2.0) 164 | nokogiri (>= 1.6) 165 | rails-html-sanitizer (1.0.4) 166 | loofah (~> 2.2, >= 2.2.2) 167 | railties (5.2.3) 168 | actionpack (= 5.2.3) 169 | activesupport (= 5.2.3) 170 | method_source 171 | rake (>= 0.8.7) 172 | thor (>= 0.19.0, < 2.0) 173 | rainbow (3.0.0) 174 | rake (12.3.2) 175 | rb-fsevent (0.10.3) 176 | rb-inotify (0.10.0) 177 | ffi (~> 1.0) 178 | regexp_parser (1.5.1) 179 | responders (3.0.0) 180 | actionpack (>= 5.0) 181 | railties (>= 5.0) 182 | rspec-core (3.8.1) 183 | rspec-support (~> 3.8.0) 184 | rspec-expectations (3.8.4) 185 | diff-lcs (>= 1.2.0, < 2.0) 186 | rspec-support (~> 3.8.0) 187 | rspec-mocks (3.8.1) 188 | diff-lcs (>= 1.2.0, < 2.0) 189 | rspec-support (~> 3.8.0) 190 | rspec-rails (3.8.2) 191 | actionpack (>= 3.0) 192 | activesupport (>= 3.0) 193 | railties (>= 3.0) 194 | rspec-core (~> 3.8.0) 195 | rspec-expectations (~> 3.8.0) 196 | rspec-mocks (~> 3.8.0) 197 | rspec-support (~> 3.8.0) 198 | rspec-support (3.8.2) 199 | rubocop (0.60.0) 200 | jaro_winkler (~> 1.5.1) 201 | parallel (~> 1.10) 202 | parser (>= 2.5, != 2.5.1.1) 203 | powerpack (~> 0.1) 204 | rainbow (>= 2.2.2, < 4.0) 205 | ruby-progressbar (~> 1.7) 206 | unicode-display_width (~> 1.4.0) 207 | ruby-progressbar (1.10.1) 208 | ruby_dep (1.5.0) 209 | rubyzip (1.2.3) 210 | sass (3.7.4) 211 | sass-listen (~> 4.0.0) 212 | sass-listen (4.0.0) 213 | rb-fsevent (~> 0.9, >= 0.9.4) 214 | rb-inotify (~> 0.9, >= 0.9.7) 215 | sass-rails (5.0.7) 216 | railties (>= 4.0.0, < 6) 217 | sass (~> 3.1) 218 | sprockets (>= 2.8, < 4.0) 219 | sprockets-rails (>= 2.0, < 4.0) 220 | tilt (>= 1.1, < 3) 221 | sassc (2.0.1) 222 | ffi (~> 1.9) 223 | rake 224 | sassc-rails (2.1.2) 225 | railties (>= 4.0.0) 226 | sassc (>= 2.0) 227 | sprockets (> 3.0) 228 | sprockets-rails 229 | tilt 230 | selenium-webdriver (3.142.3) 231 | childprocess (>= 0.5, < 2.0) 232 | rubyzip (~> 1.2, >= 1.2.2) 233 | spring (2.1.0) 234 | spring-watcher-listen (2.0.1) 235 | listen (>= 2.7, < 4.0) 236 | spring (>= 1.2, < 3.0) 237 | sprockets (3.7.2) 238 | concurrent-ruby (~> 1.0) 239 | rack (> 1, < 3) 240 | sprockets-rails (3.2.1) 241 | actionpack (>= 4.0) 242 | activesupport (>= 4.0) 243 | sprockets (>= 3.0.0) 244 | thor (0.19.4) 245 | thread_safe (0.3.6) 246 | tilt (2.0.9) 247 | turbolinks (5.2.0) 248 | turbolinks-source (~> 5.2) 249 | turbolinks-source (5.2.0) 250 | tzinfo (1.2.5) 251 | thread_safe (~> 0.1) 252 | uglifier (4.1.20) 253 | execjs (>= 0.3.0, < 3) 254 | unicode-display_width (1.4.1) 255 | warden (1.2.8) 256 | rack (>= 2.0.6) 257 | web-console (3.7.0) 258 | actionview (>= 5.0) 259 | activemodel (>= 5.0) 260 | bindex (>= 0.4.0) 261 | railties (>= 5.0) 262 | webpacker (4.0.7) 263 | activesupport (>= 4.2) 264 | rack-proxy (>= 0.6.1) 265 | railties (>= 4.2) 266 | websocket-driver (0.7.1) 267 | websocket-extensions (>= 0.1.0) 268 | websocket-extensions (0.1.4) 269 | xpath (3.2.0) 270 | nokogiri (~> 1.8) 271 | 272 | PLATFORMS 273 | ruby 274 | 275 | DEPENDENCIES 276 | bootsnap (>= 1.1.0) 277 | bootstrap (>= 4.3.1) 278 | capybara (>= 2.15) 279 | coffee-rails (~> 4.2) 280 | devise 281 | devise-token_authenticatable 282 | factory_bot_rails 283 | foreman 284 | graphiql-rails 285 | graphql 286 | jbuilder (~> 2.5) 287 | listen (>= 3.0.5, < 3.2) 288 | pg 289 | pry 290 | pry-nav 291 | puma (~> 3.11) 292 | rails (= 5.2.3) 293 | rspec-rails 294 | sass-rails (~> 5.0) 295 | selenium-webdriver 296 | spring 297 | spring-watcher-listen (~> 2.0.0) 298 | sprockets (~> 3.7.2) 299 | turbolinks (~> 5) 300 | uglifier (>= 1.3.0) 301 | web-console (>= 3.3.0) 302 | webpacker (~> 4.0.7) 303 | 304 | RUBY VERSION 305 | ruby 2.6.3p62 306 | 307 | BUNDLED WITH 308 | 2.0.2 309 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: bin/rails server puma 2 | webpack: bin/webpack-dev-server 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Purpose 2 | 3 | VueGraphqlAuthExample demonstrates how to use Rails, Vue, GraphQL and Devise together to create basic token authentication. The [related article](https://engineering.doximity.com/articles/token-authentication-with-rails-vue-graphql-and-devise) provides a step-by-step guide to help navigate the repo and set up auth on your application. 4 | 5 | ![](demo.gif) 6 | 7 | # Setup 8 | 9 | Please check `.ruby-version` and `.nvmrc` to ensure you have the right versions of Ruby and Node installed and activated on your system. Then run 10 | 11 | ``` 12 | bin/setup 13 | ``` 14 | 15 | # Usage 16 | 17 | ## Running the App 18 | 19 | To run the app 20 | 21 | ``` 22 | foreman start 23 | ``` 24 | 25 | then head to http://localhost:3000/. 26 | 27 | ## Running Tests 28 | 29 | All tests can be found in the `./spec`. Run the tests with 30 | 31 | ``` 32 | bin/rspec 33 | ``` 34 | 35 | # Contributing 36 | 37 | Any and all feedback is welcome. Please feel free to open a pull request, issue or message me directly at me@jamesmklein.com. 38 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative 'config/application' 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /app/assets/config/manifest.js: -------------------------------------------------------------------------------- 1 | //= link_tree ../images 2 | //= link_directory ../javascripts .js 3 | //= link_directory ../stylesheets .css 4 | -------------------------------------------------------------------------------- /app/assets/images/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/app/assets/images/.keep -------------------------------------------------------------------------------- /app/assets/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's 5 | // vendor/assets/javascripts directory can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // compiled file. JavaScript code in this file should be added after the last require_* statement. 9 | // 10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details 11 | // about supported directives. 12 | // 13 | //= require rails-ujs 14 | //= require activestorage 15 | //= require turbolinks 16 | //= require_tree . 17 | -------------------------------------------------------------------------------- /app/assets/javascripts/cable.js: -------------------------------------------------------------------------------- 1 | // Action Cable provides the framework to deal with WebSockets in Rails. 2 | // You can generate new channels where WebSocket features live using the `rails generate channel` command. 3 | // 4 | //= require action_cable 5 | //= require_self 6 | //= require_tree ./channels 7 | 8 | (function() { 9 | this.App || (this.App = {}); 10 | 11 | App.cable = ActionCable.createConsumer(); 12 | 13 | }).call(this); 14 | -------------------------------------------------------------------------------- /app/assets/javascripts/channels/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/app/assets/javascripts/channels/.keep -------------------------------------------------------------------------------- /app/assets/stylesheets/application.scss: -------------------------------------------------------------------------------- 1 | // Custom bootstrap variables must be set or imported *before* bootstrap. 2 | @import 'bootstrap'; 3 | -------------------------------------------------------------------------------- /app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Channel < ActionCable::Channel::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Connection < ActionCable::Connection::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationController < ActionController::Base 4 | # Prevent CSRF attacks by raising an exception. 5 | # For APIs, you want to use :null_session instead. 6 | protect_from_forgery with: :null_session 7 | 8 | before_action :handle_html_requests 9 | 10 | # Avoid having an empty view file. 11 | def index 12 | render inline: "" 13 | end 14 | 15 | private 16 | 17 | # Required for initial page load so that the entire app isn't served as json 18 | def handle_html_requests 19 | render "layouts/application" if request.format.symbol == :html 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/graphql_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class GraphqlController < ApplicationController 4 | def execute 5 | variables = ensure_hash(params[:variables]) 6 | query = params[:query] 7 | operation_name = params[:operationName] 8 | context = { current_user: current_user } 9 | 10 | result = VueGraphqlAuthExampleSchema.execute( 11 | query, 12 | variables: variables, 13 | context: context, 14 | operation_name: operation_name 15 | ) 16 | render json: result 17 | rescue StandardError => e 18 | raise e unless Rails.env.development? 19 | 20 | handle_error_in_development e 21 | end 22 | 23 | private 24 | 25 | # Handle form data, JSON body, or a blank value 26 | def ensure_hash(ambiguous_param) 27 | case ambiguous_param 28 | when String 29 | if ambiguous_param.present? 30 | ensure_hash(JSON.parse(ambiguous_param)) 31 | else 32 | {} 33 | end 34 | when Hash, ActionController::Parameters 35 | ambiguous_param 36 | when nil 37 | {} 38 | else 39 | raise ArgumentError, "Unexpected parameter: #{ambiguous_param}" 40 | end 41 | end 42 | 43 | def handle_error_in_development(e) 44 | logger.error e.message 45 | logger.error e.backtrace.join("\n") 46 | 47 | render json: { error: { message: e.message, backtrace: e.backtrace }, data: {} }, status: 500 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /app/graphql/mutations/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/app/graphql/mutations/.keep -------------------------------------------------------------------------------- /app/graphql/mutations/base_mutation.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mutations 4 | class BaseMutation < GraphQL::Schema::RelayClassicMutation 5 | # Add your custom classes if you have them: 6 | # This is used for generating payload types 7 | object_class Types::BaseObject 8 | 9 | # This is used for return fields on the mutation's payload 10 | field_class Types::BaseField 11 | 12 | # This is used for generating the `input: { ... }` object type 13 | input_object_class Types::BaseInputObject 14 | 15 | # https://github.com/rmosolgo/graphql-ruby/issues/1837 16 | field :success, Boolean, null: false 17 | field :errors, [String], null: true 18 | 19 | protected 20 | 21 | def authorize_user 22 | return true if context[:current_user].present? 23 | 24 | raise GraphQL::ExecutionError, "User not signed in" 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /app/graphql/mutations/mutation_result.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mutations 4 | class MutationResult 5 | def self.call(obj: {}, success: true, errors: []) 6 | obj.merge(success: success, errors: errors) 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/graphql/mutations/register_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mutations 4 | class RegisterUser < Mutations::BaseMutation 5 | graphql_name "RegisterUser" 6 | 7 | argument :first_name, String, required: true 8 | argument :last_name, String, required: true 9 | argument :email, String, required: true 10 | argument :password, String, required: true 11 | 12 | field :user, Types::UserType, null: false 13 | 14 | def resolve(args) 15 | user = User.create!(args) 16 | 17 | # current_user needs to be set so authenticationToken can be returned 18 | context[:current_user] = user 19 | 20 | MutationResult.call( 21 | obj: { user: user }, 22 | success: user.persisted?, 23 | errors: user.errors 24 | ) 25 | rescue ActiveRecord::RecordInvalid => invalid 26 | GraphQL::ExecutionError.new( 27 | "Invalid Attributes for #{invalid.record.class.name}: " \ 28 | "#{invalid.record.errors.full_messages.join(', ')}" 29 | ) 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /app/graphql/mutations/sign_in.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mutations 4 | class SignIn < Mutations::BaseMutation 5 | graphql_name "SignIn" 6 | 7 | argument :email, String, required: true 8 | argument :password, String, required: true 9 | 10 | field :user, Types::UserType, null: false 11 | 12 | def resolve(args) 13 | user = User.find_for_database_authentication(email: args[:email]) 14 | 15 | if user.present? 16 | if user.valid_password?(args[:password]) 17 | context[:current_user] = user 18 | MutationResult.call(obj: { user: user }, success: true) 19 | else 20 | GraphQL::ExecutionError.new("Incorrect Email/Password") 21 | end 22 | else 23 | GraphQL::ExecutionError.new("User not registered on this application") 24 | end 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /app/graphql/mutations/sign_out.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mutations 4 | class SignOut < Mutations::BaseMutation 5 | graphql_name "SignOut" 6 | 7 | field :user, Types::UserType, null: false 8 | 9 | def resolve 10 | user = context[:current_user] 11 | if user.present? 12 | success = user.reset_authentication_token! 13 | 14 | MutationResult.call( 15 | obj: { user: user }, 16 | success: success, 17 | errors: user.errors 18 | ) 19 | else 20 | GraphQL::ExecutionError.new("User not signed in") 21 | end 22 | end 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /app/graphql/types/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/app/graphql/types/.keep -------------------------------------------------------------------------------- /app/graphql/types/base_enum.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseEnum < GraphQL::Schema::Enum 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_field.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Types 4 | class BaseField < GraphQL::Schema::Field 5 | def resolve_field(obj, args, ctx) 6 | resolve(obj, args, ctx) 7 | end 8 | end 9 | end 10 | 11 | -------------------------------------------------------------------------------- /app/graphql/types/base_input_object.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseInputObject < GraphQL::Schema::InputObject 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_interface.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module BaseInterface 3 | include GraphQL::Schema::Interface 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/graphql/types/base_object.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Types 4 | class BaseObject < GraphQL::Schema::Object 5 | # Used by Relay to lookup objects by UUID: 6 | add_field(GraphQL::Types::Relay::NodeField) 7 | 8 | # Fetches a list of objects given a list of IDs 9 | add_field(GraphQL::Types::Relay::NodesField) 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/graphql/types/base_scalar.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseScalar < GraphQL::Schema::Scalar 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_union.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseUnion < GraphQL::Schema::Union 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/mutation_type.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Types 4 | class MutationType < Types::BaseObject 5 | field :register_user, mutation: Mutations::RegisterUser 6 | field :sign_in, mutation: Mutations::SignIn 7 | field :sign_out, mutation: Mutations::SignOut 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/graphql/types/query_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class QueryType < Types::BaseObject 3 | # Add root-level fields here. 4 | # They will be entry points for queries on your schema. 5 | 6 | # TODO: remove me 7 | field :test_field, String, null: false, 8 | description: "An example field added by the generator" 9 | def test_field 10 | "Hello World!" 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/graphql/types/user_type.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Types 4 | class UserType < Types::BaseObject 5 | graphql_name "User" 6 | 7 | implements GraphQL::Types::Relay::Node 8 | global_id_field :id 9 | 10 | field :lastName, String, null: false 11 | delegate :last_name, to: :object 12 | 13 | field :firstName, String, null: false 14 | delegate :first_name, to: :object 15 | 16 | field :email, String, null: false 17 | 18 | field :authentication_token, String, null: false 19 | def authentication_token 20 | if object.gql_id != context[:current_user]&.gql_id 21 | raise GraphQL::UnauthorizedFieldError, 22 | "Unable to access authentication_token" 23 | end 24 | 25 | object.authentication_token 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /app/graphql/vue_graphql_auth_example_schema.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class VueGraphqlAuthExampleSchema < GraphQL::Schema 4 | mutation(Types::MutationType) 5 | query(Types::QueryType) 6 | 7 | # You'll also need to define `resolve_type` for 8 | # telling the schema what type Relay `Node` objects are 9 | def self.resolve_type(_type, obj, _ctx) 10 | "Types::#{obj.class.name}Type".constantize 11 | rescue NameError 12 | raise("Unexpected object: #{obj}") 13 | end 14 | 15 | def self.id_from_object(object, type_definition, _ctx = nil) 16 | GraphQL::Schema::UniqueWithinType.encode(type_definition.name, object.id) 17 | end 18 | 19 | def self.object_from_id(id, _ctx) 20 | type_name, object_id = GraphQL::Schema::UniqueWithinType.decode(id) 21 | 22 | # Now, based on `type_name` and `id` 23 | # find an object in your application 24 | # This will give the user access to all records in your db 25 | # so you might want to restrict this properly 26 | Object.const_get(type_name).find(object_id) 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/javascript/components/application.vue: -------------------------------------------------------------------------------- 1 | 15 | 16 | 24 | -------------------------------------------------------------------------------- /app/javascript/components/layout/Navbar.vue: -------------------------------------------------------------------------------- 1 | 68 | 69 | 95 | -------------------------------------------------------------------------------- /app/javascript/components/shared/alerts.vue: -------------------------------------------------------------------------------- 1 | 17 | 33 | -------------------------------------------------------------------------------- /app/javascript/mixins/applicationSettings.js: -------------------------------------------------------------------------------- 1 | import _isEmpty from 'lodash/isEmpty'; 2 | import { AUTH_TOKEN_KEY } from '~configuration/appConstants'; 3 | import { mapGetters } from 'vuex'; 4 | 5 | function authTokenExists() { 6 | const token = localStorage.getItem(AUTH_TOKEN_KEY); 7 | 8 | return token !== '' && token !== undefined && token !== null; 9 | } 10 | 11 | export default { 12 | computed: { 13 | ...mapGetters(['user']), 14 | signedIn() { 15 | return !_isEmpty(this.user) && authTokenExists(); 16 | }, 17 | userFullName() { 18 | if(!this.signedIn) return ''; 19 | return `${this.user.firstName} ${this.user.lastName}`; 20 | }, 21 | }, 22 | }; 23 | -------------------------------------------------------------------------------- /app/javascript/mutations/registerUser.js: -------------------------------------------------------------------------------- 1 | // app/javascript/mutations/registerUser.js 2 | 3 | import gql from 'graphql-tag'; 4 | 5 | const mutation = gql` 6 | mutation registerUser( 7 | $firstName: String!, 8 | $lastName: String!, 9 | $email: String!, 10 | $password: String!, 11 | ) { 12 | registerUser(input: { 13 | firstName: $firstName, 14 | lastName: $lastName, 15 | email: $email, 16 | password: $password, 17 | }) { 18 | user { 19 | id 20 | firstName 21 | lastName 22 | email 23 | authenticationToken 24 | } 25 | success 26 | errors 27 | } 28 | } 29 | `; 30 | 31 | export default function({ 32 | apollo, 33 | firstName, 34 | lastName, 35 | email, 36 | password, 37 | }) { 38 | return apollo.mutate({ 39 | mutation, 40 | variables: { 41 | firstName, 42 | lastName, 43 | email, 44 | password, 45 | }, 46 | }); 47 | } -------------------------------------------------------------------------------- /app/javascript/mutations/signIn.js: -------------------------------------------------------------------------------- 1 | // app/javascript/mutations/signIn.js 2 | 3 | import gql from 'graphql-tag'; 4 | 5 | const mutation = gql` 6 | mutation signIn($email: String!, $password: String!) { 7 | signIn(input: { email: $email, password: $password }) { 8 | user { 9 | id 10 | firstName 11 | lastName 12 | authenticationToken 13 | } 14 | success 15 | errors 16 | } 17 | } 18 | `; 19 | 20 | export default function signIn({ 21 | apollo, 22 | email, 23 | password, 24 | }) { 25 | return apollo.mutate({ 26 | mutation, 27 | variables: { 28 | email, 29 | password, 30 | }, 31 | }); 32 | } -------------------------------------------------------------------------------- /app/javascript/mutations/signOut.js: -------------------------------------------------------------------------------- 1 | // app/javascript/mutations/signOut.js 2 | 3 | import gql from 'graphql-tag'; 4 | 5 | const mutation = gql` 6 | mutation signOut { 7 | signOut(input: {}) { 8 | success 9 | errors 10 | } 11 | } 12 | `; 13 | 14 | export default function signOut({ apollo }) { 15 | return apollo.mutate({ mutation }); 16 | } -------------------------------------------------------------------------------- /app/javascript/packs/application.js: -------------------------------------------------------------------------------- 1 | /* eslint no-console:0 */ 2 | // This file is automatically compiled by Webpack, along with any other files 3 | // present in this directory. You're encouraged to place your actual application logic in 4 | // a relevant structure within app/javascript and only use these pack files to reference 5 | // that code so it'll be compiled. 6 | // 7 | // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate 8 | // layout file, like app/views/layouts/application.html.erb 9 | 10 | 11 | // Uncomment to copy all static images under ../images to the output folder and reference 12 | // them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>) 13 | // or the `imagePath` JavaScript helper below. 14 | // 15 | // const images = require.context('../images', true) 16 | // const imagePath = (name) => images(name, true) 17 | 18 | import Application from '../components/application.vue'; 19 | import ApplicationSettingsMixin from '../mixins/applicationSettings'; 20 | import Vue from 'vue'; 21 | import VueRouter from 'vue-router'; 22 | import Vuex from 'vuex'; 23 | import apolloProvider from './configuration/apolloProvider'; 24 | import createStore from 'store/baseStore.js'; 25 | import router from './configuration/router'; 26 | 27 | Vue.use(VueRouter); 28 | Vue.use(Vuex); 29 | 30 | Vue.mixin(ApplicationSettingsMixin); 31 | 32 | document.addEventListener('DOMContentLoaded', () => { 33 | new Vue({ 34 | el: '#vg-application', 35 | name: 'AppRoot', 36 | apolloProvider, 37 | router, 38 | store: createStore(), 39 | render: h => h(Application), 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /app/javascript/packs/configuration/apolloProvider.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue'; 2 | import VueApollo from 'vue-apollo'; 3 | import { ApolloClient } from 'apollo-client'; 4 | import { createHttpLink } from 'apollo-link-http'; 5 | import { setContext } from 'apollo-link-context'; 6 | import { InMemoryCache } from 'apollo-cache-inmemory'; 7 | import { AUTH_TOKEN_KEY } from '~configuration/appConstants'; 8 | 9 | Vue.use(VueApollo); 10 | 11 | const host = window.location.origin; 12 | const httpLink = createHttpLink({ uri: `${host}/graphql` }); 13 | 14 | const authLink = setContext((_, { headers }) => { 15 | // get the csrfToken from the element in appilcation.html layout 16 | const csrfToken = document. 17 | querySelector('meta[name="csrf-token"]'). 18 | attributes.content.value; 19 | 20 | // get the authentication token from local storage if it exists 21 | const authToken = localStorage.getItem(AUTH_TOKEN_KEY); 22 | 23 | return { 24 | headers: { 25 | ...headers, 26 | 'X-CSRF-Token': csrfToken, 27 | authorization: authToken ? `Bearer ${authToken}` : '', 28 | }, 29 | }; 30 | }); 31 | 32 | const client = new ApolloClient({ 33 | link: authLink.concat(httpLink), 34 | cache: new InMemoryCache(), 35 | }); 36 | 37 | const apolloProvider = new VueApollo({ defaultClient: client }); 38 | 39 | export default apolloProvider; 40 | -------------------------------------------------------------------------------- /app/javascript/packs/configuration/appConstants.js: -------------------------------------------------------------------------------- 1 | const AUTH_TOKEN_KEY = 'authToken'; 2 | 3 | export { AUTH_TOKEN_KEY }; 4 | 5 | -------------------------------------------------------------------------------- /app/javascript/packs/configuration/router.js: -------------------------------------------------------------------------------- 1 | import VueRouter from 'vue-router'; 2 | import routes from 'router/routes'; 3 | 4 | const router = new VueRouter({ 5 | routes, 6 | mode: 'history', 7 | }); 8 | 9 | export default router; 10 | -------------------------------------------------------------------------------- /app/javascript/pages/home/show.vue: -------------------------------------------------------------------------------- 1 | 15 | 20 | -------------------------------------------------------------------------------- /app/javascript/pages/sign_in/new.vue: -------------------------------------------------------------------------------- 1 | 38 | 77 | -------------------------------------------------------------------------------- /app/javascript/pages/sign_up/new.vue: -------------------------------------------------------------------------------- 1 | 59 | 98 | -------------------------------------------------------------------------------- /app/javascript/router/routes.js: -------------------------------------------------------------------------------- 1 | import _map from 'lodash/map'; 2 | import _extend from 'lodash/extend'; 3 | 4 | import SignUp from 'pages/sign_up/new.vue'; 5 | import SignIn from 'pages/sign_in/new.vue'; 6 | import HomeShow from 'pages/home/show.vue'; 7 | 8 | let routes = [ 9 | { 10 | path: '/home', 11 | name: 'home', 12 | component: HomeShow, 13 | }, 14 | { 15 | path: '', 16 | name: 'sign_in', 17 | component: SignIn, 18 | }, 19 | { 20 | path: '/sign_up', 21 | name: 'sign_up', 22 | component: SignUp, 23 | }, 24 | ]; 25 | 26 | routes = _map(routes, (route) => { 27 | return _extend({}, route, { props: true }); 28 | }); 29 | export default routes; 30 | 31 | -------------------------------------------------------------------------------- /app/javascript/store/baseStore.js: -------------------------------------------------------------------------------- 1 | import * as Cookies from 'js-cookie'; 2 | import createPersistedState from 'vuex-persistedstate'; 3 | import usersStore from './usersStore'; 4 | import { Store } from 'vuex'; 5 | 6 | export default function createStore() { 7 | return new Store({ 8 | plugins: [ 9 | createPersistedState({ 10 | getState: (key) => { 11 | return Cookies.getJSON(key); 12 | }, 13 | setState: (key, state) => { 14 | Cookies.set(key, state, { expires: 3 }); // 3 days 15 | }, 16 | }), 17 | ], 18 | modules: { 19 | usersStore, 20 | }, 21 | }); 22 | } 23 | -------------------------------------------------------------------------------- /app/javascript/store/usersStore.js: -------------------------------------------------------------------------------- 1 | const state = { 2 | user: {}, 3 | }; 4 | 5 | const getters = { 6 | user: state => { 7 | return state.user; 8 | }, 9 | }; 10 | 11 | const mutations = { 12 | signIn(state, user) { 13 | state.user = user; 14 | }, 15 | clearUser(state) { 16 | state.user = {}; 17 | }, 18 | }; 19 | 20 | const actions = { 21 | signOut(context) { 22 | context.commit('clearUser'); 23 | }, 24 | signIn(context, user) { 25 | context.commit('signIn', user); 26 | }, 27 | }; 28 | 29 | export default { state, getters, mutations, actions }; 30 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | end 3 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/concerns/graph_ql/interface.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Note the path of this file must be graph_ql, not graphql 4 | module GraphQL 5 | module Interface 6 | def self.included(base) 7 | base.send(:include, InstanceMethods) 8 | base.extend(ClassMethods) 9 | end 10 | 11 | module InstanceMethods 12 | def gql_id 13 | GraphQL::Schema::UniqueWithinType.encode(self.class.name, id) 14 | end 15 | end 16 | 17 | module ClassMethods 18 | def find_by_gql_id(gql_id) 19 | _type_name, object_id = GraphQL::Schema::UniqueWithinType.decode(gql_id) 20 | 21 | find(object_id) 22 | end 23 | 24 | def find_by_gql_ids(gql_ids) 25 | ids = gql_ids.map do |gql_id| 26 | GraphQL::Schema::UniqueWithinType.decode(gql_id).last 27 | end 28 | 29 | where(id: ids) 30 | end 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class User < ApplicationRecord 4 | include GraphQL::Interface 5 | 6 | # Include default devise modules. Others available are: 7 | # :confirmable, :lockable, :timeoutable and :omniauthable 8 | devise :database_authenticatable, :registerable, 9 | :recoverable, :rememberable, :trackable, :validatable, 10 | :database_authenticatable, :token_authenticatable 11 | 12 | validates :first_name, :last_name, presence: true 13 | end 14 | -------------------------------------------------------------------------------- /app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | VueGraphqlAuthExample 5 | <%= csrf_meta_tags %> 6 | <%= csp_meta_tag %> 7 | 8 | <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> 9 | <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> 10 | 11 | <%= javascript_pack_tag "application" %> 12 | <%= stylesheet_link_tag "application", :media => "all" %> 13 | 14 | 15 | 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'bundle' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "rubygems" 12 | 13 | m = Module.new do 14 | module_function 15 | 16 | def invoked_as_script? 17 | File.expand_path($0) == File.expand_path(__FILE__) 18 | end 19 | 20 | def env_var_version 21 | ENV["BUNDLER_VERSION"] 22 | end 23 | 24 | def cli_arg_version 25 | return unless invoked_as_script? # don't want to hijack other binstubs 26 | return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` 27 | bundler_version = nil 28 | update_index = nil 29 | ARGV.each_with_index do |a, i| 30 | if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN 31 | bundler_version = a 32 | end 33 | next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ 34 | bundler_version = $1 || ">= 0.a" 35 | update_index = i 36 | end 37 | bundler_version 38 | end 39 | 40 | def gemfile 41 | gemfile = ENV["BUNDLE_GEMFILE"] 42 | return gemfile if gemfile && !gemfile.empty? 43 | 44 | File.expand_path("../../Gemfile", __FILE__) 45 | end 46 | 47 | def lockfile 48 | lockfile = 49 | case File.basename(gemfile) 50 | when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) 51 | else "#{gemfile}.lock" 52 | end 53 | File.expand_path(lockfile) 54 | end 55 | 56 | def lockfile_version 57 | return unless File.file?(lockfile) 58 | lockfile_contents = File.read(lockfile) 59 | return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ 60 | Regexp.last_match(1) 61 | end 62 | 63 | def bundler_version 64 | @bundler_version ||= begin 65 | env_var_version || cli_arg_version || 66 | lockfile_version || "#{Gem::Requirement.default}.a" 67 | end 68 | end 69 | 70 | def load_bundler! 71 | ENV["BUNDLE_GEMFILE"] ||= gemfile 72 | 73 | # must dup string for RG < 1.8 compatibility 74 | activate_bundler(bundler_version.dup) 75 | end 76 | 77 | def activate_bundler(bundler_version) 78 | if Gem::Version.correct?(bundler_version) && Gem::Version.new(bundler_version).release < Gem::Version.new("2.0") 79 | bundler_version = "< 2" 80 | end 81 | gem_error = activation_error_handling do 82 | gem "bundler", bundler_version 83 | end 84 | return if gem_error.nil? 85 | require_error = activation_error_handling do 86 | require "bundler/version" 87 | end 88 | return if require_error.nil? && Gem::Requirement.new(bundler_version).satisfied_by?(Gem::Version.new(Bundler::VERSION)) 89 | warn "Activating bundler (#{bundler_version}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_version}'`" 90 | exit 42 91 | end 92 | 93 | def activation_error_handling 94 | yield 95 | nil 96 | rescue StandardError, LoadError => e 97 | e 98 | end 99 | end 100 | 101 | m.load_bundler! 102 | 103 | if m.invoked_as_script? 104 | load Gem.bin_path("bundler", "bundle") 105 | end 106 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | APP_PATH = File.expand_path('../config/application', __dir__) 8 | require_relative '../config/boot' 9 | require 'rails/commands' 10 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | require_relative '../config/boot' 8 | require 'rake' 9 | Rake.application.run 10 | -------------------------------------------------------------------------------- /bin/rspec: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'rspec' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "pathname" 12 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 13 | Pathname.new(__FILE__).realpath) 14 | 15 | bundle_binstub = File.expand_path("../bundle", __FILE__) 16 | 17 | if File.file?(bundle_binstub) 18 | if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ 19 | load(bundle_binstub) 20 | else 21 | abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. 22 | Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") 23 | end 24 | end 25 | 26 | require "rubygems" 27 | require "bundler/setup" 28 | 29 | load Gem.bin_path("rspec-core", "rspec") 30 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require "fileutils" 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path("..", __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a starting point to setup your application. 14 | # Add necessary setup steps to this file. 15 | 16 | puts "== Installing dependencies ==" 17 | system! "gem install bundler --conservative" 18 | system("bundle check") || system!("bundle install") 19 | 20 | # Install JavaScript dependencies if using Yarn 21 | system("bin/yarn") 22 | 23 | puts "\n== Preparing database ==" 24 | system! "bin/rails db:setup" 25 | 26 | puts "\n== Removing old logs and tempfiles ==" 27 | system! "bin/rails log:clear tmp:clear" 28 | end 29 | -------------------------------------------------------------------------------- /bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file loads Spring without using Bundler, in order to be fast. 4 | # It gets overwritten when you run the `spring binstub` command. 5 | 6 | unless defined?(Spring) 7 | require 'rubygems' 8 | require 'bundler' 9 | 10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read) 11 | spring = lockfile.specs.detect { |spec| spec.name == 'spring' } 12 | if spring 13 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path 14 | gem 'spring', spring.version 15 | require 'spring/binstub' 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /bin/update: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a way to update your development environment automatically. 14 | # Add necessary update steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # Install JavaScript dependencies if using Yarn 21 | # system('bin/yarn') 22 | 23 | puts "\n== Updating database ==" 24 | system! 'bin/rails db:migrate' 25 | 26 | puts "\n== Removing old logs and tempfiles ==" 27 | system! 'bin/rails log:clear tmp:clear' 28 | 29 | puts "\n== Restarting application server ==" 30 | system! 'bin/rails restart' 31 | end 32 | -------------------------------------------------------------------------------- /bin/webpack: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development" 4 | ENV["NODE_ENV"] ||= "development" 5 | 6 | require "pathname" 7 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 8 | Pathname.new(__FILE__).realpath) 9 | 10 | require "rubygems" 11 | require "bundler/setup" 12 | 13 | require "webpacker" 14 | require "webpacker/webpack_runner" 15 | 16 | APP_ROOT = File.expand_path("..", __dir__) 17 | Dir.chdir(APP_ROOT) do 18 | Webpacker::WebpackRunner.run(ARGV) 19 | end 20 | -------------------------------------------------------------------------------- /bin/webpack-dev-server: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development" 5 | ENV["NODE_ENV"] ||= ENV["RAILS_ENV"] 6 | 7 | require "pathname" 8 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 9 | Pathname.new(__FILE__).realpath) 10 | 11 | require "rubygems" 12 | require "bundler/setup" 13 | 14 | require "webpacker" 15 | require "webpacker/dev_server_runner" 16 | Webpacker::DevServerRunner.run(ARGV) 17 | -------------------------------------------------------------------------------- /bin/yarn: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_ROOT = File.expand_path('..', __dir__) 3 | Dir.chdir(APP_ROOT) do 4 | begin 5 | exec "yarnpkg", *ARGV 6 | rescue Errno::ENOENT 7 | $stderr.puts "Yarn executable was not detected in the system." 8 | $stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install" 9 | exit 1 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative 'config/environment' 4 | 5 | run Rails.application 6 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative 'boot' 2 | 3 | require 'rails/all' 4 | 5 | # Require the gems listed in Gemfile, including any gems 6 | # you've limited to :test, :development, or :production. 7 | Bundler.require(*Rails.groups) 8 | 9 | module VueGraphqlAuthExample 10 | class Application < Rails::Application 11 | # Initialize configuration defaults for originally generated Rails version. 12 | config.load_defaults 5.2 13 | 14 | # Settings in config/environments/* take precedence over those specified here. 15 | # Application configuration can go into files in config/initializers 16 | # -- all .rb files in that directory are automatically loaded after loading 17 | # the framework and any gems in your application. 18 | config.autoload_paths += %W[#{config.root}/app] 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | require 'bootsnap/setup' # Speed up boot time by caching expensive operations. 5 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: async 3 | 4 | test: 5 | adapter: async 6 | 7 | production: 8 | adapter: redis 9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 10 | channel_prefix: vue_graphql_auth_example_production 11 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | Igkt3wiaBVEvfl+KxIjgeuUxc4w8ZQ0LaaPhldBLTB4GmFfTj+51vHsZsNfuOHBiRylEcdHch3WWEcYpHvPPiQeFMM7Y1CVBvcM+RaZM9MPr6VBXxyQhMSuTDaQ5bRp7MQ5QA8n1z0mGwuXB/2/CcBAW0Oe4W/ks7WW3XfLXWA1wnwVdHBLYc9nRkJ3/i8Jb0o6bhy9prPYMG2L643xvDTzbyTeYO31XpXcOrlJD2egbWWgVDU4wJESp+Cvwy4mPHMpUDi7KzgwlZlJbjrEa3S3aV83E5hk3WIA2rPISa+yZdREO+iFFoFJN65D4OPTQG2wokhK+gY42YOD+s7zbFX2/E7faBWnEYevTy4PnONOpEA2Z5t4BsD3CORLIpM9gKcmPy5Q9f6npd21+n5LfSKfY12C1NuJtA7AO--bwYfwArRQekB2BHN--AdY6cDqIeaku4M55FhVmjQ== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 8.2 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On OS X with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On OS X with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | # For details on connection pooling, see rails configuration guide 21 | # http://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 23 | timeout: 5000 24 | 25 | development: 26 | <<: *default 27 | database: vue_graphql_auth_example_development 28 | 29 | # The specified database role being used to connect to postgres. 30 | # To create additional roles in postgres see `$ createuser --help`. 31 | # When left blank, postgres will use the default role. This is 32 | # the same name as the operating system user that initialized the database. 33 | #username: vue_graphql_auth_example 34 | 35 | # The password associated with the postgres role (username). 36 | #password: 37 | 38 | # Connect on a TCP socket. Omitted by default since the client uses a 39 | # domain socket that doesn't need configuration. Windows does not have 40 | # domain sockets, so uncomment these lines. 41 | #host: localhost 42 | 43 | # The TCP port the server listens on. Defaults to 5432. 44 | # If your server runs on a different port number, change accordingly. 45 | #port: 5432 46 | 47 | # Schema search path. The server defaults to $user,public 48 | #schema_search_path: myapp,sharedapp,public 49 | 50 | # Minimum log levels, in increasing order: 51 | # debug5, debug4, debug3, debug2, debug1, 52 | # log, notice, warning, error, fatal, and panic 53 | # Defaults to warning. 54 | #min_messages: notice 55 | 56 | # Warning: The database defined as "test" will be erased and 57 | # re-generated from your development database when you run "rake". 58 | # Do not set this db to the same as development or production. 59 | test: 60 | <<: *default 61 | database: vue_graphql_auth_example_test 62 | 63 | # As with config/secrets.yml, you never want to store sensitive information, 64 | # like your database password, in your source code. If your source code is 65 | # ever seen by anyone, they now have access to your database. 66 | # 67 | # Instead, provide the password as a unix environment variable when you boot 68 | # the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database 69 | # for a full rundown on how to provide these environment variables in a 70 | # production deployment. 71 | # 72 | # On Heroku and other platform providers, you may have a full connection URL 73 | # available as an environment variable. For example: 74 | # 75 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 76 | # 77 | # You can use this database configuration with: 78 | # 79 | # production: 80 | # url: <%= ENV['DATABASE_URL'] %> 81 | # 82 | production: 83 | <<: *default 84 | database: vue_graphql_auth_example_production 85 | username: vue_graphql_auth_example 86 | password: <%= ENV['VUE_GRAPHQL_AUTH_EXAMPLE_DATABASE_PASSWORD'] %> 87 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative 'application' 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } 3 | 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # In the development environment your application's code is reloaded on 7 | # every request. This slows down response time but is perfect for development 8 | # since you don't have to restart the web server when you make code changes. 9 | config.cache_classes = false 10 | 11 | # Do not eager load code on boot. 12 | config.eager_load = false 13 | 14 | # Show full error reports. 15 | config.consider_all_requests_local = true 16 | 17 | # Enable/disable caching. By default caching is disabled. 18 | # Run rails dev:cache to toggle caching. 19 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 20 | config.action_controller.perform_caching = true 21 | 22 | config.cache_store = :memory_store 23 | config.public_file_server.headers = { 24 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 25 | } 26 | else 27 | config.action_controller.perform_caching = false 28 | 29 | config.cache_store = :null_store 30 | end 31 | 32 | # Store uploaded files on the local file system (see config/storage.yml for options) 33 | config.active_storage.service = :local 34 | 35 | # Don't care if the mailer can't send. 36 | config.action_mailer.raise_delivery_errors = false 37 | 38 | config.action_mailer.perform_caching = false 39 | 40 | # Print deprecation notices to the Rails logger. 41 | config.active_support.deprecation = :log 42 | 43 | # Raise an error on page load if there are pending migrations. 44 | config.active_record.migration_error = :page_load 45 | 46 | # Highlight code that triggered database queries in logs. 47 | config.active_record.verbose_query_logs = true 48 | 49 | # Debug mode disables concatenation and preprocessing of assets. 50 | # This option may cause significant delays in view rendering with a large 51 | # number of complex assets. 52 | config.assets.debug = true 53 | 54 | # Suppress logger output for asset requests. 55 | config.assets.quiet = true 56 | 57 | # Raises error for missing translations 58 | # config.action_view.raise_on_missing_translations = true 59 | 60 | # Use an evented file watcher to asynchronously detect changes in source code, 61 | # routes, locales, etc. This feature depends on the listen gem. 62 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 63 | end 64 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 18 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 19 | # config.require_master_key = true 20 | 21 | # Disable serving static files from the `/public` folder by default since 22 | # Apache or NGINX already handles this. 23 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 24 | 25 | # Compress JavaScripts and CSS. 26 | config.assets.js_compressor = :uglifier 27 | # config.assets.css_compressor = :sass 28 | 29 | # Do not fallback to assets pipeline if a precompiled asset is missed. 30 | config.assets.compile = false 31 | 32 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb 33 | 34 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 35 | # config.action_controller.asset_host = 'http://assets.example.com' 36 | 37 | # Specifies the header that your server uses for sending files. 38 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 39 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 40 | 41 | # Store uploaded files on the local file system (see config/storage.yml for options) 42 | config.active_storage.service = :local 43 | 44 | # Mount Action Cable outside main process or domain 45 | # config.action_cable.mount_path = nil 46 | # config.action_cable.url = 'wss://example.com/cable' 47 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 48 | 49 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 50 | # config.force_ssl = true 51 | 52 | # Use the lowest log level to ensure availability of diagnostic information 53 | # when problems arise. 54 | config.log_level = :debug 55 | 56 | # Prepend all log lines with the following tags. 57 | config.log_tags = [ :request_id ] 58 | 59 | # Use a different cache store in production. 60 | # config.cache_store = :mem_cache_store 61 | 62 | # Use a real queuing backend for Active Job (and separate queues per environment) 63 | # config.active_job.queue_adapter = :resque 64 | # config.active_job.queue_name_prefix = "vue_graphql_auth_example_#{Rails.env}" 65 | 66 | config.action_mailer.perform_caching = false 67 | 68 | # Ignore bad email addresses and do not raise email delivery errors. 69 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 70 | # config.action_mailer.raise_delivery_errors = false 71 | 72 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 73 | # the I18n.default_locale when a translation cannot be found). 74 | config.i18n.fallbacks = true 75 | 76 | # Send deprecation notices to registered listeners. 77 | config.active_support.deprecation = :notify 78 | 79 | # Use default logging formatter so that PID and timestamp are not suppressed. 80 | config.log_formatter = ::Logger::Formatter.new 81 | 82 | # Use a different logger for distributed setups. 83 | # require 'syslog/logger' 84 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 85 | 86 | if ENV["RAILS_LOG_TO_STDOUT"].present? 87 | logger = ActiveSupport::Logger.new(STDOUT) 88 | logger.formatter = config.log_formatter 89 | config.logger = ActiveSupport::TaggedLogging.new(logger) 90 | end 91 | 92 | # Do not dump schema after migrations. 93 | config.active_record.dump_schema_after_migration = false 94 | end 95 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure public file server for tests with Cache-Control for performance. 16 | config.public_file_server.enabled = true 17 | config.public_file_server.headers = { 18 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 19 | } 20 | 21 | # Show full error reports and disable caching. 22 | config.consider_all_requests_local = true 23 | config.action_controller.perform_caching = false 24 | 25 | # Raise exceptions instead of rendering exception templates. 26 | config.action_dispatch.show_exceptions = false 27 | 28 | # Disable request forgery protection in test environment. 29 | config.action_controller.allow_forgery_protection = false 30 | 31 | # Store uploaded files on the local file system in a temporary directory 32 | config.active_storage.service = :test 33 | 34 | config.action_mailer.perform_caching = false 35 | 36 | # Tell Action Mailer not to deliver emails to the real world. 37 | # The :test delivery method accumulates sent emails in the 38 | # ActionMailer::Base.deliveries array. 39 | config.action_mailer.delivery_method = :test 40 | 41 | # Print deprecation notices to the stderr. 42 | config.active_support.deprecation = :stderr 43 | 44 | # Raises error for missing translations 45 | # config.action_view.raise_on_missing_translations = true 46 | end 47 | -------------------------------------------------------------------------------- /config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ActiveSupport::Reloader.to_prepare do 4 | # ApplicationController.renderer.defaults.merge!( 5 | # http_host: 'example.org', 6 | # https: false 7 | # ) 8 | # end 9 | -------------------------------------------------------------------------------- /config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path. 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | # Add Yarn node_modules folder to the asset load path. 9 | Rails.application.config.assets.paths << Rails.root.join('node_modules') 10 | 11 | # Precompile additional assets. 12 | # application.js, application.css, and all non-JS/CSS in the app/assets 13 | # folder are already added. 14 | # Rails.application.config.assets.precompile += %w( admin.js admin.css ) 15 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /config/initializers/content_security_policy.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Define an application-wide content security policy 4 | # For further information see the following documentation 5 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy 6 | 7 | # Rails.application.config.content_security_policy do |policy| 8 | # policy.default_src :self, :https 9 | # policy.font_src :self, :https, :data 10 | # policy.img_src :self, :https, :data 11 | # policy.object_src :none 12 | # policy.script_src :self, :https 13 | # policy.style_src :self, :https 14 | 15 | # # Specify URI for violation reports 16 | # # policy.report_uri "/csp-violation-report-endpoint" 17 | # end 18 | 19 | # If you are using UJS then enable automatic nonce generation 20 | # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } 21 | 22 | # Report CSP violations to a specified URI 23 | # For further information see the following documentation: 24 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only 25 | # Rails.application.config.content_security_policy_report_only = true 26 | -------------------------------------------------------------------------------- /config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Specify a serializer for the signed and encrypted cookie jars. 4 | # Valid options are :json, :marshal, and :hybrid. 5 | Rails.application.config.action_dispatch.cookies_serializer = :json 6 | -------------------------------------------------------------------------------- /config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Devise::TokenAuthenticatable.setup do |config| 4 | # enables the expiration of a token after a specified amount of time, 5 | # requires an additional field on the model: `authentication_token_created_at` 6 | # defaults to nil 7 | # config.token_expires_in = 1.day 8 | 9 | # set the authentication key name used by this module, 10 | # defaults to :auth_token 11 | # config.token_authentication_key = :auth_token 12 | 13 | # enable reset of the authentication token before the model is saved, 14 | # defaults to false 15 | # config.should_reset_authentication_token = true 16 | 17 | # enables the setting of the authentication token - if not already - before the model is saved, 18 | # defaults to false 19 | config.should_ensure_authentication_token = true 20 | end 21 | 22 | # Use this hook to configure devise mailer, warden hooks and so forth. 23 | # Many of these configuration options can be set straight in your model. 24 | Devise.setup do |config| 25 | # The secret key used by Devise. Devise uses this key to generate 26 | # random tokens. Changing this key will render invalid all existing 27 | # confirmation, reset password and unlock tokens in the database. 28 | # Devise will use the `secret_key_base` as its `secret_key` 29 | # by default. You can change it below and use your own secret key. 30 | # config.secret_key = 'dec4f922677ba09b52f419f4ba46a13ebdfd10bac421e96e5577e4b6f95a961efa49a5614704b58553dff708ab98275c2b38a4d62d2fb7a7957df1cfa85cedd0' 31 | 32 | # ==> Controller configuration 33 | # Configure the parent class to the devise controllers. 34 | # config.parent_controller = 'DeviseController' 35 | 36 | # ==> Mailer Configuration 37 | # Configure the e-mail address which will be shown in Devise::Mailer, 38 | # note that it will be overwritten if you use your own mailer class 39 | # with default "from" parameter. 40 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' 41 | 42 | # Configure the class responsible to send e-mails. 43 | # config.mailer = 'Devise::Mailer' 44 | 45 | # Configure the parent class responsible to send e-mails. 46 | # config.parent_mailer = 'ActionMailer::Base' 47 | 48 | # ==> ORM configuration 49 | # Load and configure the ORM. Supports :active_record (default) and 50 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 51 | # available as additional gems. 52 | require 'devise/orm/active_record' 53 | 54 | # ==> Configuration for any authentication mechanism 55 | # Configure which keys are used when authenticating a user. The default is 56 | # just :email. You can configure it to use [:username, :subdomain], so for 57 | # authenticating a user, both parameters are required. Remember that those 58 | # parameters are used only when authenticating and not when retrieving from 59 | # session. If you need permissions, you should implement that in a before filter. 60 | # You can also supply a hash where the value is a boolean determining whether 61 | # or not authentication should be aborted when the value is not present. 62 | # config.authentication_keys = [:email] 63 | 64 | # Configure parameters from the request object used for authentication. Each entry 65 | # given should be a request method and it will automatically be passed to the 66 | # find_for_authentication method and considered in your model lookup. For instance, 67 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 68 | # The same considerations mentioned for authentication_keys also apply to request_keys. 69 | # config.request_keys = [] 70 | 71 | # Configure which authentication keys should be case-insensitive. 72 | # These keys will be downcased upon creating or modifying a user and when used 73 | # to authenticate or find a user. Default is :email. 74 | config.case_insensitive_keys = [:email] 75 | 76 | # Configure which authentication keys should have whitespace stripped. 77 | # These keys will have whitespace before and after removed upon creating or 78 | # modifying a user and when used to authenticate or find a user. Default is :email. 79 | config.strip_whitespace_keys = [:email] 80 | 81 | # Tell if authentication through request.params is enabled. True by default. 82 | # It can be set to an array that will enable params authentication only for the 83 | # given strategies, for example, `config.params_authenticatable = [:database]` will 84 | # enable it only for database (email + password) authentication. 85 | # config.params_authenticatable = true 86 | 87 | # Tell if authentication through HTTP Auth is enabled. False by default. 88 | # It can be set to an array that will enable http authentication only for the 89 | # given strategies, for example, `config.http_authenticatable = [:database]` will 90 | # enable it only for database authentication. The supported strategies are: 91 | # :database = Support basic authentication with authentication key + password 92 | config.http_authenticatable = true 93 | 94 | # If 401 status code should be returned for AJAX requests. True by default. 95 | config.http_authenticatable_on_xhr = false 96 | 97 | # The realm used in Http Basic Authentication. 'Application' by default. 98 | # config.http_authentication_realm = 'Application' 99 | 100 | # It will change confirmation, password recovery and other workflows 101 | # to behave the same regardless if the e-mail provided was right or wrong. 102 | # Does not affect registerable. 103 | # config.paranoid = true 104 | 105 | # By default Devise will store the user in session. You can skip storage for 106 | # particular strategies by setting this option. 107 | # Notice that if you are skipping storage for all authentication paths, you 108 | # may want to disable generating routes to Devise's sessions controller by 109 | # passing skip: :sessions to `devise_for` in your config/routes.rb 110 | config.skip_session_storage = [:http_auth, :token_auth] 111 | 112 | # By default, Devise cleans up the CSRF token on authentication to 113 | # avoid CSRF token fixation attacks. This means that, when using AJAX 114 | # requests for sign in and sign up, you need to get a new CSRF token 115 | # from the server. You can disable this option at your own risk. 116 | # config.clean_up_csrf_token_on_authentication = true 117 | 118 | # When false, Devise will not attempt to reload routes on eager load. 119 | # This can reduce the time taken to boot the app but if your application 120 | # requires the Devise mappings to be loaded during boot time the application 121 | # won't boot properly. 122 | # config.reload_routes = true 123 | 124 | # ==> Configuration for :database_authenticatable 125 | # For bcrypt, this is the cost for hashing the password and defaults to 11. If 126 | # using other algorithms, it sets how many times you want the password to be hashed. 127 | # 128 | # Limiting the stretches to just one in testing will increase the performance of 129 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 130 | # a value less than 10 in other environments. Note that, for bcrypt (the default 131 | # algorithm), the cost increases exponentially with the number of stretches (e.g. 132 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). 133 | config.stretches = Rails.env.test? ? 1 : 11 134 | 135 | # Set up a pepper to generate the hashed password. 136 | # config.pepper = 'cf36639a337f996e9b4715cdb547d789aab679d6d798e30353d3ef4ca86b5b7aba692813ccd4c5ad584145573785926d5e4bbf2bbe7def8c12acaa2b97f21b56' 137 | 138 | # Send a notification to the original email when the user's email is changed. 139 | # config.send_email_changed_notification = false 140 | 141 | # Send a notification email when the user's password is changed. 142 | # config.send_password_change_notification = false 143 | 144 | # ==> Configuration for :confirmable 145 | # A period that the user is allowed to access the website even without 146 | # confirming their account. For instance, if set to 2.days, the user will be 147 | # able to access the website for two days without confirming their account, 148 | # access will be blocked just in the third day. 149 | # You can also set it to nil, which will allow the user to access the website 150 | # without confirming their account. 151 | # Default is 0.days, meaning the user cannot access the website without 152 | # confirming their account. 153 | # config.allow_unconfirmed_access_for = 2.days 154 | 155 | # A period that the user is allowed to confirm their account before their 156 | # token becomes invalid. For example, if set to 3.days, the user can confirm 157 | # their account within 3 days after the mail was sent, but on the fourth day 158 | # their account can't be confirmed with the token any more. 159 | # Default is nil, meaning there is no restriction on how long a user can take 160 | # before confirming their account. 161 | # config.confirm_within = 3.days 162 | 163 | # If true, requires any email changes to be confirmed (exactly the same way as 164 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 165 | # db field (see migrations). Until confirmed, new email is stored in 166 | # unconfirmed_email column, and copied to email column on successful confirmation. 167 | config.reconfirmable = true 168 | 169 | # Defines which key will be used when confirming an account 170 | # config.confirmation_keys = [:email] 171 | 172 | # ==> Configuration for :rememberable 173 | # The time the user will be remembered without asking for credentials again. 174 | # config.remember_for = 2.weeks 175 | 176 | # Invalidates all the remember me tokens when the user signs out. 177 | config.expire_all_remember_me_on_sign_out = true 178 | 179 | # If true, extends the user's remember period when remembered via cookie. 180 | # config.extend_remember_period = false 181 | 182 | # Options to be passed to the created cookie. For instance, you can set 183 | # secure: true in order to force SSL only cookies. 184 | # config.rememberable_options = {} 185 | 186 | # ==> Configuration for :validatable 187 | # Range for password length. 188 | config.password_length = 6..128 189 | 190 | # Email regex used to validate email formats. It simply asserts that 191 | # one (and only one) @ exists in the given string. This is mainly 192 | # to give user feedback and not to assert the e-mail validity. 193 | config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ 194 | 195 | # ==> Configuration for :timeoutable 196 | # The time you want to timeout the user session without activity. After this 197 | # time the user will be asked for credentials again. Default is 30 minutes. 198 | # config.timeout_in = 30.minutes 199 | 200 | # ==> Configuration for :lockable 201 | # Defines which strategy will be used to lock an account. 202 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 203 | # :none = No lock strategy. You should handle locking by yourself. 204 | # config.lock_strategy = :failed_attempts 205 | 206 | # Defines which key will be used when locking and unlocking an account 207 | # config.unlock_keys = [:email] 208 | 209 | # Defines which strategy will be used to unlock an account. 210 | # :email = Sends an unlock link to the user email 211 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 212 | # :both = Enables both strategies 213 | # :none = No unlock strategy. You should handle unlocking by yourself. 214 | # config.unlock_strategy = :both 215 | 216 | # Number of authentication tries before locking an account if lock_strategy 217 | # is failed attempts. 218 | # config.maximum_attempts = 20 219 | 220 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 221 | # config.unlock_in = 1.hour 222 | 223 | # Warn on the last attempt before the account is locked. 224 | # config.last_attempt_warning = true 225 | 226 | # ==> Configuration for :recoverable 227 | # 228 | # Defines which key will be used when recovering the password for an account 229 | # config.reset_password_keys = [:email] 230 | 231 | # Time interval you can reset your password with a reset password key. 232 | # Don't put a too small interval or your users won't have the time to 233 | # change their passwords. 234 | config.reset_password_within = 6.hours 235 | 236 | # When set to false, does not sign a user in automatically after their password is 237 | # reset. Defaults to true, so a user is signed in automatically after a reset. 238 | # config.sign_in_after_reset_password = true 239 | 240 | # ==> Configuration for :encryptable 241 | # Allow you to use another hashing or encryption algorithm besides bcrypt (default). 242 | # You can use :sha1, :sha512 or algorithms from others authentication tools as 243 | # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 244 | # for default behavior) and :restful_authentication_sha1 (then you should set 245 | # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). 246 | # 247 | # Require the `devise-encryptable` gem when using anything other than bcrypt 248 | # config.encryptor = :sha512 249 | 250 | # ==> Scopes configuration 251 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 252 | # "users/sessions/new". It's turned off by default because it's slower if you 253 | # are using only default views. 254 | # config.scoped_views = false 255 | 256 | # Configure the default scope given to Warden. By default it's the first 257 | # devise role declared in your routes (usually :user). 258 | # config.default_scope = :user 259 | 260 | # Set this configuration to false if you want /users/sign_out to sign out 261 | # only the current scope. By default, Devise signs out all scopes. 262 | # config.sign_out_all_scopes = true 263 | 264 | # ==> Navigation configuration 265 | # Lists the formats that should be treated as navigational. Formats like 266 | # :html, should redirect to the sign in page when the user does not have 267 | # access, but formats like :xml or :json, should return 401. 268 | # 269 | # If you have any extra navigational formats, like :iphone or :mobile, you 270 | # should add them to the navigational formats lists. 271 | # 272 | # The "*/*" below is required to match Internet Explorer requests. 273 | # config.navigational_formats = ['*/*', :html] 274 | 275 | # The default HTTP method used to sign out a resource. Default is :delete. 276 | config.sign_out_via = :delete 277 | 278 | # ==> OmniAuth 279 | # Add a new OmniAuth provider. Check the wiki for more information on setting 280 | # up on your models and hooks. 281 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' 282 | 283 | # ==> Warden configuration 284 | # If you want to use other strategies, that are not supported by Devise, or 285 | # change the failure app, you can configure them inside the config.warden block. 286 | # 287 | # config.warden do |manager| 288 | # manager.intercept_401 = false 289 | # manager.default_strategies(scope: :user).unshift :some_external_strategy 290 | # end 291 | 292 | # ==> Mountable engine configurations 293 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 294 | # is mountable, there are some extra configurations to be taken into account. 295 | # The following options are available, assuming the engine is mounted as: 296 | # 297 | # mount MyEngine, at: '/my_engine' 298 | # 299 | # The router that invoked `devise_for`, in the example above, would be: 300 | # config.router_name = :my_engine 301 | # 302 | # When using OmniAuth, Devise cannot automatically set OmniAuth path, 303 | # so you need to do it manually. For the users scope, it would be: 304 | # config.omniauth_path_prefix = '/my_engine/users/auth' 305 | 306 | # ==> Turbolinks configuration 307 | # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: 308 | # 309 | # ActiveSupport.on_load(:devise_failure_app) do 310 | # include Turbolinks::Controller 311 | # end 312 | 313 | # ==> Configuration for :registerable 314 | 315 | # When set to false, does not sign a user in automatically after their password is 316 | # changed. Defaults to true, so a user is signed in automatically after changing a password. 317 | # config.sign_in_after_change_password = true 318 | end 319 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /config/locales/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | en: 4 | devise: 5 | confirmations: 6 | confirmed: "Your email address has been successfully confirmed." 7 | send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." 8 | send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." 9 | failure: 10 | already_authenticated: "You are already signed in." 11 | inactive: "Your account is not activated yet." 12 | invalid: "Invalid %{authentication_keys} or password." 13 | locked: "Your account is locked." 14 | last_attempt: "You have one more attempt before your account is locked." 15 | not_found_in_database: "Invalid %{authentication_keys} or password." 16 | timeout: "Your session expired. Please sign in again to continue." 17 | unauthenticated: "You need to sign in or sign up before continuing." 18 | unconfirmed: "You have to confirm your email address before continuing." 19 | mailer: 20 | confirmation_instructions: 21 | subject: "Confirmation instructions" 22 | reset_password_instructions: 23 | subject: "Reset password instructions" 24 | unlock_instructions: 25 | subject: "Unlock instructions" 26 | email_changed: 27 | subject: "Email Changed" 28 | password_change: 29 | subject: "Password Changed" 30 | omniauth_callbacks: 31 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"." 32 | success: "Successfully authenticated from %{kind} account." 33 | passwords: 34 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." 35 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." 36 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." 37 | updated: "Your password has been changed successfully. You are now signed in." 38 | updated_not_active: "Your password has been changed successfully." 39 | registrations: 40 | destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." 41 | signed_up: "Welcome! You have signed up successfully." 42 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." 43 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." 44 | signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." 45 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address." 46 | updated: "Your account has been updated successfully." 47 | updated_but_not_signed_in: "Your account has been updated successfully, but since your password was changed, you need to sign in again" 48 | sessions: 49 | signed_in: "Signed in successfully." 50 | signed_out: "Signed out successfully." 51 | already_signed_out: "Signed out successfully." 52 | unlocks: 53 | send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." 54 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." 55 | unlocked: "Your account has been unlocked successfully. Please sign in to continue." 56 | errors: 57 | messages: 58 | already_confirmed: "was already confirmed, please try signing in" 59 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" 60 | expired: "has expired, please request a new one" 61 | not_found: "not found" 62 | not_locked: "was not locked" 63 | not_saved: 64 | one: "1 error prohibited this %{resource} from being saved:" 65 | other: "%{count} errors prohibited this %{resource} from being saved:" 66 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at http://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers: a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum; this matches the default thread size of Active Record. 6 | # 7 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } 8 | threads threads_count, threads_count 9 | 10 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 11 | # 12 | port ENV.fetch("PORT") { 3000 } 13 | 14 | # Specifies the `environment` that Puma will run in. 15 | # 16 | environment ENV.fetch("RAILS_ENV") { "development" } 17 | 18 | # Specifies the number of `workers` to boot in clustered mode. 19 | # Workers are forked webserver processes. If using threads and workers together 20 | # the concurrency of the application would be max `threads` * `workers`. 21 | # Workers do not work on JRuby or Windows (both of which do not support 22 | # processes). 23 | # 24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 25 | 26 | # Use the `preload_app!` method when specifying a `workers` number. 27 | # This directive tells Puma to first boot the application and load code 28 | # before forking the application. This takes advantage of Copy On Write 29 | # process behavior so workers use less memory. 30 | # 31 | # preload_app! 32 | 33 | # Allow puma to be restarted by `rails restart` command. 34 | plugin :tmp_restart 35 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.routes.draw do 4 | devise_for :users, skip: :sessions 5 | 6 | if Rails.env.development? 7 | mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql" 8 | end 9 | post "/graphql", to: "graphql#execute" 10 | # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 11 | 12 | root "application#index" 13 | 14 | # Catch all for HTML 5 history routing. This must be the last route. 15 | get "/*path", to: "application#index", format: false 16 | end 17 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | %w[ 2 | .ruby-version 3 | .rbenv-vars 4 | tmp/restart.txt 5 | tmp/caching-dev.txt 6 | ].each { |path| Spring.watch(path) } 7 | -------------------------------------------------------------------------------- /config/storage.yml: -------------------------------------------------------------------------------- 1 | test: 2 | service: Disk 3 | root: <%= Rails.root.join("tmp/storage") %> 4 | 5 | local: 6 | service: Disk 7 | root: <%= Rails.root.join("storage") %> 8 | 9 | # Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) 10 | # amazon: 11 | # service: S3 12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> 13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> 14 | # region: us-east-1 15 | # bucket: your_own_bucket 16 | 17 | # Remember not to checkin your GCS keyfile to a repository 18 | # google: 19 | # service: GCS 20 | # project: your_project 21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> 22 | # bucket: your_own_bucket 23 | 24 | # Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) 25 | # microsoft: 26 | # service: AzureStorage 27 | # storage_account_name: your_account_name 28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> 29 | # container: your_container_name 30 | 31 | # mirror: 32 | # service: Mirror 33 | # primary: local 34 | # mirrors: [ amazon, google, microsoft ] 35 | -------------------------------------------------------------------------------- /config/webpack/custom.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const webpack = require('webpack'); 3 | const { VueLoaderPlugin } = require('vue-loader'); 4 | 5 | module.exports = { 6 | plugins: [ 7 | // See https://github.com/moment/moment/issues/2979#issuecomment-189899510 8 | new webpack 9 | .ContextReplacementPlugin(/\.\/locale$/, 'empty-module', false, /js$/), 10 | new VueLoaderPlugin(), 11 | ], 12 | resolve: { 13 | modules: [ 14 | path.resolve('./app/javascript/'), 15 | ], 16 | alias: { 17 | '~components': path.resolve('./app/javascript/components'), 18 | '~configuration': path.resolve('./app/javascript/packs/configuration'), 19 | '~lib': path.resolve('./app/javascript/lib'), 20 | '~mixins': path.resolve('./app/javascript/mixins'), 21 | '~mutations': path.resolve('./app/javascript/mutations'), 22 | '~pages': path.resolve('./app/javascript/pages'), 23 | '~queries': path.resolve('./app/javascript/queries'), 24 | '~store': path.resolve('./app/javascript/store'), 25 | }, 26 | extensions: ['*', '.js', '.vue', '.json'], 27 | }, 28 | }; 29 | -------------------------------------------------------------------------------- /config/webpack/development.js: -------------------------------------------------------------------------------- 1 | process.env.NODE_ENV = process.env.NODE_ENV || 'development' 2 | 3 | const environment = require('./environment') 4 | 5 | module.exports = environment.toWebpackConfig() 6 | -------------------------------------------------------------------------------- /config/webpack/environment.js: -------------------------------------------------------------------------------- 1 | const { environment } = require('@rails/webpacker'); 2 | const customConfig = require('./custom'); 3 | const vue = require('./loaders/vue'); 4 | 5 | environment.config.merge(customConfig); 6 | 7 | environment.loaders.append('vue', vue); 8 | module.exports = environment; 9 | -------------------------------------------------------------------------------- /config/webpack/loaders/vue.js: -------------------------------------------------------------------------------- 1 | const { dev_server: devServer } = require('@rails/webpacker').config 2 | 3 | const isProduction = process.env.NODE_ENV === 'production' 4 | const inDevServer = process.argv.find(v => v.includes('webpack-dev-server')) 5 | const extractCSS = !(inDevServer && (devServer && devServer.hmr)) || isProduction 6 | 7 | module.exports = { 8 | test: /\.vue(\.erb)?$/, 9 | use: [{ 10 | loader: 'vue-loader', 11 | options: { 12 | extractCSS, 13 | loaders: { 14 | sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax' // 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /public/apple-touch-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/public/apple-touch-icon-precomposed.png -------------------------------------------------------------------------------- /public/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/public/apple-touch-icon.png -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/public/favicon.ico -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | FactoryBot.define do 4 | factory :user do 5 | sequence(:email) { |n| "test-#{n}@gmail.com" } 6 | first_name { "Test" } 7 | last_name { "Man" } 8 | password { "testing123" } 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /spec/graphql/mutations/base_mutation_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe Mutations::BaseMutation do 6 | describe "#authorize_user" do 7 | it "returns true if user is signed in" do 8 | mutation = Mutations::BaseMutation.new( 9 | object: nil, context: { current_user: double } 10 | ) 11 | 12 | expect(mutation.send(:authorize_user)).to eq(true) 13 | end 14 | 15 | it "raise an error if not signed in" do 16 | mutation = Mutations::BaseMutation.new( 17 | object: nil, context: { current_user: nil } 18 | ) 19 | 20 | expect { mutation.send(:authorize_user) }. 21 | to raise_error(GraphQL::ExecutionError, "User not signed in") 22 | end 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /spec/graphql/mutations/mutation_result_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe Mutations::MutationResult do 6 | describe ".call" do 7 | it "returns the full hash with default keys" do 8 | result = described_class.call(obj: { user: { name: "test" } }) 9 | 10 | expect(result.dig(:user, :name)).to eq("test") 11 | expect(result[:success]).to eq(true) 12 | expect(result[:errors]).to eq([]) 13 | end 14 | 15 | it "returns the full hash with no object" do 16 | result = described_class.call 17 | 18 | expect(result.keys).to contain_exactly(:success, :errors) 19 | expect(result[:success]).to eq(true) 20 | expect(result[:errors]).to eq([]) 21 | end 22 | 23 | it "returns the full hash with overrides" do 24 | result = described_class.call( 25 | obj: { test: "this" }, 26 | success: false, 27 | errors: ["blah"] 28 | ) 29 | 30 | expect(result[:test]).to eq("this") 31 | expect(result[:success]).to eq(false) 32 | expect(result[:errors]).to eq(["blah"]) 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /spec/graphql/mutations/register_user_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe Mutations::RegisterUser do 6 | it "registers the user" do 7 | variables = { 8 | "firstName" => "James", 9 | "lastName" => "Klein", 10 | "email" => "kleinjm007@gmail.com", 11 | "password" => "testing123" 12 | } 13 | 14 | result = gql_query(query: mutation, variables: variables). 15 | to_h.deep_symbolize_keys.dig(:data, :registerUser) 16 | 17 | user = User.first 18 | expect(result.dig(:user, :id)).to eq(user.gql_id) 19 | expect(result.dig(:user, :firstName)).to eq(variables["firstName"]) 20 | expect(result.dig(:user, :lastName)).to eq(variables["lastName"]) 21 | expect(result.dig(:user, :email)).to eq(variables["email"]) 22 | expect(result[:errors]).to be_blank 23 | end 24 | 25 | it "raises error for RecordInvalid" do 26 | variables = { 27 | "firstName" => "James", 28 | "lastName" => "Klein", 29 | "email" => "kleinjm007@gmail.com", 30 | "password" => "testing123" 31 | } 32 | 33 | user = User.new 34 | user.validate # missing fields makes this invalid 35 | allow(User).to receive(:create!). 36 | and_raise(ActiveRecord::RecordInvalid.new(user)) 37 | result = gql_query(query: mutation, variables: variables). 38 | to_h.deep_symbolize_keys 39 | 40 | expect(result[:errors]).to_not be_blank 41 | expect(result.dig(:errors, 0, :message)). 42 | to include(user.errors.full_messages.first) 43 | end 44 | 45 | def mutation 46 | <<~GQL 47 | mutation registerUser( 48 | $firstName: String!, 49 | $lastName: String!, 50 | $email: String!, 51 | $password: String!, 52 | ) { 53 | registerUser(input: { 54 | firstName: $firstName, 55 | lastName: $lastName, 56 | email: $email, 57 | password: $password, 58 | }) { 59 | user { 60 | id 61 | firstName 62 | lastName 63 | email 64 | authenticationToken 65 | } 66 | success 67 | errors 68 | } 69 | } 70 | GQL 71 | end 72 | end 73 | -------------------------------------------------------------------------------- /spec/graphql/mutations/sign_in_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe Mutations::SignIn do 6 | it "signs in the user" do 7 | variables = { 8 | "email" => "kleinjm007@gmail.com", 9 | "password" => "testing123" 10 | } 11 | user = create(:user, **variables.symbolize_keys) 12 | 13 | result = gql_query(query: mutation, variables: variables). 14 | to_h.deep_symbolize_keys.dig(:data, :signIn) 15 | 16 | user.reload 17 | expect(result.dig(:user, :id)).to eq(user.gql_id) 18 | expect(result.dig(:user, :authenticationToken)). 19 | to eq(user.authentication_token) 20 | expect(result[:success]).to eq(true) 21 | expect(result[:errors]).to be_blank 22 | end 23 | 24 | it "raises error for incorrect email/password" do 25 | variables = { 26 | "email" => "kleinjm007@gmail.com", 27 | "password" => "testing123" 28 | } 29 | user_variables = { email: variables["email"], password: "wrongpass1" } 30 | create(:user, **user_variables) 31 | 32 | result = gql_query(query: mutation, variables: variables). 33 | to_h.deep_symbolize_keys 34 | 35 | expect(result.dig(:errors, 0, :message)).to eq("Incorrect Email/Password") 36 | expect(result.dig(:data, :signIn)).to be_blank 37 | end 38 | 39 | it "raises error for missing user" do 40 | variables = { 41 | "email" => "kleinjm007@gmail.com", 42 | "password" => "testing123" 43 | } 44 | 45 | result = gql_query(query: mutation, variables: variables). 46 | to_h.deep_symbolize_keys 47 | 48 | expect(result.dig(:errors, 0, :message)). 49 | to eq("User not registered on this application") 50 | expect(result.dig(:data, :signIn)).to be_blank 51 | end 52 | 53 | def mutation 54 | <<~GQL 55 | mutation signIn($email: String!, $password: String!) { 56 | signIn(input: { email: $email, password: $password }) { 57 | user { 58 | id 59 | firstName 60 | lastName 61 | authenticationToken 62 | } 63 | success 64 | errors 65 | } 66 | } 67 | GQL 68 | end 69 | end 70 | -------------------------------------------------------------------------------- /spec/graphql/mutations/sign_out_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe Mutations::SignOut do 6 | it "signs out the current user" do 7 | user = create(:user) 8 | auth_token = user.authentication_token 9 | 10 | result = gql_query(query: mutation, context: { current_user: user }). 11 | to_h.deep_symbolize_keys.dig(:data, :signOut) 12 | 13 | user.reload 14 | expect(result.dig(:user, :id)).to eq(user.gql_id) 15 | expect(result.dig(:user, :authenticationToken)).to_not eq(auth_token) 16 | expect(user.authentication_token).to_not eq(auth_token) 17 | expect(result[:success]).to eq(true) 18 | expect(result[:errors]).to be_blank 19 | end 20 | 21 | it "raises error for user not signed in" do 22 | result = gql_query(query: mutation).to_h.deep_symbolize_keys 23 | 24 | expect(result.dig(:errors, 0, :message)).to eq("User not signed in") 25 | expect(result.dig(:data, :signIn)).to be_blank 26 | end 27 | 28 | def mutation 29 | <<~GQL 30 | mutation signOut { 31 | signOut(input: {}) { 32 | user { 33 | id 34 | authenticationToken 35 | } 36 | success 37 | errors 38 | } 39 | } 40 | GQL 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /spec/graphql/types/user_type_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe Types::UserType do 6 | it "returns the auth token if current user" do 7 | user = create(:user) 8 | variables = { "id" => user.gql_id } 9 | 10 | result = gql_query( 11 | query: query, variables: variables, context: { current_user: user } 12 | ).to_h.deep_symbolize_keys 13 | 14 | expect(result.dig(:data, :node, :id)).to eq(user.gql_id) 15 | expect(result.dig(:data, :node, :authenticationToken)). 16 | to eq(user.authentication_token) 17 | expect(result[:errors]).to be_blank 18 | end 19 | 20 | it "does not return the authenticationToken for non current user" do 21 | user = create(:user) 22 | variables = { "id" => user.gql_id } 23 | 24 | result = gql_query(query: query, variables: variables). 25 | to_h.deep_symbolize_keys 26 | 27 | expect(result.dig(:data, :node)).to be_nil 28 | expect(result[:errors]).to_not be_blank 29 | end 30 | 31 | def query 32 | <<~GQL 33 | query user($id: ID!) { 34 | node(id: $id) { 35 | ... on User { 36 | id 37 | firstName 38 | lastName 39 | authenticationToken 40 | } 41 | } 42 | } 43 | GQL 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /spec/graphql/vue_graphql_auth_example_schema_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe VueGraphqlAuthExampleSchema do 6 | describe ".resolve_type" do 7 | it "resolves the given type dynamically" do 8 | [User].each do |klass| 9 | expect(described_class.resolve_type(nil, klass.new, nil).name). 10 | to eq(klass.name) 11 | end 12 | end 13 | 14 | it "raises an error for unknown type" do 15 | expect { described_class.resolve_type(nil, RSpec, nil) }. 16 | to raise_error(RuntimeError, "Unexpected object: RSpec") 17 | end 18 | end 19 | 20 | describe ".id_from_object" do 21 | it "returns the gql id for the given object" do 22 | user = User.new(id: 123) 23 | id = described_class.id_from_object(user, User) 24 | 25 | expect(Base64.decode64(id)).to eq("User-123") 26 | end 27 | end 28 | 29 | describe ".object_from_id" do 30 | it "returns an instance of the object from the given gql id" do 31 | user = create(:user) 32 | expect(described_class.object_from_id(user.gql_id, nil)).to eq(user) 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /spec/models/concerns/graph_ql/interface_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe GraphQL::Interface do 6 | class MockClass 7 | include GraphQL::Interface 8 | 9 | attr_reader :id 10 | 11 | def initialize(id = 123) 12 | @id = id 13 | end 14 | 15 | def self.find(id) 16 | new(id.to_i) 17 | end 18 | 19 | def self.where(id_hash) 20 | id_hash[:id].map { |id| new(id.to_i) } 21 | end 22 | end 23 | 24 | describe "#gql_id" do 25 | it "returns the gql id" do 26 | expect(MockClass.new.gql_id).to be_a(String) 27 | expect(MockClass.new.gql_id.length).to eq(20) 28 | expect(Base64.decode64(MockClass.new.gql_id)).to eq("MockClass-123") 29 | end 30 | end 31 | 32 | describe ".find_by_gql_id" do 33 | it "finds the MockClass with the given gql id" do 34 | mock_class = MockClass.new(456) 35 | 36 | expect(MockClass.find_by_gql_id(mock_class.gql_id).id). 37 | to eq(mock_class.id) 38 | end 39 | 40 | it "raises an error when given invalid id" do 41 | expect { MockClass.find_by_gql_id("bad-id") }. 42 | to raise_error(ArgumentError) 43 | end 44 | end 45 | 46 | describe ".find_by_gql_ids" do 47 | it "finds the MockClass with the given gql ids" do 48 | mock_class = MockClass.new(456) 49 | 50 | expect(MockClass.find_by_gql_ids([mock_class.gql_id]).first.id). 51 | to eq(mock_class.id) 52 | end 53 | end 54 | end 55 | -------------------------------------------------------------------------------- /spec/models/user_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe User do 6 | describe "callbacks" do 7 | it "creates an auth token before saving if one does not exist" do 8 | # See: Devise initializer `config.http_authenticatable = true` 9 | user = User.new(attributes_for(:user)) 10 | expect(user.authentication_token).to be_blank 11 | 12 | user.save 13 | 14 | expect(user.reload.authentication_token).to_not be_blank 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | require 'spec_helper' 3 | ENV['RAILS_ENV'] ||= 'test' 4 | require File.expand_path('../../config/environment', __FILE__) 5 | # Prevent database truncation if the environment is production 6 | abort("The Rails environment is running in production mode!") if Rails.env.production? 7 | require 'rspec/rails' 8 | 9 | Dir[Rails.root.join("spec", "support", "**", "*.rb")].each { |f| require f } 10 | 11 | # Add additional requires below this line. Rails is not loaded until this point! 12 | 13 | # Requires supporting ruby files with custom matchers and macros, etc, in 14 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 15 | # run as spec files by default. This means that files in spec/support that end 16 | # in _spec.rb will both be required and run as specs, causing the specs to be 17 | # run twice. It is recommended that you do not name files matching this glob to 18 | # end with _spec.rb. You can configure this pattern with the --pattern 19 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 20 | # 21 | # The following line is provided for convenience purposes. It has the downside 22 | # of increasing the boot-up time by auto-requiring all files in the support 23 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 24 | # require only the support files necessary. 25 | # 26 | # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } 27 | 28 | # Checks for pending migrations and applies them before tests are run. 29 | # If you are not using ActiveRecord, you can remove these lines. 30 | begin 31 | ActiveRecord::Migration.maintain_test_schema! 32 | rescue ActiveRecord::PendingMigrationError => e 33 | puts e.to_s.strip 34 | exit 1 35 | end 36 | RSpec.configure do |config| 37 | config.include FactoryBot::Syntax::Methods 38 | 39 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 40 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 41 | 42 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 43 | # examples within a transaction, remove the following line or assign false 44 | # instead of true. 45 | config.use_transactional_fixtures = true 46 | 47 | # RSpec Rails can automatically mix in different behaviours to your tests 48 | # based on their file location, for example enabling you to call `get` and 49 | # `post` in specs under `spec/controllers`. 50 | # 51 | # You can disable this behaviour by removing the line below, and instead 52 | # explicitly tag your specs with their type, e.g.: 53 | # 54 | # RSpec.describe UsersController, :type => :controller do 55 | # # ... 56 | # end 57 | # 58 | # The different available types are documented in the features, such as in 59 | # https://relishapp.com/rspec/rspec-rails/docs 60 | config.infer_spec_type_from_file_location! 61 | 62 | # Filter lines from Rails gems in backtraces. 63 | config.filter_rails_from_backtrace! 64 | # arbitrary gems may also be filtered via: 65 | # config.filter_gems_from_backtrace("gem name") 66 | end 67 | -------------------------------------------------------------------------------- /spec/requests/graphql_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | RSpec.describe "POST /graphql" do 6 | it "executes the given query or mutation" do 7 | stub_schema_execute 8 | 9 | variables = { "myVariables" => "test" } 10 | query = "someLongQuery(input: { id: ID } { users { id name } })" 11 | operation_name = "signIn" 12 | 13 | post graphql_path( 14 | format: :json, 15 | variables: variables.to_json, 16 | query: query, 17 | operationName: operation_name 18 | ) 19 | 20 | expect(VueGraphqlAuthExampleSchema).to have_received(:execute).with( 21 | query, 22 | variables: variables, 23 | context: { current_user: nil }, 24 | operation_name: operation_name 25 | ) 26 | expect(json_body).to eq("success" => true) 27 | end 28 | 29 | it "sets the current_user context" do 30 | stub_schema_execute 31 | user = sign_in_user 32 | 33 | post graphql_path(format: :json) 34 | 35 | expect(VueGraphqlAuthExampleSchema).to have_received(:execute).with( 36 | nil, 37 | variables: {}, 38 | context: { current_user: user }, 39 | operation_name: nil 40 | ) 41 | expect(json_body).to eq("success" => true) 42 | end 43 | 44 | # ... 45 | 46 | def stub_schema_execute 47 | allow(VueGraphqlAuthExampleSchema). 48 | to receive(:execute).and_return(success: true) 49 | end 50 | 51 | def json_body 52 | json = JSON.parse(response.body) 53 | json.is_a?(Hash) ? json.with_indifferent_access : json # could be an array 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 3 | # The generated `.rspec` file contains `--require spec_helper` which will cause 4 | # this file to always be loaded, without a need to explicitly require it in any 5 | # files. 6 | # 7 | # Given that it is always loaded, you are encouraged to keep this file as 8 | # light-weight as possible. Requiring heavyweight dependencies from this file 9 | # will add to the boot time of your test suite on EVERY test run, even for an 10 | # individual file that may not need all of that loaded. Instead, consider making 11 | # a separate helper file that requires the additional dependencies and performs 12 | # the additional setup, and require it from the spec files that actually need 13 | # it. 14 | # 15 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 16 | RSpec.configure do |config| 17 | # rspec-expectations config goes here. You can use an alternate 18 | # assertion/expectation library such as wrong or the stdlib/minitest 19 | # assertions if you prefer. 20 | config.expect_with :rspec do |expectations| 21 | # This option will default to `true` in RSpec 4. It makes the `description` 22 | # and `failure_message` of custom matchers include text for helper methods 23 | # defined using `chain`, e.g.: 24 | # be_bigger_than(2).and_smaller_than(4).description 25 | # # => "be bigger than 2 and smaller than 4" 26 | # ...rather than: 27 | # # => "be bigger than 2" 28 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 29 | end 30 | 31 | # rspec-mocks config goes here. You can use an alternate test double 32 | # library (such as bogus or mocha) by changing the `mock_with` option here. 33 | config.mock_with :rspec do |mocks| 34 | # Prevents you from mocking or stubbing a method that does not exist on 35 | # a real object. This is generally recommended, and will default to 36 | # `true` in RSpec 4. 37 | mocks.verify_partial_doubles = true 38 | end 39 | 40 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will 41 | # have no way to turn it off -- the option exists only for backwards 42 | # compatibility in RSpec 3). It causes shared context metadata to be 43 | # inherited by the metadata hash of host groups and examples, rather than 44 | # triggering implicit auto-inclusion in groups with matching metadata. 45 | config.shared_context_metadata_behavior = :apply_to_host_groups 46 | 47 | # The settings below are suggested to provide a good initial experience 48 | # with RSpec, but feel free to customize to your heart's content. 49 | =begin 50 | # This allows you to limit a spec run to individual examples or groups 51 | # you care about by tagging them with `:focus` metadata. When nothing 52 | # is tagged with `:focus`, all examples get run. RSpec also provides 53 | # aliases for `it`, `describe`, and `context` that include `:focus` 54 | # metadata: `fit`, `fdescribe` and `fcontext`, respectively. 55 | config.filter_run_when_matching :focus 56 | 57 | # Allows RSpec to persist some state between runs in order to support 58 | # the `--only-failures` and `--next-failure` CLI options. We recommend 59 | # you configure your source control system to ignore this file. 60 | config.example_status_persistence_file_path = "spec/examples.txt" 61 | 62 | # Limits the available syntax to the non-monkey patched syntax that is 63 | # recommended. For more details, see: 64 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ 65 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 66 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode 67 | config.disable_monkey_patching! 68 | 69 | # Many RSpec users commonly either run the entire suite or an individual 70 | # file, and it's useful to allow more verbose output when running an 71 | # individual spec file. 72 | if config.files_to_run.one? 73 | # Use the documentation formatter for detailed output, 74 | # unless a formatter has already been configured 75 | # (e.g. via a command-line flag). 76 | config.default_formatter = "doc" 77 | end 78 | 79 | # Print the 10 slowest examples and example groups at the 80 | # end of the spec run, to help surface which specs are running 81 | # particularly slow. 82 | config.profile_examples = 10 83 | 84 | # Run specs in random order to surface order dependencies. If you find an 85 | # order dependency and want to debug it, you can fix the order by providing 86 | # the seed, which is printed after each run. 87 | # --seed 1234 88 | config.order = :random 89 | 90 | # Seed global randomization in this process using the `--seed` CLI option. 91 | # Setting this allows you to use `--seed` to deterministically reproduce 92 | # test failures related to randomization by passing the same `--seed` value 93 | # as the one that triggered the failure. 94 | Kernel.srand config.seed 95 | =end 96 | end 97 | -------------------------------------------------------------------------------- /spec/support/graphql_config.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | RSpec.configure do |config| 4 | # infer the integrations dir so we don't need to add the tag to each one 5 | config.define_derived_metadata( 6 | file_path: Regexp.new("/spec/graphql/") 7 | ) do |metadata| 8 | metadata[:type] = :gql 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /spec/support/graphql_support.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module GqlSupport 4 | def gql_query(query:, variables: {}, context: {}, account: nil) 5 | add_account(context: context, account: account) 6 | 7 | query = GraphQL::Query.new( 8 | VueGraphqlAuthExampleSchema, 9 | query, 10 | variables: variables.deep_stringify_keys, 11 | context: context 12 | ) 13 | 14 | query.result if query.valid? 15 | end 16 | 17 | private 18 | 19 | def add_account(context:, account:) 20 | return if account.blank? 21 | 22 | context[:current_account] = account 23 | context[:current_user] = account.users&.first 24 | end 25 | end 26 | 27 | RSpec.configure do |config| 28 | config.include GqlSupport, type: :gql 29 | end 30 | -------------------------------------------------------------------------------- /spec/support/request_spec_support.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module RequestSpecHelper 4 | include Warden::Test::Helpers 5 | 6 | def self.included(base) 7 | base.before(:each) { Warden.test_mode! } 8 | base.after(:each) { Warden.test_reset! } 9 | end 10 | 11 | def sign_in(resource) 12 | login_as(resource, scope: warden_scope(resource)) 13 | end 14 | 15 | def sign_out(resource) 16 | logout(warden_scope(resource)) 17 | end 18 | 19 | def sign_in_user 20 | user = create :user 21 | sign_in(user) 22 | user 23 | end 24 | 25 | private 26 | 27 | def warden_scope(resource) 28 | resource.class.name.underscore.to_sym 29 | end 30 | end 31 | 32 | RSpec.configure do |config| 33 | config.include RequestSpecHelper, type: :request 34 | end 35 | -------------------------------------------------------------------------------- /storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/storage/.keep -------------------------------------------------------------------------------- /test/application_system_test_case.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class ApplicationSystemTestCase < ActionDispatch::SystemTestCase 4 | driven_by :selenium, using: :chrome, screen_size: [1400, 1400] 5 | end 6 | -------------------------------------------------------------------------------- /test/controllers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/test/controllers/.keep -------------------------------------------------------------------------------- /test/fixtures/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/test/fixtures/.keep -------------------------------------------------------------------------------- /test/fixtures/files/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/test/fixtures/files/.keep -------------------------------------------------------------------------------- /test/fixtures/users.yml: -------------------------------------------------------------------------------- 1 | # Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html 2 | 3 | # This model initially had no columns defined. If you add columns to the 4 | # model remove the '{}' from the fixture names and add the columns immediately 5 | # below each fixture, per the syntax in the comments below 6 | # 7 | one: {} 8 | # column: value 9 | # 10 | two: {} 11 | # column: value 12 | -------------------------------------------------------------------------------- /test/helpers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/test/helpers/.keep -------------------------------------------------------------------------------- /test/integration/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/test/integration/.keep -------------------------------------------------------------------------------- /test/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/test/mailers/.keep -------------------------------------------------------------------------------- /test/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/test/models/.keep -------------------------------------------------------------------------------- /test/models/user_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | 3 | class UserTest < ActiveSupport::TestCase 4 | # test "the truth" do 5 | # assert true 6 | # end 7 | end 8 | -------------------------------------------------------------------------------- /test/system/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/test/system/.keep -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | ENV['RAILS_ENV'] ||= 'test' 2 | require_relative '../config/environment' 3 | require 'rails/test_help' 4 | 5 | class ActiveSupport::TestCase 6 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. 7 | fixtures :all 8 | 9 | # Add more helper methods to be used by all tests here... 10 | end 11 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/tmp/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kleinjm/vue_graphql_auth_example/15d2caaa639c6ed1959a1d33d498510e1b764cae/vendor/.keep --------------------------------------------------------------------------------