Skip to content

User.from_jwt! method only creates users but never updates existing ones #1739

@louispt1

Description

@louispt1

Context

Running bin/import-scenarios --user email.address@email.com checks if a user is an admin in etengine before assigning scenarios to them. That's because dump n load is admin only functionality. Unfortunately, if the user already existed in etengine before they were made an admin in myetm (which is a common scenario), the etengine user may not be recognised as an admin user, or have access to the users email.

Steps to reproduce

bin/import-scenarios --user email.address@email.com - this is just one example. Specifying a user by their email in etengine could also fail quite often.

Version (e.g. production/2025-01):

Proposed solution

If the user exists, sync their data (admin status, name, email) from the JWT token.

Before:

  def self.from_jwt!(token)
    id = token['sub']
    admin = token.dig('user', 'admin')
    name = token.dig('user', 'name')
    email = token.dig('user', 'email')

    raise 'Token does not contain user information' if id.blank? || name.blank? || email.blank?

    User.find_or_create_by!(id: token['sub']) do |u|
      u.admin = admin.presence || false
      u.name = name
      u.user_email = email
  end

After:

  def self.from_jwt!(token)
    id = token['sub']
    admin = token.dig('user', 'admin')
    name = token.dig('user', 'name')
    email = token.dig('user', 'email')

    raise 'Token does not contain user information' if id.blank? || name.blank? || email.blank?

    User.find_or_create_by!(id: token['sub']) do |u|
      u.admin = admin.presence || false
      u.name = name
      u.user_email = email
    end.tap do |user|

      jwt_admin = admin.presence || false

      if user.admin != jwt_admin || user.name != name || user.user_email != email
        user.update!(
          admin: jwt_admin,
          name: name,
          user_email: email
        )
      end
    end

The spec will also need to be updated to test this behaviour

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions