Class: CognitoRails::User

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/cognito_rails/user.rb

Overview

A class to map the cognito user to a model-like object

rubocop:disable Metrics/ClassLength

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ User

Returns a new instance of User.

Parameters:

  • attributes (Hash) (defaults to: {})

Options Hash (attributes):

  • :email (String)
  • :password (String, nil)
  • :phone (String, nil)
  • :custom_attributes (Array<Hash>, nil)
  • :user_class (Class, nil)


39
40
41
42
43
44
45
46
# File 'lib/cognito_rails/user.rb', line 39

def initialize(attributes = {})
  attributes = attributes.with_indifferent_access
  self.email = attributes[:email]
  self.password = SecureRandom.urlsafe_base64 || attributes[:password]
  self.phone = attributes[:phone]
  self.user_class = attributes[:user_class] || Config.default_user_class.constantize
  self.custom_attributes = attributes[:custom_attributes]
end

Instance Attribute Details

#custom_attributesArray<Hash>?

Returns:

  • (Array<Hash>, nil)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/cognito_rails/user.rb', line 24

class User
  # rubocop:enable Metrics/ClassLength

  include ActiveModel::Validations

  attr_accessor :id, :email, :password, :phone, :custom_attributes, :user_class

  validates :email, presence: true

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String, nil] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  def initialize(attributes = {})
    attributes = attributes.with_indifferent_access
    self.email = attributes[:email]
    self.password = SecureRandom.urlsafe_base64 || attributes[:password]
    self.phone = attributes[:phone]
    self.user_class = attributes[:user_class] || Config.default_user_class.constantize
    self.custom_attributes = attributes[:custom_attributes]
  end

  # @param id [String]
  # @param user_class [nil,Object]
  # @return [CognitoRails::User]
  def self.find(id, user_class = nil)
    result = cognito_client.admin_get_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id, # required
        username: id # required
      }
    )
    user = new(user_class: user_class)
    user.id = result.username
    user.email = extract_cognito_attribute(result.user_attributes, :email)
    user.phone = extract_cognito_attribute(result.user_attributes, :phone_number)
    user
  end

  def self.all
    cognito_client.list_users(user_pool_id: CognitoRails::Config.aws_user_pool_id)
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create!(attributes = {})
    user = new(attributes)
    user.save!
    user
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create(attributes = {})
    user = new(attributes)
    user.save
    user
  end

  # @return [Boolean]
  def new_record?
    !persisted?
  end

  # @return [Boolean]
  def persisted?
    id.present?
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def save!
    save || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Boolean]
  def save
    return false unless validate

    if persisted?
      save_for_update
    else
      save_for_create
    end

    true
  end

  # @return [Boolean]
  def destroy
    return false if new_record?

    cognito_client.admin_delete_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id
      }
    )
    self.id = nil

    true
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def destroy!
    destroy || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Aws::CognitoIdentityProvider::Client]
  # @raise [RuntimeError]
  def self.cognito_client
    @cognito_client ||= Aws::CognitoIdentityProvider::Client.new(
      { region: CognitoRails::Config.aws_region }.merge(CognitoRails::Config.aws_client_credentials)
    )
  end

  def self.extract_cognito_attribute(attributes, column)
    attributes.find { |attribute| attribute[:name] == column.to_s }&.dig(:value)
  end

  private

  # @return [Aws::CognitoIdentityProvider::Client]
  def cognito_client
    self.class.cognito_client
  end

  # @return [Boolean]
  def verify_email?
    user_class._cognito_verify_email
  end

  # @return [Boolean]
  def verify_phone?
    user_class._cognito_verify_phone
  end

  # @return [Array<Hash>]
  def general_user_attributes
    [
      *([{ name: 'email', value: email }] if email),
      *([{ name: 'phone_number', value: phone }] if phone),
      *custom_attributes
    ]
  end

  # @return [Array<Hash>]
  def verify_user_attributes
    [
      *([{ name: 'email_verified', value: 'True' }] if verify_email?),
      *([{ name: 'phone_number_verified', value: 'True' }] if verify_phone?)
    ]
  end

  def save_for_create
    resp = cognito_client.admin_create_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: email,
        temporary_password: password,
        user_attributes: [
          *general_user_attributes,
          *verify_user_attributes
        ]
      }
    )
    self.id = resp.user.attributes.find { |a| a[:name] == 'sub' }[:value]
  end

  def save_for_update
    cognito_client.admin_update_user_attributes(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id,
        user_attributes: [
          *general_user_attributes
        ]
      }
    )
  end
