Skip to content

feat: notify about created user account #14010

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 26 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DELETE FROM notification_templates WHERE id = '4e19c0ac-94e1-4532-9515-d1801aa283b2';
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
INSERT INTO notification_templates (id, name, title_template, body_template, "group", actions)
VALUES ('4e19c0ac-94e1-4532-9515-d1801aa283b2', 'User account created', E'User account "{{.Labels.user_account_name}}" created',
E'Hi {{.UserName}},\n\New user account **{{.Labels.user_account_name}}** has been created.',
'Workspace Events', '[
{
"label": "View accounts",
"url": "{{ base_url }}/deployment/users?filter=status%3Aactive"
}
]'::jsonb);
2 changes: 2 additions & 0 deletions coderd/notifications/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ var (
TemplateWorkspaceDormant = uuid.MustParse("0ea69165-ec14-4314-91f1-69566ac3c5a0")
TemplateWorkspaceAutoUpdated = uuid.MustParse("c34a0c09-0704-4cac-bd1c-0c0146811c2b")
TemplateWorkspaceMarkedForDeletion = uuid.MustParse("51ce2fdf-c9ca-4be1-8d70-628674f9bc42")

TemplateUserAccountCreated = uuid.MustParse("4e19c0ac-94e1-4532-9515-d1801aa283b2")
)
51 changes: 49 additions & 2 deletions coderd/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
"golang.org/x/xerrors"

"cdr.dev/slog"

