Skip to content

Commit

Permalink
Add last_name to ApiKey users
Browse files Browse the repository at this point in the history
When we generate a `:common_name` on Users, we check for the presence of
both `first_name` and `last_name`. If either is `nil`, we don't generate
a `common_name`.

ApiKey users only have one name (the name of the ApiKey itself) but we
should set the `last_name` to an empty string. This way, the common name
will still be generated.

Because the `metabase.models.user/insert-new-user!` function requires a
NonBlankString for `first_name` and `last_name` if they're present, I
went back to calling `t2/insert-returning-instances!` directly.
  • Loading branch information
johnswanson committed Jan 3, 2024
1 parent 0ef5af2 commit 06d6253
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
13 changes: 9 additions & 4 deletions src/metabase/api/api_key.clj
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,13 @@
(let [unhashed-key (key-with-unique-prefix)
email (format "api-key-user-%s@api-key.invalid" (u/slugify name))]
(t2/with-transaction [_conn]
(let [user (user/insert-new-user! {:email email
:first_name name
:type :api-key})]
(let [user (first
(t2/insert-returning-instances! :model/User
{:email email
:first_name name
:last_name ""
:type :api-key
:password (str (random-uuid))}))]
(user/set-permissions-groups! user [(perms-group/all-users) group_id])
(let [api-key (-> (t2/insert-returning-instance! :model/ApiKey
(-> {:user_id (u/the-id user)
Expand Down Expand Up @@ -93,7 +97,8 @@
(user/set-permissions-groups! user [(perms-group/all-users) {:id group_id}])))
(when name
;; A bit of a pain to keep these in sync, but oh well.
(t2/update! :model/User (:user_id api-key-before) {:first_name name})
(t2/update! :model/User (:user_id api-key-before) {:first_name name
:last_name ""})
(t2/update! :model/ApiKey id (with-updated-by {:name name}))))
(let [updated-api-key (-> (t2/select-one :model/ApiKey :id id)
(t2/hydrate :group :updated_by))]
Expand Down
2 changes: 1 addition & 1 deletion src/metabase/models/user.clj
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@
[:email ms/Email]
[:first_name [:maybe ms/NonBlankString]]])

(mu/defn insert-new-user!
(mu/defn ^:private insert-new-user!
"Creates a new user, defaulting the password when not provided"
[new-user :- NewUser]
(first (t2/insert-returning-instances! User (update new-user :password #(or % (str (random-uuid)))))))
Expand Down

0 comments on commit 06d6253

Please sign in to comment.