end

#emailString

Returns:

  • (String)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/cognito_rails/user.rb', line 24

class User
  # rubocop:enable Metrics/ClassLength

  include ActiveModel::Validations

  attr_accessor :id, :email, :password, :phone, :custom_attributes, :user_class

  validates :email, presence: true

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String, nil] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  def initialize(attributes = {})
    attributes = attributes.with_indifferent_access
    self.email = attributes[:email]
    self.password = SecureRandom.urlsafe_base64 || attributes[:password]
    self.phone = attributes[:phone]
    self.user_class = attributes[:user_class] || Config.default_user_class.constantize
    self.custom_attributes = attributes[:custom_attributes]
  end

  # @param id [String]
  # @param user_class [nil,Object]
  # @return [CognitoRails::User]
  def self.find(id, user_class = nil)
    result = cognito_client.admin_get_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id, # required
        username: id # required
      }
    )
    user = new(user_class: user_class)
    user.id = result.username
    user.email = extract_cognito_attribute(result.user_attributes, :email)
    user.phone = extract_cognito_attribute(result.user_attributes, :phone_number)
    user
  end

  def self.all
    cognito_client.list_users(user_pool_id: CognitoRails::Config.aws_user_pool_id)
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create!(attributes = {})
    user = new(attributes)
    user.save!
    user
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create(attributes = {})
    user = new(attributes)
    user.save
    user
  end

  # @return [Boolean]
  def new_record?
    !persisted?
  end

  # @return [Boolean]
  def persisted?
    id.present?
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def save!
    save || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Boolean]
  def save
    return false unless validate

    if persisted?
      save_for_update
    else
      save_for_create
    end

    true
  end

  # @return [Boolean]
  def destroy
    return false if new_record?

    cognito_client.admin_delete_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id
      }
    )
    self.id = nil

    true
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def destroy!
    destroy || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Aws::CognitoIdentityProvider::Client]
  # @raise [RuntimeError]
  def self.cognito_client
    @cognito_client ||= Aws::CognitoIdentityProvider::Client.new(
      { region: CognitoRails::Config.aws_region }.merge(CognitoRails::Config.aws_client_credentials)
    )
  end

  def self.extract_cognito_attribute(attributes, column)
    attributes.find { |attribute| attribute[:name] == column.to_s }&.dig(:value)
  end

  private

  # @return [Aws::CognitoIdentityProvider::Client]
  def cognito_client
    self.class.cognito_client
  end

  # @return [Boolean]
  def verify_email?
    user_class._cognito_verify_email
  end

  # @return [Boolean]
  def verify_phone?
    user_class._cognito_verify_phone
  end

  # @return [Array<Hash>]
  def general_user_attributes
    [
      *([{ name: 'email', value: email }] if email),
      *([{ name: 'phone_number', value: phone }] if phone),
      *custom_attributes
    ]
  end

  # @return [Array<Hash>]
  def verify_user_attributes
    [
      *([{ name: 'email_verified', value: 'True' }] if verify_email?),
      *([{ name: 'phone_number_verified', value: 'True' }] if verify_phone?)
    ]
  end

  def save_for_create
    resp = cognito_client.admin_create_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: email,
        temporary_password: password,
        user_attributes: [
          *general_user_attributes,
          *verify_user_attributes
        ]
      }
    )
    self.id = resp.user.attributes.find { |a| a[:name] == 'sub' }[:value]
  end

  def save_for_update
    cognito_client.admin_update_user_attributes(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id,
        user_attributes: [
          *general_user_attributes
        ]
      }
    )
  end
end

#idString

Returns:

  • (String)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/cognito_rails/user.rb', line 24

