ibrain-auth 0.1.1 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6381e8988dfab56252a71fddac56b968fc2b8d937ebaa91630318abfad057f09
4
- data.tar.gz: 60ec5dbee69620b48ddcfd798295c4df24dacd2646708668e8706c9679ad131c
3
+ metadata.gz: 30ccc8647d90b04b385f7bb63e24dbdecb1365d6c3db4a4bb187a19b7ab476c3
4
+ data.tar.gz: 25265497ddf2b02cb26b23c1d509749a54947356cb37a7c2179f1cf68efa5639
5
5
  SHA512:
6
- metadata.gz: 4e86995cfe7f5d2cb7d1fc16b9b97ec835a04f76456e3be50c9b59e3ce941d61e5fbfcd944d259308d21067336b13a8a77c1654705405b304cb95108e0d801a8
7
- data.tar.gz: 6713e1db2298017118515f435e02c4ffc369675a80e82b77a05f6f921a05b89d6f7104f060bb02b44f06bfb87f5e3450e470e19309c3bba501d0923f4a6efd08
6
+ metadata.gz: 9df833ba495a2139dd9b23f6012ca73ff040e2b4cfcaf7f03efa0dd3be78310bacb1c9e6d88800762c39c053c905bbc9ad4095a3622d8497f2bc867c114b1dc6
7
+ data.tar.gz: ca80d2bb38a7a63247cda64558876af54869a100025261b36eafc8ab93f9888971935fca14400aede6fc9ae8a649bedf6bdf994838ec267c22ca2fde415fd24a
@@ -0,0 +1,203 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ibrain::Auth::Mutations
4
+ class BaseMutation < Ibrain::Mutations::BaseMutation
5
+ include ActionController::Helpers
6
+ include Devise::Controllers::ScopedViews
7
+ include Devise::Controllers::Helpers
8
+
9
+ helpers = %w(resource scope_name resource_name signed_in_resource
10
+ resource_class resource_params devise_mapping)
11
+
12
+ helper_method(*helpers)
13
+
14
+ # Override prefixes to consider the scoped view.
15
+ # Notice we need to check for the request due to a bug in
16
+ # Action Controller tests that forces _prefixes to be
17
+ # loaded before even having a request object.
18
+ #
19
+ # This method should be public as it is in ActionPack
20
+ # itself. Changing its visibility may break other gems.
21
+ def _prefixes # :nodoc:
22
+ @_prefixes ||= if self.class.scoped_views? && request && devise_mapping
23
+ ["#{devise_mapping.scoped_path}/#{controller_name}"] + super
24
+ else
25
+ super
26
+ end
27
+ end
28
+
29
+ protected
30
+
31
+ def auth_headers(headers, user, scope: nil, aud: nil)
32
+ scope ||= Devise::Mapping.find_scope!(user)
33
+ aud ||= headers[Warden::JWTAuth.config.aud_header]
34
+
35
+ token, payload = Warden::JWTAuth::UserEncoder.new.call(
36
+ user, scope, aud
37
+ )
38
+
39
+ [token, payload.try(:fetch, 'jti')]
40
+ rescue StandardError => e
41
+ Ibrain::Logger.error(e.message)
42
+
43
+ []
44
+ end
45
+
46
+ # Gets the actual resource stored in the instance variable
47
+ def resource
48
+ instance_variable_get(:"@#{resource_name}")
49
+ end
50
+
51
+ # Proxy to devise map name
52
+ def resource_name
53
+ devise_mapping.name
54
+ end
55
+ alias :scope_name :resource_name
56
+
57
+ # Proxy to devise map class
58
+ def resource_class
59
+ devise_mapping.to
60
+ end
61
+
62
+ # Returns a signed in resource from session (if one exists)
63
+ def signed_in_resource
64
+ warden.authenticate(scope: resource_name)
65
+ end
66
+
67
+ # Attempt to find the mapped route for devise based on request path
68
+ def devise_mapping
69
+ @devise_mapping ||= request.env["devise.mapping"]
70
+ end
71
+
72
+ # Returns real navigational formats which are supported by Rails
73
+ def navigational_formats
74
+ @navigational_formats ||= Devise.navigational_formats.select { |format| Mime::EXTENSION_LOOKUP[format.to_s] }
75
+ end
76
+
77
+ def unknown_action!(msg)
78
+ logger&.debug "[Devise] #{msg}"
79
+ raise AbstractController::ActionNotFound, msg
80
+ end
81
+
82
+ # Sets the resource creating an instance variable
83
+ def resource=(new_resource)
84
+ instance_variable_set(:"@#{resource_name}", new_resource)
85
+ end
86
+
87
+ # Helper for use in before_actions where no authentication is required.
88
+ #
89
+ # Example:
90
+ # before_action :require_no_authentication, only: :new
91
+ def require_no_authentication
92
+ assert_is_devise_resource!
93
+ return unless is_navigational_format?
94
+
95
+ no_input = devise_mapping.no_input_strategies
96
+
97
+ authenticated = if no_input.present?
98
+ args = no_input.dup.push scope: resource_name
99
+ warden.authenticate?(*args)
100
+ else
101
+ warden.authenticated?(resource_name)
102
+ end
103
+
104
+ if authenticated && resource = warden.user(resource_name)
105
+ set_flash_message(:alert, 'already_authenticated', scope: 'devise.failure')
106
+ redirect_to after_sign_in_path_for(resource)
107
+ end
108
+ end
109
+
110
+ # Helper for use after calling send_*_instructions methods on a resource.
111
+ # If we are in paranoid mode, we always act as if the resource was valid
112
+ # and instructions were sent.
113
+ def successfully_sent?(resource)
114
+ notice = if Devise.paranoid
115
+ resource.errors.clear
116
+ :send_paranoid_instructions
117
+ elsif resource.errors.empty?
118
+ :send_instructions
119
+ end
120
+
121
+ if notice
122
+ set_flash_message! :notice, notice
123
+ true
124
+ end
125
+ end
126
+
127
+ # Sets the flash message with :key, using I18n. By default you are able
128
+ # to set up your messages using specific resource scope, and if no message is
129
+ # found we look to the default scope. Set the "now" options key to a true
130
+ # value to populate the flash.now hash in lieu of the default flash hash (so
131
+ # the flash message will be available to the current action instead of the
132
+ # next action).
133
+ # Example (i18n locale file):
134
+ #
135
+ # en:
136
+ # devise:
137
+ # passwords:
138
+ # #default_scope_messages - only if resource_scope is not found
139
+ # user:
140
+ # #resource_scope_messages
141
+ #
142
+ # Please refer to README or en.yml locale file to check what messages are
143
+ # available.
144
+ def set_flash_message(key, kind, options = {})
145
+ message = find_message(kind, options)
146
+ if options[:now]
147
+ flash.now[key] = message if message.present?
148
+ elsif message.present?
149
+ flash[key] = message
150
+ end
151
+ end
152
+
153
+ # Sets flash message if is_flashing_format? equals true
154
+ def set_flash_message!(key, kind, options = {})
155
+ if is_flashing_format?
156
+ set_flash_message(key, kind, options)
157
+ end
158
+ end
159
+
160
+ # Sets minimum password length to show to user
161
+ def set_minimum_password_length
162
+ if devise_mapping.validatable?
163
+ @minimum_password_length = resource_class.password_length.min
164
+ end
165
+ end
166
+
167
+ def devise_i18n_options(options)
168
+ options
169
+ end
170
+
171
+ # Get message for given
172
+ def find_message(kind, options = {})
173
+ options[:scope] ||= translation_scope
174
+ options[:default] = Array(options[:default]).unshift(kind.to_sym)
175
+ options[:resource_name] = resource_name
176
+ options = devise_i18n_options(options)
177
+ I18n.t("#{options[:resource_name]}.#{kind}", **options)
178
+ end
179
+
180
+ # Controllers inheriting DeviseController are advised to override this
181
+ # method so that other controllers inheriting from them would use
182
+ # existing translations.
183
+ def translation_scope
184
+ "devise.#{controller_name}"
185
+ end
186
+
187
+ def clean_up_passwords(object)
188
+ object.clean_up_passwords if object.respond_to?(:clean_up_passwords)
189
+ end
190
+
191
+ def respond_with_navigational(*args, &block)
192
+ respond_with(*args) do |format|
193
+ format.any(*navigational_formats, &block)
194
+ end
195
+ end
196
+
197
+ def resource_params
198
+ params.fetch(resource_name, {})
199
+ end
200
+
201
+ ActiveSupport.run_load_hooks(:devise_controller, self)
202
+ end
203
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ibrain::Auth::Mutations
4
+ class SignInMutation < BaseMutation
5
+ field :user, Types::Objects::UserType, null: true
6
+ field :token, String, null: true
7
+ field :result, Boolean, null: true
8
+
9
+ argument :username, String, description: 'Username', required: true
10
+ argument :password, String, description: 'Password', required: true
11
+
12
+ def resolve(args)
13
+ # TODO: define logic inside repository
14
+ repo = ::AuthRepository.new(nil, normalize_params(args))
15
+ user = repo.sign_in
16
+
17
+ raise ActionController::InvalidAuthenticityToken, I18n.t('ibrain.errors.account.incorrect') if user.blank?
18
+
19
+ sign_in(resource_name, user)
20
+ @current_user = warden.authenticate!(auth_options)
21
+
22
+ warden.set_user(current_user)
23
+ current_user.jwt_token, jti = auth_headers(request, user)
24
+
25
+ current_user.jti = jti
26
+ current_user.save!
27
+
28
+ context[:current_user] = current_user
29
+
30
+ OpenStruct.new(
31
+ user: user_signed_in? ? current_user : nil,
32
+ token: current_user.try(:jwt_token),
33
+ result: user_signed_in?
34
+ )
35
+ end
36
+
37
+ private
38
+
39
+ def normalize_params(args)
40
+ ActionController::Parameters.new({ auth: args })
41
+ end
42
+
43
+ def auth_options
44
+ { scope: resource_name }
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ibrain::Auth::Mutations
4
+ class SignOutMutation < BaseMutation
5
+ field :result, Boolean, null: true
6
+
7
+ def resolve
8
+ current_user.jti = nil
9
+ sign_out if current_user.save
10
+
11
+ OpenStruct.new(result: !user_signed_in?)
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ibrain::Auth::Mutations
4
+ class SignInMutation < BaseMutation
5
+ field :user, Types::Objects::UserType, null: true
6
+ field :token, String, null: true
7
+ field :result, Boolean, null: true
8
+
9
+ argument :id_token, String, description: 'Id Token from SSO', required: true
10
+
11
+ def resolve(args)
12
+ # TODO: define logic inside repository
13
+ repo = ::AuthRepository.new(nil, normalize_params(args))
14
+ user = repo.sign_in
15
+
16
+ raise ActionController::InvalidAuthenticityToken, I18n.t('ibrain.errors.account.incorrect') if user.blank?
17
+
18
+ sign_in(resource_name, user)
19
+ @current_user = warden.authenticate!(auth_options)
20
+
21
+ warden.set_user(current_user)
22
+ current_user.jwt_token, jti = auth_headers(request, user)
23
+
24
+ current_user.jti = jti
25
+ current_user.save!
26
+
27
+ context[:current_user] = current_user
28
+
29
+ OpenStruct.new(
30
+ user: user_signed_in? ? current_user : nil,
31
+ token: current_user.try(:jwt_token),
32
+ result: user_signed_in?
33
+ )
34
+ end
35
+
36
+ private
37
+
38
+ def normalize_params(args)
39
+ ActionController::Parameters.new({ auth: args })
40
+ end
41
+
42
+ def auth_options
43
+ { scope: resource_name }
44
+ end
45
+ end
46
+ end
@@ -3,24 +3,44 @@
3
3
  module Ibrain
