From b7cfaa7495ff0fd3eb99df0510007aac7f967ee1 Mon Sep 17 00:00:00 2001 From: Rasmus Kjellberg <2277443+kjellberg@users.noreply.github.com> Date: Tue, 9 Apr 2024 20:50:43 +0200 Subject: [PATCH] refactor: create Account::Create service and extract to kiqr gem --- Gemfile | 3 - Gemfile.lock | 6 +- app/controllers/accounts_controller.rb | 7 +- config/routes/authentication.rb | 6 - gems/kiqr/Gemfile | 14 + gems/kiqr/Gemfile.lock | 239 +++++++++++++ {app => gems/kiqr/app}/models/account.rb | 0 {app => gems/kiqr/app}/models/account_user.rb | 0 {app => gems/kiqr/app}/models/user.rb | 0 gems/kiqr/config/initializers/devise.rb | 313 ++++++++++++++++++ gems/kiqr/config/routes.rb | 5 + .../20240321094123_devise_create_users.rb | 43 +++ .../migrate/20240325084418_create_accounts.rb | 14 + .../20240325142603_create_account_users.rb | 11 + ...01110029_add_devise_two_factor_to_users.rb | 8 + ...4092246_add_public_uid_to_account_users.rb | 6 + ...eplace_role_with_owner_on_account_users.rb | 6 + ...240407174725_create_account_invitations.rb | 15 + ...05555_add_unique_index_to_account_users.rb | 5 + ...10931_add_locale_and_time_zone_to_users.rb | 6 + gems/kiqr/kiqr.gemspec | 3 + gems/kiqr/lib/kiqr.rb | 15 +- gems/kiqr/lib/kiqr/application_service.rb | 35 ++ .../kiqr/lib/kiqr/services/accounts/create.rb | 38 +++ {test/kiqr => gems/kiqr/test}/config_test.rb | 9 +- gems/kiqr/test/dummy/db/schema.rb | 88 +++++ gems/kiqr/test/factories/accounts.rb | 6 + gems/kiqr/test/factories/user.rb | 18 + .../test/services/accounts/create_test.rb | 48 +++ gems/kiqr/test/test_helper.rb | 29 +- 30 files changed, 971 insertions(+), 25 deletions(-) create mode 100644 gems/kiqr/Gemfile.lock rename {app => gems/kiqr/app}/models/account.rb (100%) rename {app => gems/kiqr/app}/models/account_user.rb (100%) rename {app => gems/kiqr/app}/models/user.rb (100%) create mode 100644 gems/kiqr/config/initializers/devise.rb create mode 100644 gems/kiqr/db/migrate/20240321094123_devise_create_users.rb create mode 100644 gems/kiqr/db/migrate/20240325084418_create_accounts.rb create mode 100644 gems/kiqr/db/migrate/20240325142603_create_account_users.rb create mode 100644 gems/kiqr/db/migrate/20240401110029_add_devise_two_factor_to_users.rb create mode 100644 gems/kiqr/db/migrate/20240404092246_add_public_uid_to_account_users.rb create mode 100644 gems/kiqr/db/migrate/20240404205037_replace_role_with_owner_on_account_users.rb create mode 100644 gems/kiqr/db/migrate/20240407174725_create_account_invitations.rb create mode 100644 gems/kiqr/db/migrate/20240408105555_add_unique_index_to_account_users.rb create mode 100644 gems/kiqr/db/migrate/20240408210931_add_locale_and_time_zone_to_users.rb create mode 100644 gems/kiqr/lib/kiqr/application_service.rb create mode 100644 gems/kiqr/lib/kiqr/services/accounts/create.rb rename {test/kiqr => gems/kiqr/test}/config_test.rb (63%) create mode 100644 gems/kiqr/test/dummy/db/schema.rb create mode 100644 gems/kiqr/test/factories/accounts.rb create mode 100644 gems/kiqr/test/factories/user.rb create mode 100644 gems/kiqr/test/services/accounts/create_test.rb diff --git a/Gemfile b/Gemfile index 3d82f86..bbbbbcb 100644 --- a/Gemfile +++ b/Gemfile @@ -47,11 +47,8 @@ gem "bootsnap", require: false # Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] # gem "image_processing", "~> 1.2" -gem "devise", "~> 4.9", ">= 4.9.3" -gem "devise-two-factor", "~> 5.0.0" gem "dry-initializer", "~> 3.1" gem "meta-tags", "~> 2.20" -gem "public_uid", "~> 2.2" gem "rqrcode", "~> 2.0" gem "simple_form", "~> 5.3.0" gem "view_component", "~> 3.11" diff --git a/Gemfile.lock b/Gemfile.lock index 7c0bc87..7cd5899 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -2,6 +2,9 @@ PATH remote: gems/kiqr specs: kiqr (0.1.0) + devise (~> 4.9, >= 4.9.3) + devise-two-factor (~> 5.0.0) + public_uid (~> 2.2) rails (>= 7.1.3.2) GEM @@ -403,8 +406,6 @@ DEPENDENCIES brakeman (~> 6.1) capybara debug - devise (~> 4.9, >= 4.9.3) - devise-two-factor (~> 5.0.0) dry-initializer (~> 3.1) erb_lint factory_bot_rails (~> 6.4.3) @@ -414,7 +415,6 @@ DEPENDENCIES kiqr! letter_opener_web (~> 2.0) meta-tags (~> 2.20) - public_uid (~> 2.2) puma (>= 5.0) rails (~> 7.1.3, >= 7.1.3.2) rails-controller-testing diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb index 37d4c8e..e16d834 100644 --- a/app/controllers/accounts_controller.rb +++ b/app/controllers/accounts_controller.rb @@ -7,10 +7,11 @@ def new def create @account = Account.new(account_permitted_parameters) - @account.account_users.new(user: current_user, owner: true) - if @account.save - redirect_to dashboard_path(account_id: @account), notice: I18n.t("accounts.create.success") + if @account.valid? + Kiqr::Services::Accounts::Create.call!(account: @account, user: current_user) + flash[:notice] = I18n.t("accounts.create.success") + redirect_to dashboard_path(account_id: @account) else render :new, status: :unprocessable_entity end diff --git a/config/routes/authentication.rb b/config/routes/authentication.rb index 85abfa9..fd2313e 100644 --- a/config/routes/authentication.rb +++ b/config/routes/authentication.rb @@ -1,9 +1,3 @@ -# Devise routes for user authentication -devise_for :users, path_names: {sign_in: "login", sign_up: "create-account"}, controllers: { - registrations: "users/registrations", - sessions: "users/sessions" -} - # User personal accounts. scope module: :users, path: :users do get "onboarding" => "onboarding#new" diff --git a/gems/kiqr/Gemfile b/gems/kiqr/Gemfile index 96069e1..f3f1fbf 100644 --- a/gems/kiqr/Gemfile +++ b/gems/kiqr/Gemfile @@ -12,3 +12,17 @@ gem "sprockets-rails" # Start debugger with binding.b [https://github.com/ruby/debug] # gem "debug", ">= 1.0.0" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + # gem "brakeman", "~> 6.1" + # gem "debug", platforms: %i[mri windows] + + # gem "standard", require: false + # gem "erb_lint", require: false + # gem "letter_opener_web", "~> 2.0" + gem "factory_bot", "~> 6.4.3" + # gem "rails-controller-testing" + gem "faker" + gem "simplecov", require: false +end diff --git a/gems/kiqr/Gemfile.lock b/gems/kiqr/Gemfile.lock new file mode 100644 index 0000000..4f63dbe --- /dev/null +++ b/gems/kiqr/Gemfile.lock @@ -0,0 +1,239 @@ +PATH + remote: . + specs: + kiqr (0.1.0) + devise (~> 4.9, >= 4.9.3) + devise-two-factor (~> 5.0.0) + public_uid (~> 2.2) + rails (>= 7.1.3.2) + +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.1.3.2) + actionpack (= 7.1.3.2) + activesupport (= 7.1.3.2) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (7.1.3.2) + actionpack (= 7.1.3.2) + activejob (= 7.1.3.2) + activerecord (= 7.1.3.2) + activestorage (= 7.1.3.2) + activesupport (= 7.1.3.2) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.1.3.2) + actionpack (= 7.1.3.2) + actionview (= 7.1.3.2) + activejob (= 7.1.3.2) + activesupport (= 7.1.3.2) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.2) + actionpack (7.1.3.2) + actionview (= 7.1.3.2) + activesupport (= 7.1.3.2) + nokogiri (>= 1.8.5) + racc + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + actiontext (7.1.3.2) + actionpack (= 7.1.3.2) + activerecord (= 7.1.3.2) + activestorage (= 7.1.3.2) + activesupport (= 7.1.3.2) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.1.3.2) + activesupport (= 7.1.3.2) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (7.1.3.2) + activesupport (= 7.1.3.2) + globalid (>= 0.3.6) + activemodel (7.1.3.2) + activesupport (= 7.1.3.2) + activerecord (7.1.3.2) + activemodel (= 7.1.3.2) + activesupport (= 7.1.3.2) + timeout (>= 0.4.0) + activestorage (7.1.3.2) + actionpack (= 7.1.3.2) + activejob (= 7.1.3.2) + activerecord (= 7.1.3.2) + activesupport (= 7.1.3.2) + marcel (~> 1.0) + activesupport (7.1.3.2) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.0.2) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + minitest (>= 5.1) + mutex_m + tzinfo (~> 2.0) + base64 (0.2.0) + bcrypt (3.1.20) + bigdecimal (3.1.7) + builder (3.2.4) + concurrent-ruby (1.2.3) + connection_pool (2.4.1) + crass (1.0.6) + date (3.3.4) + devise (4.9.3) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 4.1.0) + responders + warden (~> 1.2.3) + devise-two-factor (5.0.0) + activesupport (~> 7.0) + devise (~> 4.0) + railties (~> 7.0) + rotp (~> 6.0) + docile (1.4.0) + drb (2.2.1) + erubi (1.12.0) + factory_bot (6.4.6) + activesupport (>= 5.0.0) + faker (3.3.1) + i18n (>= 1.8.11, < 2) + globalid (1.2.1) + activesupport (>= 6.1) + i18n (1.14.4) + concurrent-ruby (~> 1.0) + io-console (0.7.2) + irb (1.12.0) + rdoc + reline (>= 0.4.2) + loofah (2.22.0) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.8.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.4) + mini_mime (1.1.5) + minitest (5.22.3) + mutex_m (0.2.0) + net-imap (0.4.10) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-smtp (0.5.0) + net-protocol + nio4r (2.7.1) + nokogiri (1.16.3-arm64-darwin) + racc (~> 1.4) + orm_adapter (0.5.0) + psych (5.1.2) + stringio + public_uid (2.2.0) + activerecord (> 4.2) + puma (6.4.2) + nio4r (~> 2.0) + racc (1.7.3) + rack (3.0.10) + rack-session (2.0.0) + rack (>= 3.0.0) + rack-test (2.1.0) + rack (>= 1.3) + rackup (2.1.0) + rack (>= 3) + webrick (~> 1.8) + rails (7.1.3.2) + actioncable (= 7.1.3.2) + actionmailbox (= 7.1.3.2) + actionmailer (= 7.1.3.2) + actionpack (= 7.1.3.2) + actiontext (= 7.1.3.2) + actionview (= 7.1.3.2) + activejob (= 7.1.3.2) + activemodel (= 7.1.3.2) + activerecord (= 7.1.3.2) + activestorage (= 7.1.3.2) + activesupport (= 7.1.3.2) + bundler (>= 1.15.0) + railties (= 7.1.3.2) + rails-dom-testing (2.2.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.0) + loofah (~> 2.21) + nokogiri (~> 1.14) + railties (7.1.3.2) + actionpack (= 7.1.3.2) + activesupport (= 7.1.3.2) + irb + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + zeitwerk (~> 2.6) + rake (13.1.0) + rdoc (6.6.3.1) + psych (>= 4.0.0) + reline (0.5.0) + io-console (~> 0.5) + responders (3.1.1) + actionpack (>= 5.2) + railties (>= 5.2) + rotp (6.3.0) + simplecov (0.22.0) + docile (~> 1.1) + simplecov-html (~> 0.11) + simplecov_json_formatter (~> 0.1) + simplecov-html (0.12.3) + simplecov_json_formatter (0.1.4) + sprockets (4.2.1) + concurrent-ruby (~> 1.0) + rack (>= 2.2.4, < 4) + sprockets-rails (3.4.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + sprockets (>= 3.0.0) + sqlite3 (1.7.3-arm64-darwin) + stringio (3.1.0) + thor (1.3.1) + timeout (0.4.1) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + warden (1.2.9) + rack (>= 2.0.9) + webrick (1.8.1) + websocket-driver (0.7.6) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.6.13) + +PLATFORMS + arm64-darwin + +DEPENDENCIES + factory_bot (~> 6.4.3) + faker + kiqr! + puma + simplecov + sprockets-rails + sqlite3 + +BUNDLED WITH + 2.5.6 diff --git a/app/models/account.rb b/gems/kiqr/app/models/account.rb similarity index 100% rename from app/models/account.rb rename to gems/kiqr/app/models/account.rb diff --git a/app/models/account_user.rb b/gems/kiqr/app/models/account_user.rb similarity index 100% rename from app/models/account_user.rb rename to gems/kiqr/app/models/account_user.rb diff --git a/app/models/user.rb b/gems/kiqr/app/models/user.rb similarity index 100% rename from app/models/user.rb rename to gems/kiqr/app/models/user.rb diff --git a/gems/kiqr/config/initializers/devise.rb b/gems/kiqr/config/initializers/devise.rb new file mode 100644 index 0000000..7cf34d6 --- /dev/null +++ b/gems/kiqr/config/initializers/devise.rb @@ -0,0 +1,313 @@ +# frozen_string_literal: true + +# Assuming you have not yet modified this file, each configuration option below +# is set to its default value. Note that some are commented out while others +# are not: uncommented lines are intended to protect your configuration from +# breaking changes in upgrades (i.e., in the event that future versions of +# Devise change the default values for those options). +# +# Use this hook to configure devise mailer, warden hooks and so forth. +# Many of these configuration options can be set straight in your model. +Devise.setup do |config| + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + # Devise will use the `secret_key_base` as its `secret_key` + # by default. You can change it below and use your own secret key. + config.secret_key = Rails.application.secret_key_base + + # ==> Controller configuration + # Configure the parent class to the devise controllers. + # config.parent_controller = 'DeviseController' + + # ==> Mailer Configuration + # Configure the e-mail address which will be shown in Devise::Mailer, + # note that it will be overwritten if you use your own mailer class + # with default "from" parameter. + config.mailer_sender = Kiqr::Config.default_from_email + + # Configure the class responsible to send e-mails. + # config.mailer = 'Devise::Mailer' + + # Configure the parent class responsible to send e-mails. + # config.parent_mailer = 'ActionMailer::Base' + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :mongoid (bson_ext recommended) by default. Other ORMs may be + # available as additional gems. + require "devise/orm/active_record" + + # ==> Configuration for any authentication mechanism + # Configure which keys are used when authenticating a user. The default is + # just :email. You can configure it to use [:username, :subdomain], so for + # authenticating a user, both parameters are required. Remember that those + # parameters are used only when authenticating and not when retrieving from + # session. If you need permissions, you should implement that in a before filter. + # You can also supply a hash where the value is a boolean determining whether + # or not authentication should be aborted when the value is not present. + # config.authentication_keys = [:email] + + # Configure parameters from the request object used for authentication. Each entry + # given should be a request method and it will automatically be passed to the + # find_for_authentication method and considered in your model lookup. For instance, + # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. + # The same considerations mentioned for authentication_keys also apply to request_keys. + # config.request_keys = [] + + # Configure which authentication keys should be case-insensitive. + # These keys will be downcased upon creating or modifying a user and when used + # to authenticate or find a user. Default is :email. + config.case_insensitive_keys = [:email] + + # Configure which authentication keys should have whitespace stripped. + # These keys will have whitespace before and after removed upon creating or + # modifying a user and when used to authenticate or find a user. Default is :email. + config.strip_whitespace_keys = [:email] + + # Tell if authentication through request.params is enabled. True by default. + # It can be set to an array that will enable params authentication only for the + # given strategies, for example, `config.params_authenticatable = [:database]` will + # enable it only for database (email + password) authentication. + # config.params_authenticatable = true + + # Tell if authentication through HTTP Auth is enabled. False by default. + # It can be set to an array that will enable http authentication only for the + # given strategies, for example, `config.http_authenticatable = [:database]` will + # enable it only for database authentication. + # For API-only applications to support authentication "out-of-the-box", you will likely want to + # enable this with :database unless you are using a custom strategy. + # The supported strategies are: + # :database = Support basic authentication with authentication key + password + # config.http_authenticatable = false + + # If 401 status code should be returned for AJAX requests. True by default. + # config.http_authenticatable_on_xhr = true + + # The realm used in Http Basic Authentication. 'Application' by default. + # config.http_authentication_realm = 'Application' + + # It will change confirmation, password recovery and other workflows + # to behave the same regardless if the e-mail provided was right or wrong. + # Does not affect registerable. + # config.paranoid = true + + # By default Devise will store the user in session. You can skip storage for + # particular strategies by setting this option. + # Notice that if you are skipping storage for all authentication paths, you + # may want to disable generating routes to Devise's sessions controller by + # passing skip: :sessions to `devise_for` in your config/routes.rb + config.skip_session_storage = [:http_auth] + + # By default, Devise cleans up the CSRF token on authentication to + # avoid CSRF token fixation attacks. This means that, when using AJAX + # requests for sign in and sign up, you need to get a new CSRF token + # from the server. You can disable this option at your own risk. + # config.clean_up_csrf_token_on_authentication = true + + # When false, Devise will not attempt to reload routes on eager load. + # This can reduce the time taken to boot the app but if your application + # requires the Devise mappings to be loaded during boot time the application + # won't boot properly. + # config.reload_routes = true + + # ==> Configuration for :database_authenticatable + # For bcrypt, this is the cost for hashing the password and defaults to 12. If + # using other algorithms, it sets how many times you want the password to be hashed. + # The number of stretches used for generating the hashed password are stored + # with the hashed password. This allows you to change the stretches without + # invalidating existing passwords. + # + # Limiting the stretches to just one in testing will increase the performance of + # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use + # a value less than 10 in other environments. Note that, for bcrypt (the default + # algorithm), the cost increases exponentially with the number of stretches (e.g. + # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). + config.stretches = Rails.env.test? ? 1 : 12 + + # Set up a pepper to generate the hashed password. + # config.pepper = 'ea1b2b6bc2cab3822ab549365377edf897bd981e917fc2edd201e8af3f9dba8ba36adc3237c75cf3bc1f1693bb258e402c1cafd3c8783dbdccb31a7f923ca4dc' + + # Send a notification to the original email when the user's email is changed. + # config.send_email_changed_notification = false + + # Send a notification email when the user's password is changed. + # config.send_password_change_notification = false + + # ==> Configuration for :confirmable + # A period that the user is allowed to access the website even without + # confirming their account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming their account, + # access will be blocked just in the third day. + # You can also set it to nil, which will allow the user to access the website + # without confirming their account. + # Default is 0.days, meaning the user cannot access the website without + # confirming their account. + # config.allow_unconfirmed_access_for = 2.days + + # A period that the user is allowed to confirm their account before their + # token becomes invalid. For example, if set to 3.days, the user can confirm + # their account within 3 days after the mail was sent, but on the fourth day + # their account can't be confirmed with the token any more. + # Default is nil, meaning there is no restriction on how long a user can take + # before confirming their account. + # config.confirm_within = 3.days + + # If true, requires any email changes to be confirmed (exactly the same way as + # initial account confirmation) to be applied. Requires additional unconfirmed_email + # db field (see migrations). Until confirmed, new email is stored in + # unconfirmed_email column, and copied to email column on successful confirmation. + config.reconfirmable = true + + # Defines which key will be used when confirming an account + # config.confirmation_keys = [:email] + + # ==> Configuration for :rememberable + # The time the user will be remembered without asking for credentials again. + # config.remember_for = 2.weeks + + # Invalidates all the remember me tokens when the user signs out. + config.expire_all_remember_me_on_sign_out = true + + # If true, extends the user's remember period when remembered via cookie. + # config.extend_remember_period = false + + # Options to be passed to the created cookie. For instance, you can set + # secure: true in order to force SSL only cookies. + # config.rememberable_options = {} + + # ==> Configuration for :validatable + # Range for password length. + config.password_length = 6..128 + + # Email regex used to validate email formats. It simply asserts that + # one (and only one) @ exists in the given string. This is mainly + # to give user feedback and not to assert the e-mail validity. + config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ + + # ==> Configuration for :timeoutable + # The time you want to timeout the user session without activity. After this + # time the user will be asked for credentials again. Default is 30 minutes. + # config.timeout_in = 30.minutes + + # ==> Configuration for :lockable + # Defines which strategy will be used to lock an account. + # :failed_attempts = Locks an account after a number of failed attempts to sign in. + # :none = No lock strategy. You should handle locking by yourself. + # config.lock_strategy = :failed_attempts + + # Defines which key will be used when locking and unlocking an account + # config.unlock_keys = [:email] + + # Defines which strategy will be used to unlock an account. + # :email = Sends an unlock link to the user email + # :time = Re-enables login after a certain amount of time (see :unlock_in below) + # :both = Enables both strategies + # :none = No unlock strategy. You should handle unlocking by yourself. + # config.unlock_strategy = :both + + # Number of authentication tries before locking an account if lock_strategy + # is failed attempts. + # config.maximum_attempts = 20 + + # Time interval to unlock the account if :time is enabled as unlock_strategy. + # config.unlock_in = 1.hour + + # Warn on the last attempt before the account is locked. + # config.last_attempt_warning = true + + # ==> Configuration for :recoverable + # + # Defines which key will be used when recovering the password for an account + # config.reset_password_keys = [:email] + + # Time interval you can reset your password with a reset password key. + # Don't put a too small interval or your users won't have the time to + # change their passwords. + config.reset_password_within = 6.hours + + # When set to false, does not sign a user in automatically after their password is + # reset. Defaults to true, so a user is signed in automatically after a reset. + # config.sign_in_after_reset_password = true + + # ==> Configuration for :encryptable + # Allow you to use another hashing or encryption algorithm besides bcrypt (default). + # You can use :sha1, :sha512 or algorithms from others authentication tools as + # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 + # for default behavior) and :restful_authentication_sha1 (then you should set + # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). + # + # Require the `devise-encryptable` gem when using anything other than bcrypt + # config.encryptor = :sha512 + + # ==> Scopes configuration + # Turn scoped views on. Before rendering "sessions/new", it will first check for + # "users/sessions/new". It's turned off by default because it's slower if you + # are using only default views. + # config.scoped_views = false + + # Configure the default scope given to Warden. By default it's the first + # devise role declared in your routes (usually :user). + # config.default_scope = :user + + # Set this configuration to false if you want /users/sign_out to sign out + # only the current scope. By default, Devise signs out all scopes. + # config.sign_out_all_scopes = true + + # ==> Navigation configuration + # Lists the formats that should be treated as navigational. Formats like + # :html should redirect to the sign in page when the user does not have + # access, but formats like :xml or :json, should return 401. + # + # If you have any extra navigational formats, like :iphone or :mobile, you + # should add them to the navigational formats lists. + # + # The "*/*" below is required to match Internet Explorer requests. + # config.navigational_formats = ['*/*', :html, :turbo_stream] + + # The default HTTP method used to sign out a resource. Default is :delete. + config.sign_out_via = :delete + + # ==> OmniAuth + # Add a new OmniAuth provider. Check the wiki for more information on setting + # up on your models and hooks. + # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' + + # ==> Warden configuration + # If you want to use other strategies, that are not supported by Devise, or + # change the failure app, you can configure them inside the config.warden block. + # + # config.warden do |manager| + # manager.intercept_401 = false + # manager.default_strategies(scope: :user).unshift :some_external_strategy + # end + + # ==> Mountable engine configurations + # When using Devise inside an engine, let's call it `MyEngine`, and this engine + # is mountable, there are some extra configurations to be taken into account. + # The following options are available, assuming the engine is mounted as: + # + # mount MyEngine, at: '/my_engine' + # + # The router that invoked `devise_for`, in the example above, would be: + # config.router_name = :my_engine + # + # When using OmniAuth, Devise cannot automatically set OmniAuth path, + # so you need to do it manually. For the users scope, it would be: + # config.omniauth_path_prefix = '/my_engine/users/auth' + + # ==> Hotwire/Turbo configuration + # When using Devise with Hotwire/Turbo, the http status for error responses + # and some redirects must match the following. The default in Devise for existing + # apps is `200 OK` and `302 Found` respectively, but new apps are generated with + # these new defaults that match Hotwire/Turbo behavior. + # Note: These might become the new default in future versions of Devise. + config.responder.error_status = :unprocessable_entity + config.responder.redirect_status = :see_other + + # ==> Configuration for :registerable + + # When set to false, does not sign a user in automatically after their password is + # changed. Defaults to true, so a user is signed in automatically after changing a password. + # config.sign_in_after_change_password = true +end diff --git a/gems/kiqr/config/routes.rb b/gems/kiqr/config/routes.rb index 1daf9a4..7e79630 100644 --- a/gems/kiqr/config/routes.rb +++ b/gems/kiqr/config/routes.rb @@ -1,2 +1,7 @@ Rails.application.routes.draw do + # User authentication + devise_for :users, path_names: {sign_in: "login", sign_up: "create-account"}, controllers: { + registrations: "users/registrations", + sessions: "users/sessions" + } end diff --git a/gems/kiqr/db/migrate/20240321094123_devise_create_users.rb b/gems/kiqr/db/migrate/20240321094123_devise_create_users.rb new file mode 100644 index 0000000..959c9cc --- /dev/null +++ b/gems/kiqr/db/migrate/20240321094123_devise_create_users.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +class DeviseCreateUsers < ActiveRecord::Migration[7.1] + def change + create_table :users do |t| + ## Database authenticatable + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + + ## Trackable + t.integer :sign_in_count, default: 0, null: false + t.datetime :current_sign_in_at + t.datetime :last_sign_in_at + t.string :current_sign_in_ip + t.string :last_sign_in_ip + + ## Confirmable + t.string :confirmation_token + t.datetime :confirmed_at + t.datetime :confirmation_sent_at + t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts + t.string :unlock_token # Only if unlock strategy is :email or :both + t.datetime :locked_at + + t.timestamps null: false + end + + add_index :users, :email, unique: true + add_index :users, :reset_password_token, unique: true + add_index :users, :confirmation_token, unique: true + add_index :users, :unlock_token, unique: true + end +end diff --git a/gems/kiqr/db/migrate/20240325084418_create_accounts.rb b/gems/kiqr/db/migrate/20240325084418_create_accounts.rb new file mode 100644 index 0000000..9aa9752 --- /dev/null +++ b/gems/kiqr/db/migrate/20240325084418_create_accounts.rb @@ -0,0 +1,14 @@ +class CreateAccounts < ActiveRecord::Migration[7.1] + def change + create_table :accounts do |t| + t.string :public_uid, index: {unique: true} + t.string :name, null: false + t.boolean :personal, null: false, default: false + + t.timestamps + end + + # Add a optional personal_account reference to users. + add_reference :users, :personal_account, foreign_key: {to_table: :accounts}, null: true + end +end diff --git a/gems/kiqr/db/migrate/20240325142603_create_account_users.rb b/gems/kiqr/db/migrate/20240325142603_create_account_users.rb new file mode 100644 index 0000000..bc45c80 --- /dev/null +++ b/gems/kiqr/db/migrate/20240325142603_create_account_users.rb @@ -0,0 +1,11 @@ +class CreateAccountUsers < ActiveRecord::Migration[7.1] + def change + create_table :account_users do |t| + t.references :user, null: false, foreign_key: true + t.references :account, null: false, foreign_key: true + t.string :role, null: false, default: "owner" + + t.timestamps + end + end +end diff --git a/gems/kiqr/db/migrate/20240401110029_add_devise_two_factor_to_users.rb b/gems/kiqr/db/migrate/20240401110029_add_devise_two_factor_to_users.rb new file mode 100644 index 0000000..57bc382 --- /dev/null +++ b/gems/kiqr/db/migrate/20240401110029_add_devise_two_factor_to_users.rb @@ -0,0 +1,8 @@ +class AddDeviseTwoFactorToUsers < ActiveRecord::Migration[7.1] + def change + add_column :users, :otp_secret, :string + add_column :users, :consumed_timestep, :integer + add_column :users, :otp_required_for_login, :boolean, default: false + add_column :users, :otp_backup_codes, :text + end +end diff --git a/gems/kiqr/db/migrate/20240404092246_add_public_uid_to_account_users.rb b/gems/kiqr/db/migrate/20240404092246_add_public_uid_to_account_users.rb new file mode 100644 index 0000000..efe4ea0 --- /dev/null +++ b/gems/kiqr/db/migrate/20240404092246_add_public_uid_to_account_users.rb @@ -0,0 +1,6 @@ +class AddPublicUidToAccountUsers < ActiveRecord::Migration[7.1] + def change + add_column :account_users, :public_uid, :string + add_index :account_users, :public_uid, unique: true + end +end diff --git a/gems/kiqr/db/migrate/20240404205037_replace_role_with_owner_on_account_users.rb b/gems/kiqr/db/migrate/20240404205037_replace_role_with_owner_on_account_users.rb new file mode 100644 index 0000000..b6900d9 --- /dev/null +++ b/gems/kiqr/db/migrate/20240404205037_replace_role_with_owner_on_account_users.rb @@ -0,0 +1,6 @@ +class ReplaceRoleWithOwnerOnAccountUsers < ActiveRecord::Migration[7.1] + def change + remove_column :account_users, :role, :string, default: "owner", null: false + add_column :account_users, :owner, :boolean, default: false, null: false + end +end diff --git a/gems/kiqr/db/migrate/20240407174725_create_account_invitations.rb b/gems/kiqr/db/migrate/20240407174725_create_account_invitations.rb new file mode 100644 index 0000000..9ea256c --- /dev/null +++ b/gems/kiqr/db/migrate/20240407174725_create_account_invitations.rb @@ -0,0 +1,15 @@ +class CreateAccountInvitations < ActiveRecord::Migration[7.1] + def change + create_table :account_invitations do |t| + t.string :public_uid, index: {unique: true} + t.references :account, null: false, foreign_key: true + t.string :email, null: false + t.datetime :accepted_at + t.timestamps + end + + add_column :accounts, :account_invitations_count, :integer, default: 0 + add_index :account_invitations, :email + add_index :account_invitations, [:account_id, :email], unique: true + end +end diff --git a/gems/kiqr/db/migrate/20240408105555_add_unique_index_to_account_users.rb b/gems/kiqr/db/migrate/20240408105555_add_unique_index_to_account_users.rb new file mode 100644 index 0000000..0d7f215 --- /dev/null +++ b/gems/kiqr/db/migrate/20240408105555_add_unique_index_to_account_users.rb @@ -0,0 +1,5 @@ +class AddUniqueIndexToAccountUsers < ActiveRecord::Migration[7.1] + def change + add_index :account_users, [:account_id, :user_id], unique: true + end +end diff --git a/gems/kiqr/db/migrate/20240408210931_add_locale_and_time_zone_to_users.rb b/gems/kiqr/db/migrate/20240408210931_add_locale_and_time_zone_to_users.rb new file mode 100644 index 0000000..665ba9a --- /dev/null +++ b/gems/kiqr/db/migrate/20240408210931_add_locale_and_time_zone_to_users.rb @@ -0,0 +1,6 @@ +class AddLocaleAndTimeZoneToUsers < ActiveRecord::Migration[7.1] + def change + add_column :users, :locale, :string, default: "en" + add_column :users, :time_zone, :string, default: "UTC" + end +end diff --git a/gems/kiqr/kiqr.gemspec b/gems/kiqr/kiqr.gemspec index e13453f..df362c8 100644 --- a/gems/kiqr/kiqr.gemspec +++ b/gems/kiqr/kiqr.gemspec @@ -18,4 +18,7 @@ Gem::Specification.new do |spec| end spec.add_dependency "rails", ">= 7.1.3.2" + spec.add_dependency "devise", "~> 4.9", ">= 4.9.3" + spec.add_dependency "devise-two-factor", "~> 5.0.0" + spec.add_dependency "public_uid", "~> 2.2" end diff --git a/gems/kiqr/lib/kiqr.rb b/gems/kiqr/lib/kiqr.rb index 6616eec..1c6e9cf 100644 --- a/gems/kiqr/lib/kiqr.rb +++ b/gems/kiqr/lib/kiqr.rb @@ -1,10 +1,21 @@ -require "kiqr/version" require "kiqr/engine" +require "kiqr/version" + +require "devise" +require "devise-two-factor" +require "public_uid" module Kiqr + autoload :ApplicationService, "kiqr/application_service" autoload :Config, "kiqr/config" - def config + module Services + module Accounts + autoload :Create, "kiqr/services/accounts/create" + end + end + + def self.config @config ||= Kiqr::Config end end diff --git a/gems/kiqr/lib/kiqr/application_service.rb b/gems/kiqr/lib/kiqr/application_service.rb new file mode 100644 index 0000000..8b8ec0d --- /dev/null +++ b/gems/kiqr/lib/kiqr/application_service.rb @@ -0,0 +1,35 @@ +module Kiqr + class ApplicationService + Response = Struct.new(:success?, :payload, :error) do + def failure? + !success? + end + end + + def initialize(propagate = true) + @propagate = propagate + end + + def self.call(...) + service = new(false) + service.call(...) + rescue => e + service.failure(e) + end + + def self.call!(...) + new(true).call(...) + end + + def success(payload = nil) + Response.new(true, payload) + end + + def failure(exception, options = {}) + raise exception if @propagate + + # ErrorService.error(exception, options) + Response.new(false, nil, exception) + end + end +end diff --git a/gems/kiqr/lib/kiqr/services/accounts/create.rb b/gems/kiqr/lib/kiqr/services/accounts/create.rb new file mode 100644 index 0000000..07a0827 --- /dev/null +++ b/gems/kiqr/lib/kiqr/services/accounts/create.rb @@ -0,0 +1,38 @@ +module Kiqr + module Services + module Accounts + class Create < Kiqr::ApplicationService + def call(account:, user:, personal: false) + @account, @user = account, user + + personal ? create_personal_account : create_team_account + + success account + end + + private + + def create_personal_account + raise StandardError, "User already has a personal account" if user.personal_account.present? + + user.transaction do + account.personal = true + user.personal_account = account + user.save! + end + end + + def create_team_account + account.transaction do + account.account_users.new(user: user, owner: true) + account.save! + end + end + + private + + attr_reader :account, :user + end + end + end +end diff --git a/test/kiqr/config_test.rb b/gems/kiqr/test/config_test.rb similarity index 63% rename from test/kiqr/config_test.rb rename to gems/kiqr/test/config_test.rb index dfa6524..6a9d3a7 100644 --- a/test/kiqr/config_test.rb +++ b/gems/kiqr/test/config_test.rb @@ -2,9 +2,16 @@ module Kiqr class ConfigTest < ActiveSupport::TestCase - test "it can set and read config values" do + def setup Kiqr::Config.app_name = "Foobar" + end + + test "it can set and read config values" do assert Kiqr::Config.app_name == "Foobar" end + + test "config can be accessed via Kiqr.config" do + assert Kiqr.config.app_name == "Foobar" + end end end diff --git a/gems/kiqr/test/dummy/db/schema.rb b/gems/kiqr/test/dummy/db/schema.rb new file mode 100644 index 0000000..917447c --- /dev/null +++ b/gems/kiqr/test/dummy/db/schema.rb @@ -0,0 +1,88 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[7.1].define(version: 2024_04_08_210931) do + create_table "account_invitations", force: :cascade do |t| + t.string "public_uid" + t.integer "account_id", null: false + t.string "email", null: false + t.datetime "accepted_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["account_id", "email"], name: "index_account_invitations_on_account_id_and_email", unique: true + t.index ["account_id"], name: "index_account_invitations_on_account_id" + t.index ["email"], name: "index_account_invitations_on_email" + t.index ["public_uid"], name: "index_account_invitations_on_public_uid", unique: true + end + + create_table "account_users", force: :cascade do |t| + t.integer "user_id", null: false + t.integer "account_id", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.string "public_uid" + t.boolean "owner", default: false, null: false + t.index ["account_id", "user_id"], name: "index_account_users_on_account_id_and_user_id", unique: true + t.index ["account_id"], name: "index_account_users_on_account_id" + t.index ["public_uid"], name: "index_account_users_on_public_uid", unique: true + t.index ["user_id"], name: "index_account_users_on_user_id" + end + + create_table "accounts", force: :cascade do |t| + t.string "public_uid" + t.string "name", null: false + t.boolean "personal", default: false, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.integer "account_invitations_count", default: 0 + t.index ["public_uid"], name: "index_accounts_on_public_uid", unique: true + end + + create_table "users", force: :cascade do |t| + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.integer "sign_in_count", default: 0, null: false + t.datetime "current_sign_in_at" + t.datetime "last_sign_in_at" + t.string "current_sign_in_ip" + t.string "last_sign_in_ip" + t.string "confirmation_token" + t.datetime "confirmed_at" + t.datetime "confirmation_sent_at" + t.string "unconfirmed_email" + t.integer "failed_attempts", default: 0, null: false + t.string "unlock_token" + t.datetime "locked_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.integer "personal_account_id" + t.string "otp_secret" + t.integer "consumed_timestep" + t.boolean "otp_required_for_login", default: false + t.text "otp_backup_codes" + t.string "locale", default: "en" + t.string "time_zone", default: "UTC" + t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true + t.index ["email"], name: "index_users_on_email", unique: true + t.index ["personal_account_id"], name: "index_users_on_personal_account_id" + t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true + t.index ["unlock_token"], name: "index_users_on_unlock_token", unique: true + end + + add_foreign_key "account_invitations", "accounts" + add_foreign_key "account_users", "accounts" + add_foreign_key "account_users", "users" + add_foreign_key "users", "accounts", column: "personal_account_id" +end diff --git a/gems/kiqr/test/factories/accounts.rb b/gems/kiqr/test/factories/accounts.rb new file mode 100644 index 0000000..551c7ef --- /dev/null +++ b/gems/kiqr/test/factories/accounts.rb @@ -0,0 +1,6 @@ +FactoryBot.define do + factory :account do + sequence(:name) { |n| "Account #{n}" } + personal { false } + end +end diff --git a/gems/kiqr/test/factories/user.rb b/gems/kiqr/test/factories/user.rb new file mode 100644 index 0000000..1758a64 --- /dev/null +++ b/gems/kiqr/test/factories/user.rb @@ -0,0 +1,18 @@ +FactoryBot.define do + factory :user do + sequence(:email) { |n| "generic-user-#{n}@example.com" } + password { "th1s1sp4ssw0rd" } + password_confirmation { "th1s1sp4ssw0rd" } + confirmed_at { Time.zone.now } + personal_account { build(:account, personal: true) } + + # trait :unconfirmed do + # confirmed_at { nil } + # end + + # trait :otp_enabled do + # otp_required_for_login { true } + # otp_secret { User.generate_otp_secret } + # end + end +end diff --git a/gems/kiqr/test/services/accounts/create_test.rb b/gems/kiqr/test/services/accounts/create_test.rb new file mode 100644 index 0000000..eb6bd3c --- /dev/null +++ b/gems/kiqr/test/services/accounts/create_test.rb @@ -0,0 +1,48 @@ +require "test_helper" + +module Kiqr + module Services + module Accounts + class CreateTest < ActionDispatch::IntegrationTest + def setup + @service = Kiqr::Services::Accounts::Create.new + end + + test "creates team account" do + user = create(:user) + account = build(:account) + + @service.call(account:, user:, personal: false) + refute_empty account.account_users, "Expected account_users not to be empty" + assert account.account_users.find_by(user: user).owner, "Expected account_users to have owner set to true" + refute account.personal, "Expected account.personal to be false" + assert account.persisted?, "Expected account to be saved" + end + + test "creates personal account" do + user = create(:user, personal_account: nil) + account = build(:account) + + @service.call(account:, user:, personal: true) + assert_empty account.account_users, "Expected account_users to be empty" + assert account.personal, "Expected account.personal to be true" + assert_equal account, user.personal_account, "Expected user to have personal account" + end + + test "can only have one personal account" do + user = create(:user) + assert_raises(StandardError) do + @service.call(account: Account.new(name: "Jane Doe"), user:, personal: true) + end + end + + test "account with invalid attributes raises error" do + user = create(:user) + assert_raises(StandardError) do + @service.call(account: build(:account, name: "no"), user:, personal: false) + end + end + end + end + end +end diff --git a/gems/kiqr/test/test_helper.rb b/gems/kiqr/test/test_helper.rb index 9f2c11d..98c945a 100644 --- a/gems/kiqr/test/test_helper.rb +++ b/gems/kiqr/test/test_helper.rb @@ -1,14 +1,29 @@ # Configure Rails Environment ENV["RAILS_ENV"] = "test" +require "simplecov" +SimpleCov.start "rails" do + add_filter %r{^/test/} + add_filter "lib/kiqr/version.rb" +end + require_relative "../test/dummy/config/environment" -ActiveRecord::Migrator.migrations_paths = [File.expand_path("../test/dummy/db/migrate", __dir__)] +ActiveRecord::Migrator.migrations_paths = [File.expand_path("../db/migrate", __dir__)] require "rails/test_help" -# Load fixtures from the engine -if ActiveSupport::TestCase.respond_to?(:fixture_paths=) - ActiveSupport::TestCase.fixture_paths = [File.expand_path("fixtures", __dir__)] - ActionDispatch::IntegrationTest.fixture_paths = ActiveSupport::TestCase.fixture_paths - ActiveSupport::TestCase.file_fixture_path = File.expand_path("fixtures", __dir__) + "/files" - ActiveSupport::TestCase.fixtures :all +FactoryBot.find_definitions + +module ActiveSupport + class TestCase + # include Devise::Test::IntegrationHelpers + include FactoryBot::Syntax::Methods + + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... + end end