class User
  # rubocop:enable Metrics/ClassLength

  include ActiveModel::Validations

  attr_accessor :id, :email, :password, :phone, :custom_attributes, :user_class

  validates :email, presence: true

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String, nil] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  def initialize(attributes = {})
    attributes = attributes.with_indifferent_access
    self.email = attributes[:email]
    self.password = SecureRandom.urlsafe_base64 || attributes[:password]
    self.phone = attributes[:phone]
    self.user_class = attributes[:user_class] || Config.default_user_class.constantize
    self.custom_attributes = attributes[:custom_attributes]
  end

  # @param id [String]
  # @param user_class [nil,Object]
  # @return [CognitoRails::User]
  def self.find(id, user_class = nil)
    result = cognito_client.admin_get_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id, # required
        username: id # required
      }
    )
    user = new(user_class: user_class)
    user.id = result.username
    user.email = extract_cognito_attribute(result.user_attributes, :email)
    user.phone = extract_cognito_attribute(result.user_attributes, :phone_number)
    user
  end

  def self.all
    cognito_client.list_users(user_pool_id: CognitoRails::Config.aws_user_pool_id)
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create!(attributes = {})
    user = new(attributes)
    user.save!
    user
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create(attributes = {})
    user = new(attributes)
    user.save
    user
  end

  # @return [Boolean]
  def new_record?
    !persisted?
  end

  # @return [Boolean]
  def persisted?
    id.present?
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def save!
    save || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Boolean]
  def save
    return false unless validate

    if persisted?
      save_for_update
    else
      save_for_create
    end

    true
  end

  # @return [Boolean]
  def destroy
    return false if new_record?

    cognito_client.admin_delete_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id
      }
    )
    self.id = nil

    true
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def destroy!
    destroy || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Aws::CognitoIdentityProvider::Client]
  # @raise [RuntimeError]
  def self.cognito_client
    @cognito_client ||= Aws::CognitoIdentityProvider::Client.new(
      { region: CognitoRails::Config.aws_region }.merge(CognitoRails::Config.aws_client_credentials)
    )
  end

  def self.extract_cognito_attribute(attributes, column)
    attributes.find { |attribute| attribute[:name] == column.to_s }&.dig(:value)
  end

  private

  # @return [Aws::CognitoIdentityProvider::Client]
  def cognito_client
    self.class.cognito_client
  end

  # @return [Boolean]
  def verify_email?
    user_class._cognito_verify_email
  end

  # @return [Boolean]
  def verify_phone?
    user_class._cognito_verify_phone
  end

  # @return [Array<Hash>]
  def general_user_attributes
    [
      *([{ name: 'email', value: email }] if email),
      *([{ name: 'phone_number', value: phone }] if phone),
      *custom_attributes
    ]
  end

  # @return [Array<Hash>]
  def verify_user_attributes
    [
      *([{ name: 'email_verified', value: 'True' }] if verify_email?),
      *([{ name: 'phone_number_verified', value: 'True' }] if verify_phone?)
    ]
  end

  def save_for_create
    resp = cognito_client.admin_create_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: email,
        temporary_password: password,
        user_attributes: [
          *general_user_attributes,
          *verify_user_attributes
        ]
      }
    )
    self.id = resp.user.attributes.find { |a| a[:name] == 'sub' }[:value]
  end

  def save_for_update
    cognito_client.admin_update_user_attributes(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id,
        user_attributes: [
          *general_user_attributes
        ]
      }
    )
  end
end

#passwordString?

Returns:

  • (String, nil)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/cognito_rails/user.rb', line 24

class User
  # rubocop:enable Metrics/ClassLength

  include ActiveModel::Validations

  attr_accessor :id, :email, :password, :phone, :custom_attributes, :user_class

  validates :email, presence: true

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String, nil] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  def initialize(attributes = {})
    attributes = attributes.with_indifferent_access
    self.email = attributes[:email]
    self.password = SecureRandom.urlsafe_base64 || attributes[:password]
    self.phone = attributes[:phone]
    self.user_class = attributes[:user_class] || Config.default_user_class.constantize
    self.custom_attributes = attributes[:custom_attributes]
  end

  # @param id [String]
  # @param user_class [nil,Object]
  # @return [CognitoRails::User]
  def self.find(id, user_class = nil)
    result = cognito_client.admin_get_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id, # required
        username: id # required
      }
    )
    user = new(user_class: user_class)
    user.id = result.username
    user.email = extract_cognito_attribute(result.user_attributes, :email)
    user.phone = extract_cognito_attribute(result.user_attributes, :phone_number)
    user
  end

  def self.all
    cognito_client.list_users(user_pool_id: CognitoRails::Config.aws_user_pool_id)
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create!(attributes = {})
    user = new(attributes)
    user.save!
    user
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create(attributes = {})
    user = new(attributes)
    user.save
    user
  end

  # @return [Boolean]
  def new_record?
    !persisted?
  end

  # @return [Boolean]
  def persisted?
    id.present?
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def save!
    save || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Boolean]
  def save
    return false unless validate

    if persisted?
      save_for_update
    else
      save_for_create
    end

    true
  end

  # @return [Boolean]
  def destroy
    return false if new_record?

    cognito_client.admin_delete_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id
      }
    )
    self.id = nil

    true
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def destroy!
    destroy || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Aws::CognitoIdentityProvider::Client]
  # @raise [RuntimeError]
  def self.cognito_client
    @cognito_client ||= Aws::CognitoIdentityProvider::Client.new(
      { region: CognitoRails::Config.aws_region }.merge(CognitoRails::Config.aws_client_credentials)
    )
  end

  def self.extract_cognito_attribute(attributes, column)
    attributes.find { |attribute| attribute[:name] == column.to_s }&.dig(:value)
  end

  private

  # @return [Aws::CognitoIdentityProvider::Client]
  def cognito_client
    self.class.cognito_client
  end

  # @return [Boolean]
  def verify_email?
    user_class._cognito_verify_email
  end

  # @return [Boolean]
  def verify_phone?
    user_class._cognito_verify_phone
  end

  # @return [Array<Hash>]
  def general_user_attributes
    [
      *([{ name: 'email', value: email }] if email),
      *([{ name: 'phone_number', value: phone }] if phone),
      *custom_attributes
    ]
  end

  # @return [Array<Hash>]
  def verify_user_attributes
    [
      *([{ name: 'email_verified', value: 'True' }] if verify_email?),
      *([{ name: 'phone_number_verified', value: 'True' }] if verify_phone?)
    ]
  end

  def save_for_create
    resp = cognito_client.admin_create_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: email,
        temporary_password: password,
        user_attributes: [
          *general_user_attributes,
          *verify_user_attributes
        ]
      }
    )
    self.id = resp.user.attributes.find { |a| a[:name] == 'sub' }[:value]
  end

  def save_for_update
    cognito_client.admin_update_user_attributes(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id,
        user_attributes: [
          *general_user_attributes
        ]
      }
    )
  end