4
4
  module Auth
5
5
  class User < Ibrain::Base
6
- self.table_name = Ibrain::Auth::Config.user_table_name
7
-
8
6
  include Devise::JWT::RevocationStrategies::JTIMatcher
9
7
 
8
+ attr_accessor :jwt_token
9
+
10
+ self.table_name = Ibrain::Auth::Config.user_table_name
11
+
10
12
  devise :database_authenticatable, :registerable,
11
- :recoverable, :validatable,
13
+ :recoverable, :validatable, :timeoutable,
12
14
  :jwt_authenticatable, jwt_revocation_strategy: self
13
15
 
14
16
  def jwt_payload
15
17
  # for hasura
16
- hasura_keys = { 'https://hasura.io/jwt/claims': {
17
- 'x-hasura-allowed-roles': [role],
18
- 'x-hasura-default-role': role,
19
- 'x-hasura-user-id': id.to_s
20
- } }
18
+ hasura_keys = {
19
+ 'https://hasura.io/jwt/claims': {
20
+ 'x-hasura-allowed-roles': [role],
21
+ 'x-hasura-default-role': role,
22
+ 'x-hasura-user-id': id.to_s
23
+ }
24
+ }
21
25
 
22
26
  super.merge({ 'role' => role }, hasura_keys)
