100 lines
2.5 KiB
Go
100 lines
2.5 KiB
Go
// Package perm is the single source of truth for permission codes. One code
|
|
// per module: holding it grants every action (read and write) in that module;
|
|
// which records the caller sees is decided by the role's scope, not here.
|
|
//
|
|
// The admin UI can only assign these codes to roles - it cannot create,
|
|
// rename or delete them. Sync writes this list into the permissions table on
|
|
// startup so role_permissions' foreign key always matches the code.
|
|
package perm
|
|
|
|
import (
|
|
"context"
|
|
|
|
"online-back/pkg/client/postgresql"
|
|
)
|
|
|
|
type Code string
|
|
|
|
const (
|
|
Dashboard Code = "dashboard"
|
|
Cards Code = "cards"
|
|
Loans Code = "loans"
|
|
Users Code = "users"
|
|
Roles Code = "roles"
|
|
Branches Code = "branches"
|
|
Provinces Code = "provinces"
|
|
Currencies Code = "currencies"
|
|
PaymentSettings Code = "payment-settings"
|
|
Backups Code = "backups"
|
|
ActivityLogs Code = "activity-logs"
|
|
)
|
|
|
|
type Def struct {
|
|
Code Code `json:"code"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
// All is also the display order for the admin UI and the profile.
|
|
var All = []Def{
|
|
{Dashboard, "Dolandyryş paneli"},
|
|
{Cards, "Kartlar"},
|
|
{Loans, "Karzlar"},
|
|
{Users, "Ulanyjylar"},
|
|
{Roles, "Rollar"},
|
|
{Branches, "Şahamçalar"},
|
|
{Provinces, "Welaýatlar"},
|
|
{Currencies, "Walýutalar"},
|
|
{PaymentSettings, "Töleg sazlamalary"},
|
|
{Backups, "Ätiýaçlyk nusgalary"},
|
|
{ActivityLogs, "Hereket žurnaly"},
|
|
}
|
|
|
|
var known = func() map[Code]struct{} {
|
|
m := make(map[Code]struct{}, len(All))
|
|
for _, d := range All {
|
|
m[d.Code] = struct{}{}
|
|
}
|
|
return m
|
|
}()
|
|
|
|
func Valid(code Code) bool {
|
|
_, ok := known[code]
|
|
return ok
|
|
}
|
|
|
|
func Codes() []Code {
|
|
out := make([]Code, len(All))
|
|
for i, d := range All {
|
|
out[i] = d.Code
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Sync upserts All into the permissions table and removes codes no longer
|
|
// in the catalog (role_permissions rows go with them via ON DELETE CASCADE).
|
|
func Sync(ctx context.Context, client postgresql.Client) error {
|
|
tx, err := client.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
codes := make([]string, len(All))
|
|
names := make([]string, len(All))
|
|
for i, d := range All {
|
|
codes[i] = string(d.Code)
|
|
names[i] = d.Name
|
|
}
|
|
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO permissions (code, name)
|
|
SELECT * FROM unnest($1::varchar[], $2::varchar[])
|
|
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name`, codes, names); err != nil {
|
|
return err
|
|
}
|
|
if _, err := tx.Exec(ctx, `DELETE FROM permissions WHERE NOT (code = ANY($1::varchar[]))`, codes); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|