end

#phoneString?

Returns:

  • (String, nil)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/cognito_rails/user.rb', line 24

class User
  # rubocop:enable Metrics/ClassLength

  include ActiveModel::Validations

  attr_accessor :id, :email, :password, :phone, :custom_attributes, :user_class

  validates :email, presence: true

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String, nil] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  def initialize(attributes = {})
    attributes = attributes.with_indifferent_access
    self.email = attributes[:email]
    self.password = SecureRandom.urlsafe_base64 || attributes[:password]
    self.phone = attributes[:phone]
    self.user_class = attributes[:user_class] || Config.default_user_class.constantize
    self.custom_attributes = attributes[:custom_attributes]
  end

  # @param id [String]
  # @param user_class [nil,Object]
  # @return [CognitoRails::User]
  def self.find(id, user_class = nil)
    result = cognito_client.admin_get_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id, # required
        username: id # required
      }
    )
    user = new(user_class: user_class)
    user.id = result.username
    user.email = extract_cognito_attribute(result.user_attributes, :email)
    user.phone = extract_cognito_attribute(result.user_attributes, :phone_number)
    user
  end

  def self.all
    cognito_client.list_users(user_pool_id: CognitoRails::Config.aws_user_pool_id)
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create!(attributes = {})
    user = new(attributes)
    user.save!
    user
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create(attributes = {})
    user = new(attributes)
    user.save
    user
  end

  # @return [Boolean]
  def new_record?
    !persisted?
  end

  # @return [Boolean]
  def persisted?
    id.present?
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def save!
    save || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Boolean]
  def save
    return false unless validate

    if persisted?
      save_for_update
    else
      save_for_create
    end

    true
  end

  # @return [Boolean]
  def destroy
    return false if new_record?

    cognito_client.admin_delete_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id
      }
    )
    self.id = nil

    true
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def destroy!
    destroy || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Aws::CognitoIdentityProvider::Client]
  # @raise [RuntimeError]
  def self.cognito_client
    @cognito_client ||= Aws::CognitoIdentityProvider::Client.new(
      { region: CognitoRails::Config.aws_region }.merge(CognitoRails::Config.aws_client_credentials)
    )
  end

  def self.extract_cognito_attribute(attributes, column)
    attributes.find { |attribute| attribute[:name] == column.to_s }&.dig(:value)
  end

  private

  # @return [Aws::CognitoIdentityProvider::Client]
  def cognito_client
    self.class.cognito_client
  end

  # @return [Boolean]
  def verify_email?
    user_class._cognito_verify_email
  end

  # @return [Boolean]
  def verify_phone?
    user_class._cognito_verify_phone
  end

  # @return [Array<Hash>]
  def general_user_attributes
    [
      *([{ name: 'email', value: email }] if email),
      *([{ name: 'phone_number', value: phone }] if phone),
      *custom_attributes
    ]
  end

  # @return [Array<Hash>]
  def verify_user_attributes
    [
      *([{ name: 'email_verified', value: 'True' }] if verify_email?),
      *([{ name: 'phone_number_verified', value: 'True' }] if verify_phone?)
    ]
  end

  def save_for_create
    resp = cognito_client.admin_create_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: email,
        temporary_password: password,
        user_attributes: [
          *general_user_attributes,
          *verify_user_attributes
        ]
      }
    )
    self.id = resp.user.attributes.find { |a| a[:name] == 'sub' }[:value]
  end

  def save_for_update
    cognito_client.admin_update_user_attributes(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id,
        user_attributes: [
          *general_user_attributes
        ]
      }
    )
  end