23
27
  end
28
+
29
+ class << self
30
+ def ibrain_find(params, available_columns)
31
+ matched_value = params[:username] || params[:email]
32
+
33
+ if matched_value.present?
34
+ query = available_columns.map do |column_name|
35
+ <<~RUBY
36
+ #{column_name} = '#{matched_value}'
37
+ RUBY
38
+ end.join(' OR ')
39
+
40
+ where(query).first
41
+ end
42
+ end
43
+ end
24
44
  end
25
45
  end
26
46
  end
@@ -7,21 +7,11 @@ class AuthRepository < Ibrain::BaseRepository
7
7
  super(nil, record)
8
8
 
9
9
  @params = params
10
+ @collection = Ibrain.user_class
10
11
  end
11
12
 
12
13
  def create
13
- user = sso_verify if normalize_params[:id_token].present?
14
-
15
- if manual_params[:username].present?
16
- query = available_columns.map do |column_name|
17
- <<~RUBY
18
- #{column_name} = '#{manual_params[:username]}'
19
- RUBY
20
- end.join('OR')
21
-
22
- user = Ibrain.user_class.where(query).first
23
- end
24
-
14
+ user = is_sso? ? sso_verify : collection.ibrain_find(manual_params, available_columns)
25
15
  user.assign_attributes(normalize_params)