"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/db2sdk"
Expand All @@ -20,6 +23,7 @@ import (
"github.com/coder/coder/v2/coderd/gitsshkey"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/coderd/searchquery"
Expand Down Expand Up @@ -1200,7 +1204,8 @@ func (api *API) organizationByUserAndName(rw http.ResponseWriter, r *http.Reques

type CreateUserRequest struct {
codersdk.CreateUserRequest
LoginType database.LoginType
LoginType database.LoginType
SkipNotifications bool
}

func (api *API) CreateUser(ctx context.Context, store database.Store, req CreateUserRequest) (database.User, uuid.UUID, error) {
Expand All @@ -1211,7 +1216,7 @@ func (api *API) CreateUser(ctx context.Context, store database.Store, req Create
}

var user database.User
return user, req.OrganizationID, store.InTx(func(tx database.Store) error {
err := store.InTx(func(tx database.Store) error {
orgRoles := make([]string, 0)
// Organization is required to know where to allocate the user.
if req.OrganizationID == uuid.Nil {
Expand Down Expand Up @@ -1272,6 +1277,48 @@ func (api *API) CreateUser(ctx context.Context, store database.Store, req Create
}
return nil
}, nil)
if err == nil && !req.SkipNotifications {
// Notify user admins
// Get all users with user admin permission including owners
var owners, userAdmins []database.GetUsersRow
var eg errgroup.Group
eg.Go(func() error {
var err error
owners, err = api.Database.GetUsers(ctx, database.GetUsersParams{
RbacRole: []string{codersdk.RoleOwner},
})
if err != nil {
return xerrors.Errorf("get owners: %w", err)
}
return nil
})
eg.Go(func() error {
var err error
userAdmins, err = api.Database.GetUsers(ctx, database.GetUsersParams{
RbacRole: []string{codersdk.RoleUserAdmin},
})
if err != nil {
return xerrors.Errorf("get user admins: %w", err)
}
return nil
})
err := eg.Wait()
if err != nil {
return database.User{}, uuid.Nil, err
}

for _, u := range append(owners, userAdmins...) {
if _, err := api.NotificationsEnqueuer.Enqueue(ctx, u.ID, notifications.TemplateUserAccountCreated,
map[string]string{
"user_account_name": user.Username,
}, "api-users-create",
user.ID,
); err != nil {
api.Logger.Warn(ctx, "unable to notify about created user", slog.F("created_user", user.Name), slog.Error(err))
}
}
}
return user, req.OrganizationID, err
}

func convertUsers(users []database.User, organizationIDsByUserID map[uuid.UUID][]uuid.UUID) []codersdk.User {
Expand Down
88 changes: 88 additions & 0 deletions coderd/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/coder/coder/v2/coderd"
"github.com/coder/coder/v2/coderd/coderdtest/oidctest"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/serpent"

Expand Down Expand Up @@ -598,6 +599,93 @@ func TestPostUsers(t *testing.T) {
})
}

func TestNotifyCreatedUser(t *testing.T) {
t.Parallel()

t.Run("OwnerNotified", func(t *testing.T) {
t.Parallel()

notifyEnq := &testutil.FakeNotificationsEnqueuer{}
adminClient := coderdtest.New(t, &coderdtest.Options{
NotificationsEnqueuer: notifyEnq,
})
firstUser := coderdtest.CreateFirstUser(t, adminClient)

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

user, err := adminClient.CreateUser(ctx, codersdk.CreateUserRequest{
OrganizationID: firstUser.OrganizationID,
Email: "another@user.org",
Username: "someone-else",
Password: "SomeSecurePassword!",
})
require.NoError(t, err)

require.Len(t, notifyEnq.Sent, 1)
require.Equal(t, notifications.TemplateUserAccountCreated, notifyEnq.Sent[0].TemplateID)
require.Equal(t, firstUser.UserID, notifyEnq.Sent[0].UserID)
require.Contains(t, notifyEnq.Sent[0].Targets, user.ID)
require.Equal(t, user.Username, notifyEnq.Sent[0].Labels["user_account_name"])
})

t.Run("UserAdminNotified", func(t *testing.T) {
t.Parallel()

notifyEnq := &testutil.FakeNotificationsEnqueuer{}
adminClient := coderdtest.New(t, &coderdtest.Options{
NotificationsEnqueuer: notifyEnq,
})
firstUser := coderdtest.CreateFirstUser(t, adminClient)

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

userAdmin, err := adminClient.CreateUser(ctx, codersdk.CreateUserRequest{
OrganizationID: firstUser.OrganizationID,
Email: "user-admin@user.org",
Username: "mr-user-admin",
Password: "SomeSecurePassword!",
})
require.NoError(t, err)

_, err = adminClient.UpdateUserRoles(ctx, userAdmin.Username, codersdk.UpdateRoles{
Roles: []string{
rbac.RoleUserAdmin().String(),
},
})
require.NoError(t, err)

member, err := adminClient.CreateUser(ctx, codersdk.CreateUserRequest{
OrganizationID: firstUser.OrganizationID,
Email: "another@user.org",
Username: "someone-else",
Password: "SomeSecurePassword!",
})
require.NoError(t, err)

require.Len(t, notifyEnq.Sent, 3)

// "User admin" account created, "owner" notified
require.Equal(t, notifications.TemplateUserAccountCreated, notifyEnq.Sent[0].TemplateID)
require.Equal(t, firstUser.UserID, notifyEnq.Sent[0].UserID)
require.Contains(t, notifyEnq.Sent[0].Targets, userAdmin.ID)
require.Equal(t, userAdmin.Username, notifyEnq.Sent[0].Labels["user_account_name"])

// "Member" account created, "owner" notified
require.Equal(t, notifications.TemplateUserAccountCreated, notifyEnq.Sent[1].TemplateID)
require.Equal(t, firstUser.UserID, notifyEnq.Sent[1].UserID)
require.Contains(t, notifyEnq.Sent[1].Targets, member.ID)
require.Equal(t, member.Username, notifyEnq.Sent[1].Labels["user_account_name"])

// "Member" account created, "user admin" notified
require.Equal(t, notifications.TemplateUserAccountCreated, notifyEnq.Sent[1].TemplateID)
require.Equal(t, userAdmin.ID, notifyEnq.Sent[2].UserID)
require.Contains(t, notifyEnq.Sent[2].Targets, member.ID)
require.Equal(t, member.Username, notifyEnq.Sent[2].Labels["user_account_name"])
})
}

func TestUpdateUserProfile(t *testing.T) {
t.Parallel()
t.Run("UserNotFound", func(t *testing.T) {
Expand Down
2 changes: 2 additions & 0 deletions enterprise/coderd/scim.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ func (api *API) scimPostUser(rw http.ResponseWriter, r *http.Request) {
OrganizationID: defaultOrganization.ID,
},
LoginType: database.LoginTypeOIDC,
// Do not send notifications to user admins as SCIM endpoint might be called sequentially to all users.
SkipNotifications: true,
})
if err != nil {
_ = handlerutil.WriteError(rw, err)
Expand Down
Loading