end

#user_classClass?

Returns:

  • (Class, nil)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/cognito_rails/user.rb', line 24

class User
  # rubocop:enable Metrics/ClassLength

  include ActiveModel::Validations

  attr_accessor :id, :email, :password, :phone, :custom_attributes, :user_class

  validates :email, presence: true

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String, nil] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  def initialize(attributes = {})
    attributes = attributes.with_indifferent_access
    self.email = attributes[:email]
    self.password = SecureRandom.urlsafe_base64 || attributes[:password]
    self.phone = attributes[:phone]
    self.user_class = attributes[:user_class] || Config.default_user_class.constantize
    self.custom_attributes = attributes[:custom_attributes]
  end

  # @param id [String]
  # @param user_class [nil,Object]
  # @return [CognitoRails::User]
  def self.find(id, user_class = nil)
    result = cognito_client.admin_get_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id, # required
        username: id # required
      }
    )
    user = new(user_class: user_class)
    user.id = result.username
    user.email = extract_cognito_attribute(result.user_attributes, :email)
    user.phone = extract_cognito_attribute(result.user_attributes, :phone_number)
    user
  end

  def self.all
    cognito_client.list_users(user_pool_id: CognitoRails::Config.aws_user_pool_id)
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create!(attributes = {})
    user = new(attributes)
    user.save!
    user
  end

  # @param attributes [Hash]
  # @option attributes [String] :email
  # @option attributes [String] :password
  # @option attributes [String, nil] :phone
  # @option attributes [Array<Hash>, nil] :custom_attributes
  # @option attributes [Class, nil] :user_class
  # @return [CognitoRails::User]
  def self.create(attributes = {})
    user = new(attributes)
    user.save
    user
  end

  # @return [Boolean]
  def new_record?
    !persisted?
  end

  # @return [Boolean]
  def persisted?
    id.present?
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def save!
    save || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Boolean]
  def save
    return false unless validate

    if persisted?
      save_for_update
    else
      save_for_create
    end

    true
  end

  # @return [Boolean]
  def destroy
    return false if new_record?

    cognito_client.admin_delete_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id
      }
    )
    self.id = nil

    true
  end

  # @return [Boolean]
  # @raise [ActiveRecord::RecordInvalid]
  def destroy!
    destroy || (raise ActiveRecord::RecordInvalid, self)
  end

  # @return [Aws::CognitoIdentityProvider::Client]
  # @raise [RuntimeError]
  def self.cognito_client
    @cognito_client ||= Aws::CognitoIdentityProvider::Client.new(
      { region: CognitoRails::Config.aws_region }.merge(CognitoRails::Config.aws_client_credentials)
    )
  end

  def self.extract_cognito_attribute(attributes, column)
    attributes.find { |attribute| attribute[:name] == column.to_s }&.dig(:value)
  end

  private

  # @return [Aws::CognitoIdentityProvider::Client]
  def cognito_client
    self.class.cognito_client
  end

  # @return [Boolean]
  def verify_email?
    user_class._cognito_verify_email
  end

  # @return [Boolean]
  def verify_phone?
    user_class._cognito_verify_phone
  end

  # @return [Array<Hash>]
  def general_user_attributes
    [
      *([{ name: 'email', value: email }] if email),
      *([{ name: 'phone_number', value: phone }] if phone),
      *custom_attributes
    ]
  end

  # @return [Array<Hash>]
  def verify_user_attributes
    [
      *([{ name: 'email_verified', value: 'True' }] if verify_email?),
      *([{ name: 'phone_number_verified', value: 'True' }] if verify_phone?)
    ]
  end

  def save_for_create
    resp = cognito_client.admin_create_user(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: email,
        temporary_password: password,
        user_attributes: [
          *general_user_attributes,
          *verify_user_attributes
        ]
      }
    )
    self.id = resp.user.attributes.find { |a| a[:name] == 'sub' }[:value]
  end

  def save_for_update
    cognito_client.admin_update_user_attributes(
      {
        user_pool_id: CognitoRails::Config.aws_user_pool_id,
        username: id,
        user_attributes: [
          *general_user_attributes
        ]
      }
    )
  end