26
16
  user.save
27
17
 
@@ -29,13 +19,7 @@ class AuthRepository < Ibrain::BaseRepository
29
19
  end
30
20
 
31
21
  def sign_in
32
- return sso_verify if normalize_params[:id_token].present?
33
-
34
- user = Ibrain.user_class.where(
35
- 'username = ? or email = ?',
36
- manual_params[:username],
37
- manual_params[:username]
38
- ).first
22
+ user = is_sso? ? sso_verify : collection.ibrain_find(manual_params, available_columns)
39
23
 
40
24
  return unless user.try(:valid_password?, manual_params[:password])
41
25
 
@@ -44,7 +28,7 @@ class AuthRepository < Ibrain::BaseRepository
44
28
 
45
29
  private
46
30
 
47
- attr_reader :params
31
+ attr_reader :params, :collection
48
32
 
49
33
  def firebase_url
50
34
  "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=#{firebase_api_key}"
@@ -78,10 +62,14 @@ class AuthRepository < Ibrain::BaseRepository
78
62
 
79
63
  raise ActiveRecord::NotFound, I18n.t('ibrain.errors.account.not_found') if uid.blank?
80
64
 
81
- Ibrain.user_class.find_by(uid: uid)
65
+ collection.find_by(uid: uid)
82
66
  end
83
67
 
84
68
  def available_columns
85
- Ibrain.user_class.column_names.select { |f| ACCOUNT_COUMNS.include?(f) }
69
+ collection.column_names.select { |f| ACCOUNT_COUMNS.include?(f) }
70
+ end
71
+
72
+ def is_sso?
73
+ normalize_params[:id_token].present?
86
74
  end
87
75
  end
@@ -14,7 +14,7 @@ Devise.setup do |config|
14
14
  # confirmation, reset password and unlock tokens in the database.
15
15
  # Devise will use the `secret_key_base` as its `secret_key`
16
16
  # by default. You can change it below and use your own secret key.
17
- # config.secret_key = '05f081e028de57b374973bd38d8cfb4782d886f6919a45983bc77299e7b1900cdd93c80adf332e462d17dad92eeb4fb78ddb4a4bf6c64833786e0c2582fb5470'
17
+ config.secret_key = SecureRandom.hex(50).inspect
18
18
 
19
19
  # ==> Controller configuration
20
20
  # Configure the parent class to the devise controllers.
@@ -308,10 +308,4 @@ Devise.setup do |config|
308
308
  # When set to false, does not sign a user in automatically after their password is
309
309
  # changed. Defaults to true, so a user is signed in automatically after changing a password.
310
310
  # config.sign_in_after_change_password = true
311
-
312
- # ==> Configuration for jwt
313
- config.jwt do |jwt|
314
- jwt.secret = Ibrain::Auth::Config.jwt_secret_key # Rails.application.credentials.secret_key_base
315
- jwt.expiration_time = 3600 * 24 * 30 # 30day
316
- end
317
311
  end
@@ -9,4 +9,5 @@ en:
9
9
  invalid_session: Invalid login session. Please try again!
10
10
  expired_session: The login session has expired.
11
11
  account:
12
- not_found: Account not found
12
+ not_found: Account not found
13
+ incorrect: Username or Password is incorrect!
@@ -9,4 +9,5 @@ jp:
9
9
  invalid_session: 無効なログインセッション。 もう一度やり直してください!
10
10
  expired_session: ログインセッションが期限切れになりました。
11
11
  account:
12
- not_found: アカウントが見つかりません
12
+ not_found: アカウントが見つかりません
13
+ incorrect: ユーザー名またはパスワードが正しくありません!
@@ -9,4 +9,5 @@ vi:
9
9
  invalid_session: Phiên đăng nhập không hợp lệ. Vui lòng thử lại!
10
10
  expired_session: Phiên đăng nhập đã hết hạn.
11
11
  account:
12
- not_found: Không tìm thấy tài khoản
12
+ not_found: Không tìm thấy tài khoản
13
+ incorrect: Tài khoản hoặc mật khẩu không chính xác!
@@ -16,6 +16,7 @@ module Ibrain
16
16
  def add_files
17
17
  template 'config/initializers/devise.rb.tt', 'config/initializers/devise.rb', { skip: true }
18
18
  template 'config/initializers/ibrain_auth.rb.tt', 'config/initializers/ibrain_auth.rb', { skip: true }
19
+ template 'config/initializers/ibrain_jwt.rb.tt', 'config/initializers/ibrain_jwt.rb', { skip: true }
19
20
 
20
21
  if options[:with_ridgepole]
21
22
  template 'db/schemas/users_schema.erb', 'db/schemas/users.schema', { skip: true }
