cacert-boardvoting/internal/models/audit.go
Jan Dittberner 5efc57d2c3 Implement user deletion
- add audit logging for user changes
- refactor model errors into functions
- implement user delete form and submit handlers
2022-06-01 18:57:38 +02:00

67 lines
1.9 KiB
Go

/*
Copyright 2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/jmoiron/sqlx"
)
type AuditChange string
const (
AuditCreateUser AuditChange = "CREATE_USER"
AuditDeleteUser AuditChange = "DELETE_USER"
AuditEditUser AuditChange = "EDIT_USER"
AuditAddEmail AuditChange = "ADD_EMAIL"
AuditRemoveEmail AuditChange = "REMOVE_EMAIL"
AuditAddRole AuditChange = "ADD_ROLE"
AuditRemoveRole AuditChange = "REMOVE_ROLE"
)
type Audit struct {
ID int64 `db:"id"`
UserName string `db:"user_name"`
UserAddress string `db:"user_address"`
Created time.Time `db:"created"`
Change *AuditChange `db:"change"`
Reasoning string `db:"reasoning"`
Details string `db:"details"`
}
func AuditLog(ctx context.Context, tx *sqlx.Tx, user *User, change AuditChange, reasoning string, details any) error {
jsonDetails, err := json.Marshal(details)
if err != nil {
return fmt.Errorf("could not transform details to JSON: %w", err)
}
_, err = tx.ExecContext(
ctx,
`INSERT INTO audit (user_name, user_address, created, change, reasoning, details) VALUES (?, ?, ?, ?, ?, ?)`,
user.Name, user.Reminder, time.Now().UTC(), change, reasoning, string(jsonDetails),
)
if err != nil {
return errCouldNotExecuteQuery(err)
}
return nil
}