end

Class Method Details

.allObject



65
66
67
# File 'lib/cognito_rails/user.rb', line 65

def self.all
  cognito_client.list_users(user_pool_id: CognitoRails::Config.aws_user_pool_id)
end

.cognito_clientAws::CognitoIdentityProvider::Client

Returns:

  • (Aws::CognitoIdentityProvider::Client)

Raises:

  • (RuntimeError)


147
148
149
150
151
# File 'lib/cognito_rails/user.rb', line 147

def self.cognito_client
  @cognito_client ||= Aws::CognitoIdentityProvider::Client.new(
    { region: CognitoRails::Config.aws_region }.merge(CognitoRails::Config.aws_client_credentials)
  )
end

.create(attributes = {}) ⇒ CognitoRails::User

Parameters:

  • attributes (Hash) (defaults to: {})

Options Hash (attributes):

  • :email (String)
  • :password (String)
  • :phone (String, nil)
  • :custom_attributes (Array<Hash>, nil)
  • :user_class (Class, nil)

Returns:



89
90
91
92
93
# File 'lib/cognito_rails/user.rb', line 89

def self.create(attributes = {})
  user = new(attributes)
  user.save
  user
end

.create!(attributes = {}) ⇒ CognitoRails::User

Parameters:

  • attributes (Hash) (defaults to: {})

Options Hash (attributes):

  • :email (String)
  • :password (String)
  • :phone (String, nil)
  • :custom_attributes (Array<Hash>, nil)
  • :user_class (Class, nil)

Returns:



76
77
78
79
80
# File 'lib/cognito_rails/user.rb', line 76

def self.create!(attributes = {})
  user = new(attributes)
  user.save!
  user
end

.extract_cognito_attribute(attributes, column) ⇒ Object



153
154
155
# File 'lib/cognito_rails/user.rb', line 153

def self.extract_cognito_attribute(attributes, column)
  attributes.find { |attribute| attribute[:name] == column.to_s }&.dig(:value)
end

.find(id, user_class = nil) ⇒ CognitoRails::User

Parameters:

  • id (String)
  • user_class (nil, Object) (defaults to: nil)

Returns:



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/cognito_rails/user.rb', line 51

def self.find(id, user_class = nil)
  result = cognito_client.admin_get_user(
    {
      user_pool_id: CognitoRails::Config.aws_user_pool_id, # required
      username: id # required
    }
  )
  user = new(user_class: user_class)
  user.id = result.username
  user.email = extract_cognito_attribute(result.user_attributes, :email)
  user.phone = extract_cognito_attribute(result.user_attributes, :phone_number)
  user
end

Instance Method Details

#destroyBoolean

Returns:

  • (Boolean)


125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/cognito_rails/user.rb', line 125

def destroy
  return false if new_record?

  cognito_client.admin_delete_user(
    {
      user_pool_id: CognitoRails::Config.aws_user_pool_id,
      username: id
    }
  )
  self.id = nil

  true
end

#destroy!Boolean

Returns:

  • (Boolean)

Raises:

  • (ActiveRecord::RecordInvalid)


141
142
143
# File 'lib/cognito_rails/user.rb', line 141

def destroy!
  destroy || (raise ActiveRecord::RecordInvalid, self)
end

#new_record?Boolean

Returns:

  • (Boolean)


96
97
98
# File 'lib/cognito_rails/user.rb', line 96

def new_record?
  !persisted?
end

#persisted?Boolean

Returns:

  • (Boolean)


101
102
103
# File 'lib/cognito_rails/user.rb', line 101

def persisted?
  id.present?
end

#saveBoolean

Returns:

  • (Boolean)


112
113
114
115
116
117
118
119
120
121
122
# File 'lib/cognito_rails/user.rb', line 112

def save
  return false unless validate

  if persisted?
    save_for_update
  else
    save_for_create
  end

  true
end

#save!Boolean

Returns:

  • (Boolean)

Raises:

  • (ActiveRecord::RecordInvalid)


107
108
109
# File 'lib/cognito_rails/user.rb', line 107

def save!
  save || (raise ActiveRecord::RecordInvalid, self)
end