@@ -1,5 +1,311 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'devise'
3
+ # Assuming you have not yet modified this file, each configuration option below
4
+ # is set to its default value. Note that some are commented out while others
5
+ # are not: uncommented lines are intended to protect your configuration from
6
+ # breaking changes in upgrades (i.e., in the event that future versions of
7
+ # Devise change the default values for those options).
8
+ #
9
+ # Use this hook to configure devise mailer, warden hooks and so forth.
10
+ # Many of these configuration options can be set straight in your model.
11
+ Devise.setup do |config|
12
+ # The secret key used by Devise. Devise uses this key to generate
13
+ # random tokens. Changing this key will render invalid all existing
14
+ # confirmation, reset password and unlock tokens in the database.
15
+ # Devise will use the `secret_key_base` as its `secret_key`
16
+ # by default. You can change it below and use your own secret key.
17
+ # config.secret_key = SecureRandom.hex(50).inspect
4
18
 
5
- Devise.secret_key = SecureRandom.hex(50).inspect
19
+ # ==> Controller configuration
20
+ # Configure the parent class to the devise controllers.
21
+ # config.parent_controller = 'DeviseController'
22
+
23
+ # ==> Mailer Configuration
24
+ # Configure the e-mail address which will be shown in Devise::Mailer,
25
+ # note that it will be overwritten if you use your own mailer class
26
+ # with default "from" parameter.
27
+ config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
28
+
29
+ # Configure the class responsible to send e-mails.
30
+ # config.mailer = 'Devise::Mailer'
31
+
32
+ # Configure the parent class responsible to send e-mails.
33
+ # config.parent_mailer = 'ActionMailer::Base'
34
+
35
+ # ==> ORM configuration
36
+ # Load and configure the ORM. Supports :active_record (default) and
37
+ # :mongoid (bson_ext recommended) by default. Other ORMs may be
38
+ # available as additional gems.
39
+ require 'devise/orm/active_record'
40
+
41
+ # ==> Configuration for any authentication mechanism
42
+ # Configure which keys are used when authenticating a user. The default is
43
+ # just :email. You can configure it to use [:username, :subdomain], so for
44
+ # authenticating a user, both parameters are required. Remember that those
45
+ # parameters are used only when authenticating and not when retrieving from
46
+ # session. If you need permissions, you should implement that in a before filter.
47
+ # You can also supply a hash where the value is a boolean determining whether
48
+ # or not authentication should be aborted when the value is not present.
49
+ config.authentication_keys = [:username, :email]
50
+
51
+ # Configure parameters from the request object used for authentication. Each entry
52
+ # given should be a request method and it will automatically be passed to the
53
+ # find_for_authentication method and considered in your model lookup. For instance,
54
+ # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
55
+ # The same considerations mentioned for authentication_keys also apply to request_keys.
56
+ # config.request_keys = []
57
+
58
+ # Configure which authentication keys should be case-insensitive.
59
+ # These keys will be downcased upon creating or modifying a user and when used
60
+ # to authenticate or find a user. Default is :username.
61
+ config.case_insensitive_keys = [:username, :email]
62
+
63
+ # Configure which authentication keys should have whitespace stripped.
64
+ # These keys will have whitespace before and after removed upon creating or
65
+ # modifying a user and when used to authenticate or find a user. Default is :username.
66
+ config.strip_whitespace_keys = [:username, :email]
67
+
68
+ # Tell if authentication through request.params is enabled. True by default.
69
+ # It can be set to an array that will enable params authentication only for the
70
+ # given strategies, for example, `config.params_authenticatable = [:database]` will
71
+ # enable it only for database (email + password) authentication.
72
+ # config.params_authenticatable = true
73
+
74
+ # Tell if authentication through HTTP Auth is enabled. False by default.
75
+ # It can be set to an array that will enable http authentication only for the
76
+ # given strategies, for example, `config.http_authenticatable = [:database]` will
77
+ # enable it only for database authentication.
78
+ # For API-only applications to support authentication "out-of-the-box", you will likely want to
79
+ # enable this with :database unless you are using a custom strategy.
80
+ # The supported strategies are:
81
+ # :database = Support basic authentication with authentication key + password
82
+ # config.http_authenticatable = false
83
+
84
+ # If 401 status code should be returned for AJAX requests. True by default.
85
+ # config.http_authenticatable_on_xhr = true
86
+
87
+ # The realm used in Http Basic Authentication. 'Application' by default.
88
+ # config.http_authentication_realm = 'Application'
89
+
90
+ # It will change confirmation, password recovery and other workflows
91
+ # to behave the same regardless if the e-mail provided was right or wrong.
92
+ # Does not affect registerable.
93
+ # config.paranoid = true
94
+
95
+ # By default Devise will store the user in session. You can skip storage for
96
+ # particular strategies by setting this option.
97
+ # Notice that if you are skipping storage for all authentication paths, you
98
+ # may want to disable generating routes to Devise's sessions controller by
99
+ # passing skip: :sessions to `devise_for` in your config/routes.rb
100
+ config.skip_session_storage = [:http_auth]
101
+
102
+ # By default, Devise cleans up the CSRF token on authentication to
103
+ # avoid CSRF token fixation attacks. This means that, when using AJAX
104
+ # requests for sign in and sign up, you need to get a new CSRF token
105
+ # from the server. You can disable this option at your own risk.
106
+ # config.clean_up_csrf_token_on_authentication = true
107
+
108
+ # When false, Devise will not attempt to reload routes on eager load.
109
+ # This can reduce the time taken to boot the app but if your application
110
+ # requires the Devise mappings to be loaded during boot time the application
111
+ # won't boot properly.
112
+ # config.reload_routes = true
113
+
114
+ # ==> Configuration for :database_authenticatable
115
+ # For bcrypt, this is the cost for hashing the password and defaults to 12. If
116
+ # using other algorithms, it sets how many times you want the password to be hashed.
117
+ # The number of stretches used for generating the hashed password are stored
118
+ # with the hashed password. This allows you to change the stretches without
119
+ # invalidating existing passwords.
120
+ #
121
+ # Limiting the stretches to just one in testing will increase the performance of
122
+ # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
123
+ # a value less than 10 in other environments. Note that, for bcrypt (the default
124
+ # algorithm), the cost increases exponentially with the number of stretches (e.g.
125
+ # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
126
+ config.stretches = Rails.env.test? ? 1 : 12
127
+
128
+ # Set up a pepper to generate the hashed password.
129
+ # config.pepper = '3df46a10f22a3580f28b33634134bfbfe9c62f8fb9dc18c8d310d174f7699b939e6fa64761c45674580487804f1f514d0d9b11538d3fc90a1c514e21dd4f1ce1'
130
+
131
+ # Send a notification to the original email when the user's email is changed.
132
+ # config.send_email_changed_notification = false
133
+
134
+ # Send a notification email when the user's password is changed.
135
+ # config.send_password_change_notification = false
136
+
137
+ # ==> Configuration for :confirmable
138
+ # A period that the user is allowed to access the website even without
139
+ # confirming their account. For instance, if set to 2.days, the user will be
140
+ # able to access the website for two days without confirming their account,
141
+ # access will be blocked just in the third day.
142
+ # You can also set it to nil, which will allow the user to access the website
143
+ # without confirming their account.
144
+ # Default is 0.days, meaning the user cannot access the website without
145
+ # confirming their account.
146
+ # config.allow_unconfirmed_access_for = 2.days
147
+
148
+ # A period that the user is allowed to confirm their account before their
149
+ # token becomes invalid. For example, if set to 3.days, the user can confirm
150
+ # their account within 3 days after the mail was sent, but on the fourth day
151
+ # their account can't be confirmed with the token any more.
152
+ # Default is nil, meaning there is no restriction on how long a user can take
153
+ # before confirming their account.
154
+ # config.confirm_within = 3.days
155
+
156
+ # If true, requires any email changes to be confirmed (exactly the same way as
157
+ # initial account confirmation) to be applied. Requires additional unconfirmed_email
158
+ # db field (see migrations). Until confirmed, new email is stored in
159
+ # unconfirmed_email column, and copied to email column on successful confirmation.
160
+ config.reconfirmable = true
161
+
162
+ # Defines which key will be used when confirming an account
163
+ # config.confirmation_keys = [:email]
164
+
165
+ # ==> Configuration for :rememberable
166
+ # The time the user will be remembered without asking for credentials again.
167
+ # config.remember_for = 2.weeks
168
+
169
+ # Invalidates all the remember me tokens when the user signs out.
170
+ config.expire_all_remember_me_on_sign_out = true
171
+
172
+ # If true, extends the user's remember period when remembered via cookie.
173
+ # config.extend_remember_period = false
174
+
175
+ # Options to be passed to the created cookie. For instance, you can set
176
+ # secure: true in order to force SSL only cookies.
177
+ # config.rememberable_options = {}
178
+
179
+ # ==> Configuration for :validatable
180
+ # Range for password length.
181
+ config.password_length = 6..128
182
+
183
+ # Email regex used to validate email formats. It simply asserts that
184
+ # one (and only one) @ exists in the given string. This is mainly
185
+ # to give user feedback and not to assert the e-mail validity.
186
+ config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
187
+
188
+ # ==> Configuration for :timeoutable
189
+ # The time you want to timeout the user session without activity. After this
190
+ # time the user will be asked for credentials again. Default is 30 minutes.
191
+ # config.timeout_in = 30.minutes
192
+
193
+ # ==> Configuration for :lockable
194
+ # Defines which strategy will be used to lock an account.
195
+ # :failed_attempts = Locks an account after a number of failed attempts to sign in.
196
+ # :none = No lock strategy. You should handle locking by yourself.
197
+ # config.lock_strategy = :failed_attempts
198
+
199
+ # Defines which key will be used when locking and unlocking an account
200
+ # config.unlock_keys = [:email]
201
+
202
+ # Defines which strategy will be used to unlock an account.
203
+ # :email = Sends an unlock link to the user email
204
+ # :time = Re-enables login after a certain amount of time (see :unlock_in below)
205
+ # :both = Enables both strategies
206
+ # :none = No unlock strategy. You should handle unlocking by yourself.
207
+ # config.unlock_strategy = :both
208
+
209
+ # Number of authentication tries before locking an account if lock_strategy
210
+ # is failed attempts.
211
+ # config.maximum_attempts = 20
212
+
213
+ # Time interval to unlock the account if :time is enabled as unlock_strategy.
214
+ # config.unlock_in = 1.hour
215
+
216
+ # Warn on the last attempt before the account is locked.
217
+ # config.last_attempt_warning = true
218
+
219
+ # ==> Configuration for :recoverable
220
+ #
221
+ # Defines which key will be used when recovering the password for an account
222
+ # config.reset_password_keys = [:email]
223
+
224
+ # Time interval you can reset your password with a reset password key.
225
+ # Don't put a too small interval or your users won't have the time to
226
+ # change their passwords.
227
+ config.reset_password_within = 6.hours
228
+
229
+ # When set to false, does not sign a user in automatically after their password is
230
+ # reset. Defaults to true, so a user is signed in automatically after a reset.
231
+ # config.sign_in_after_reset_password = true
232
+
233
+ # ==> Configuration for :encryptable
234
+ # Allow you to use another hashing or encryption algorithm besides bcrypt (default).
235
+ # You can use :sha1, :sha512 or algorithms from others authentication tools as
236
+ # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
237
+ # for default behavior) and :restful_authentication_sha1 (then you should set
238
+ # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
239
+ #
240
+ # Require the `devise-encryptable` gem when using anything other than bcrypt
241
+ # config.encryptor = :sha512
242
+
243
+ # ==> Scopes configuration
244
+ # Turn scoped views on. Before rendering "sessions/new", it will first check for
245
+ # "users/sessions/new". It's turned off by default because it's slower if you
246
+ # are using only default views.
247
+ # config.scoped_views = false
248
+
249
+ # Configure the default scope given to Warden. By default it's the first
250
+ # devise role declared in your routes (usually :user).
251
+ # config.default_scope = :user
252
+
253
+ # Set this configuration to false if you want /users/sign_out to sign out
254
+ # only the current scope. By default, Devise signs out all scopes.
255
+ # config.sign_out_all_scopes = true
256
+
257
+ # ==> Navigation configuration
258
+ # Lists the formats that should be treated as navigational. Formats like
259
+ # :html, should redirect to the sign in page when the user does not have
260
+ # access, but formats like :xml or :json, should return 401.
261
+ #
262
+ # If you have any extra navigational formats, like :iphone or :mobile, you
263
+ # should add them to the navigational formats lists.
264
+ #
265
+ # The "*/*" below is required to match Internet Explorer requests.
266
+ # config.navigational_formats = ['*/*', :html]
267
+
268
+ # The default HTTP method used to sign out a resource. Default is :delete.
269
+ config.sign_out_via = :delete
270
+
271
+ # ==> OmniAuth
272
+ # Add a new OmniAuth provider. Check the wiki for more information on setting
273
+ # up on your models and hooks.
274
+ # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
275
+
276
+ # ==> Warden configuration
277
+ # If you want to use other strategies, that are not supported by Devise, or
278
+ # change the failure app, you can configure them inside the config.warden block.
279
+ #
280
+ # config.warden do |manager|
281
+ # manager.intercept_401 = false
282
+ # manager.default_strategies(scope: :user).unshift :some_external_strategy
283
+ # end
284
+
285
+ # ==> Mountable engine configurations
286
+ # When using Devise inside an engine, let's call it `MyEngine`, and this engine
287
+ # is mountable, there are some extra configurations to be taken into account.
288
+ # The following options are available, assuming the engine is mounted as:
289
+ #
290
+ # mount MyEngine, at: '/my_engine'
291
+ #
292
+ # The router that invoked `devise_for`, in the example above, would be:
293
+ # config.router_name = :my_engine
294
+ #
295
+ # When using OmniAuth, Devise cannot automatically set OmniAuth path,
296
+ # so you need to do it manually. For the users scope, it would be:
297
+ # config.omniauth_path_prefix = '/my_engine/users/auth'
298
+
299
+ # ==> Turbolinks configuration
300
+ # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly:
301
+ #
302
+ # ActiveSupport.on_load(:devise_failure_app) do
303
+ # include Turbolinks::Controller
304
+ # end
305
+
306
+ # ==> Configuration for :registerable
307
+
308
+ # When set to false, does not sign a user in automatically after their password is
309
+ # changed. Defaults to true, so a user is signed in automatically after changing a password.
310
+ # config.sign_in_after_change_password = true
311
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ibrain/auth/failure_app'
4
+
5
+ # ==> Configuration for jwt
6
+ Devise.jwt do |jwt|
7
+ jwt.secret = ENV.fetch('JWT_SECRET_KEY', Ibrain::Auth::Config.jwt_secret_key) # Rails.application.credentials.secret_key_base
8
+ jwt.expiration_time = 3600 * 24 * 30 # 30day
9
+ end
10
+
11
+ Devise.warden do |manager|
12
+ manager.failure_app = Ibrain::Auth::FailureApp
13
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Ibrain::Auth::FailureApp < Devise::FailureApp
4
+ include ActionController::Helpers
5
+
6
+ def respond
7
+ json_error_response
8
+ end
9
+
10
+ def json_error_response
11
+ self.status = 401
12
+ self.content_type = "application/json"
13
+ self.response_body = {
14
+ errors: [{
15
+ message: i18n_message,
16
+ extensions: {
17
+ code: 401,
18
+ exception: {
19
+ stacktrace: []
20
+ }
21
+ }
22
+ }],
23
+ message: i18n_message,
24
+ data: nil
25
+ }.to_json
26
+ end
27
+ end
@@ -4,14 +4,14 @@ module Ibrain
4
4
  # frozen_string_literal: true
