2021-07-13 19:54:22 +00:00
|
|
|
package mysql
|
|
|
|
|
|
|
|
import (
|
2021-09-14 12:11:07 +00:00
|
|
|
"context"
|
2021-07-13 19:54:22 +00:00
|
|
|
"database/sql"
|
|
|
|
"encoding/json"
|
2021-09-01 19:50:52 +00:00
|
|
|
|
2021-11-15 14:11:38 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
2021-07-13 19:54:22 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/fleet"
|
2021-09-14 14:44:02 +00:00
|
|
|
"github.com/jmoiron/sqlx"
|
2021-07-13 19:54:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// NewActivity stores an activity item that the user performed
|
2021-09-14 12:11:07 +00:00
|
|
|
func (d *Datastore) NewActivity(ctx context.Context, user *fleet.User, activityType string, details *map[string]interface{}) error {
|
2021-07-13 19:54:22 +00:00
|
|
|
detailsBytes, err := json.Marshal(details)
|
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return ctxerr.Wrap(ctx, err, "marshaling activity details")
|
2021-07-13 19:54:22 +00:00
|
|
|
}
|
2021-09-14 14:44:02 +00:00
|
|
|
_, err = d.writer.ExecContext(ctx,
|
2021-07-13 19:54:22 +00:00
|
|
|
`INSERT INTO activities (user_id, user_name, activity_type, details) VALUES(?,?,?,?)`,
|
|
|
|
user.ID,
|
|
|
|
user.Name,
|
|
|
|
activityType,
|
|
|
|
detailsBytes,
|
|
|
|
)
|
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return ctxerr.Wrap(ctx, err, "new activity")
|
2021-07-13 19:54:22 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ListActivities returns a slice of activities performed across the organization
|
2021-09-14 12:11:07 +00:00
|
|
|
func (d *Datastore) ListActivities(ctx context.Context, opt fleet.ListOptions) ([]*fleet.Activity, error) {
|
2021-07-13 19:54:22 +00:00
|
|
|
activities := []*fleet.Activity{}
|
2021-09-01 19:50:52 +00:00
|
|
|
query := `SELECT a.id, a.user_id, a.created_at, a.activity_type, a.details, coalesce(u.name, a.user_name) as name, u.gravatar_url, u.email
|
2021-07-13 19:54:22 +00:00
|
|
|
FROM activities a LEFT JOIN users u ON (a.user_id=u.id)
|
|
|
|
WHERE true`
|
|
|
|
query = appendListOptionsToSQL(query, opt)
|
|
|
|
|
2021-09-14 14:44:02 +00:00
|
|
|
err := sqlx.SelectContext(ctx, d.reader, &activities, query)
|
2021-07-13 19:54:22 +00:00
|
|
|
if err == sql.ErrNoRows {
|
2021-11-15 14:11:38 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, notFound("Activity"))
|
2021-07-13 19:54:22 +00:00
|
|
|
} else if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "select activities")
|
2021-07-13 19:54:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return activities, nil
|
|
|
|
}
|