5
5
 
6
6
  module Auth
7
- VERSION = '0.1.1'
7
+ VERSION = '0.1.5'
8
8
 
9
9
  def self.ibrain_auth_version
10
10
  VERSION
11
11
  end
12
12
 
13
13
  def self.previous_ibrain_auth_minor_version
14
- '0.1.0'
14
+ '0.1.4'
15
15
  end
16
16
 
17
17
  def self.ibrain_auth_gem_version
data/lib/ibrain/auth.rb CHANGED
@@ -1,9 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'ibrain_core'
4
3
  require 'devise'
5
4
  require 'devise-encryptable'
6
5
  require 'devise/jwt'
6
+ require 'ibrain_core'
7
7
 
8
8
  require 'ibrain/auth/devise'
9
9
  require 'ibrain/auth/version'
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ibrain-auth
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.1.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tai Nguyen Van
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2021-12-27 00:00:00.000000000 Z
11
+ date: 2022-01-11 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: devise
@@ -72,14 +72,14 @@ dependencies:
72
72
  requirements:
73
73
  - - "~>"
74
74
  - !ruby/object:Gem::Version
75
- version: 0.1.5
75
+ version: 0.2.4
76
76
  type: :runtime
77
77
  prerelease: false
78
78
  version_requirements: !ruby/object:Gem::Requirement
79
79
  requirements:
80
80
  - - "~>"
81
81
  - !ruby/object:Gem::Version
82
- version: 0.1.5
82
+ version: 0.2.4
83
83
  - !ruby/object:Gem::Dependency
84
84
  name: rails
85
85
  requirement: !ruby/object:Gem::Requirement
@@ -129,6 +129,10 @@ files:
129
129
  - app/controllers/ibrain/auth/registrations_controller.rb
130
130
  - app/controllers/ibrain/auth/sessions_controller.rb
131
131
  - app/controllers/ibrain/auth/unlocks_controller.rb
132
+ - app/graphql/ibrain/auth/mutations/base_mutation.rb
133
+ - app/graphql/ibrain/auth/mutations/sign_in_mutation.rb
134
+ - app/graphql/ibrain/auth/mutations/sign_out_mutation.rb
135
+ - app/graphql/ibrain/auth/mutations/sso_sign_in_mutation.rb
132
136
  - app/models/ibrain/auth/user.rb
133
137
  - app/repositories/auth_repository.rb
134
138
  - config/initializers/devise.rb
@@ -139,11 +143,13 @@ files:
139
143
  - lib/generators/ibrain/auth/install/install_generator.rb
140
144
  - lib/generators/ibrain/auth/install/templates/config/initializers/devise.rb.tt
141
145
  - lib/generators/ibrain/auth/install/templates/config/initializers/ibrain_auth.rb.tt
146
+ - lib/generators/ibrain/auth/install/templates/config/initializers/ibrain_jwt.rb.tt
142
147
  - lib/generators/ibrain/auth/install/templates/db/schemas/users_migrate.erb
143
148
  - lib/generators/ibrain/auth/install/templates/db/schemas/users_schema.erb
144
149
  - lib/ibrain/auth.rb
145
150
  - lib/ibrain/auth/devise.rb
146
151
  - lib/ibrain/auth/engine.rb
152
+ - lib/ibrain/auth/failure_app.rb
147
153
  - lib/ibrain/auth/version.rb
148
154
  - lib/ibrain/auth_configuration.rb
149
155
  - lib/ibrain/authentication_helpers.rb