role.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. package cmd
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "gogs.dmsc.dev/arp/arp_cli/client"
  9. "gogs.dmsc.dev/arp/arp_cli/config"
  10. "github.com/AlecAivazis/survey/v2"
  11. "github.com/olekukonko/tablewriter"
  12. "github.com/urfave/cli/v3"
  13. )
  14. // RoleCommand returns the role command
  15. func RoleCommand() *cli.Command {
  16. return &cli.Command{
  17. Name: "role",
  18. Usage: "Manage roles",
  19. Description: `Manage ARP roles. Roles group permissions for access control.
  20. Use this command to create, list, update, and delete roles.`,
  21. Commands: []*cli.Command{
  22. {
  23. Name: "list",
  24. Aliases: []string{"ls"},
  25. Usage: "List all roles",
  26. Flags: []cli.Flag{
  27. &cli.BoolFlag{
  28. Name: "json",
  29. Aliases: []string{"j"},
  30. Usage: "Output as JSON",
  31. },
  32. },
  33. Action: roleList,
  34. },
  35. {
  36. Name: "get",
  37. Usage: "Get a role by ID",
  38. Flags: []cli.Flag{
  39. &cli.StringFlag{
  40. Name: "id",
  41. Aliases: []string{"i"},
  42. Usage: "Role ID",
  43. Required: true,
  44. },
  45. &cli.BoolFlag{
  46. Name: "json",
  47. Aliases: []string{"j"},
  48. Usage: "Output as JSON",
  49. },
  50. },
  51. Action: roleGet,
  52. },
  53. {
  54. Name: "create",
  55. Usage: "Create a new role",
  56. Action: roleCreate,
  57. Flags: []cli.Flag{
  58. &cli.StringFlag{
  59. Name: "name",
  60. Aliases: []string{"n"},
  61. Usage: "Role name",
  62. },
  63. &cli.StringFlag{
  64. Name: "description",
  65. Aliases: []string{"d"},
  66. Usage: "Role description",
  67. },
  68. &cli.StringSliceFlag{
  69. Name: "permissions",
  70. Aliases: []string{"p"},
  71. Usage: "Permission IDs",
  72. },
  73. },
  74. },
  75. {
  76. Name: "update",
  77. Usage: "Update a role",
  78. Action: roleUpdate,
  79. Flags: []cli.Flag{
  80. &cli.StringFlag{
  81. Name: "id",
  82. Aliases: []string{"i"},
  83. Usage: "Role ID",
  84. Required: true,
  85. },
  86. &cli.StringFlag{
  87. Name: "name",
  88. Aliases: []string{"n"},
  89. Usage: "Role name",
  90. },
  91. &cli.StringFlag{
  92. Name: "description",
  93. Aliases: []string{"d"},
  94. Usage: "Role description",
  95. },
  96. &cli.StringSliceFlag{
  97. Name: "permissions",
  98. Aliases: []string{"p"},
  99. Usage: "Permission IDs",
  100. },
  101. },
  102. },
  103. {
  104. Name: "delete",
  105. Usage: "Delete a role",
  106. Action: roleDelete,
  107. Flags: []cli.Flag{
  108. &cli.StringFlag{
  109. Name: "id",
  110. Aliases: []string{"i"},
  111. Usage: "Role ID",
  112. Required: true,
  113. },
  114. &cli.BoolFlag{
  115. Name: "yes",
  116. Aliases: []string{"y"},
  117. Usage: "Skip confirmation",
  118. },
  119. },
  120. },
  121. },
  122. }
  123. }
  124. type RoleDetail struct {
  125. ID string `json:"id"`
  126. Name string `json:"name"`
  127. Description string `json:"description"`
  128. Permissions []Permission `json:"permissions"`
  129. }
  130. type Permission struct {
  131. ID string `json:"id"`
  132. Code string `json:"code"`
  133. Description string `json:"description"`
  134. }
  135. func roleList(ctx context.Context, cmd *cli.Command) error {
  136. cfg, err := config.Load()
  137. if err != nil {
  138. return err
  139. }
  140. if err := RequireAuth(cfg); err != nil {
  141. return err
  142. }
  143. c := client.New(cfg.ServerURL)
  144. c.SetToken(cfg.Token)
  145. query := "query Roles { roles { id name description permissions { id code } } }"
  146. resp, err := c.Query(query, nil)
  147. if err != nil {
  148. return err
  149. }
  150. var result struct {
  151. Roles []RoleDetail `json:"roles"`
  152. }
  153. if err := json.Unmarshal(resp.Data, &result); err != nil {
  154. return err
  155. }
  156. if cmd.Bool("json") {
  157. enc := json.NewEncoder(os.Stdout)
  158. enc.SetIndent("", " ")
  159. return enc.Encode(result.Roles)
  160. }
  161. if len(result.Roles) == 0 {
  162. fmt.Println("No roles found.")
  163. return nil
  164. }
  165. table := tablewriter.NewWriter(os.Stdout)
  166. table.Header([]string{"ID", "Name", "Description", "Permissions"})
  167. for _, r := range result.Roles {
  168. perms := make([]string, len(r.Permissions))
  169. for i, p := range r.Permissions {
  170. perms[i] = p.Code
  171. }
  172. table.Append([]string{r.ID, r.Name, r.Description, strings.Join(perms, ", ")})
  173. }
  174. table.Render()
  175. return nil
  176. }
  177. func roleGet(ctx context.Context, cmd *cli.Command) error {
  178. cfg, err := config.Load()
  179. if err != nil {
  180. return err
  181. }
  182. if err := RequireAuth(cfg); err != nil {
  183. return err
  184. }
  185. c := client.New(cfg.ServerURL)
  186. c.SetToken(cfg.Token)
  187. id := cmd.String("id")
  188. query := "query Role($id: ID!) { role(id: $id) { id name description permissions { id code description } } }"
  189. resp, err := c.Query(query, map[string]interface{}{"id": id})
  190. if err != nil {
  191. return err
  192. }
  193. var result struct {
  194. Role *RoleDetail `json:"role"`
  195. }
  196. if err := json.Unmarshal(resp.Data, &result); err != nil {
  197. return err
  198. }
  199. if result.Role == nil {
  200. return fmt.Errorf("role not found")
  201. }
  202. if cmd.Bool("json") {
  203. enc := json.NewEncoder(os.Stdout)
  204. enc.SetIndent("", " ")
  205. return enc.Encode(result.Role)
  206. }
  207. r := result.Role
  208. fmt.Printf("ID: %s\n", r.ID)
  209. fmt.Printf("Name: %s\n", r.Name)
  210. fmt.Printf("Description: %s\n", r.Description)
  211. fmt.Printf("Permissions:\n")
  212. for _, p := range r.Permissions {
  213. fmt.Printf(" - %s (%s): %s\n", p.Code, p.ID, p.Description)
  214. }
  215. return nil
  216. }
  217. func roleCreate(ctx context.Context, cmd *cli.Command) error {
  218. cfg, err := config.Load()
  219. if err != nil {
  220. return err
  221. }
  222. if err := RequireAuth(cfg); err != nil {
  223. return err
  224. }
  225. name := cmd.String("name")
  226. description := cmd.String("description")
  227. permissions := cmd.StringSlice("permissions")
  228. if name == "" {
  229. prompt := &survey.Input{Message: "Role name:"}
  230. if err := survey.AskOne(prompt, &name, survey.WithValidator(survey.Required)); err != nil {
  231. return err
  232. }
  233. }
  234. if description == "" {
  235. prompt := &survey.Input{Message: "Description:"}
  236. if err := survey.AskOne(prompt, &description, survey.WithValidator(survey.Required)); err != nil {
  237. return err
  238. }
  239. }
  240. if len(permissions) == 0 {
  241. var permissionsStr string
  242. prompt := &survey.Input{Message: "Permission IDs (comma-separated):"}
  243. if err := survey.AskOne(prompt, &permissionsStr, survey.WithValidator(survey.Required)); err != nil {
  244. return err
  245. }
  246. for _, p := range strings.Split(permissionsStr, ",") {
  247. permissions = append(permissions, strings.TrimSpace(p))
  248. }
  249. }
  250. c := client.New(cfg.ServerURL)
  251. c.SetToken(cfg.Token)
  252. mutation := `mutation CreateRole($input: NewRole!) { createRole(input: $input) { id name description permissions { id code } } }`
  253. input := map[string]interface{}{
  254. "name": name,
  255. "description": description,
  256. "permissions": permissions,
  257. }
  258. resp, err := c.Mutation(mutation, map[string]interface{}{"input": input})
  259. if err != nil {
  260. return err
  261. }
  262. var result struct {
  263. CreateRole *RoleDetail `json:"createRole"`
  264. }
  265. if err := json.Unmarshal(resp.Data, &result); err != nil {
  266. return err
  267. }
  268. if result.CreateRole == nil {
  269. return fmt.Errorf("failed to create role")
  270. }
  271. fmt.Printf("Role created successfully!\n")
  272. fmt.Printf("ID: %s\n", result.CreateRole.ID)
  273. fmt.Printf("Name: %s\n", result.CreateRole.Name)
  274. return nil
  275. }
  276. func roleUpdate(ctx context.Context, cmd *cli.Command) error {
  277. cfg, err := config.Load()
  278. if err != nil {
  279. return err
  280. }
  281. if err := RequireAuth(cfg); err != nil {
  282. return err
  283. }
  284. id := cmd.String("id")
  285. name := cmd.String("name")
  286. description := cmd.String("description")
  287. permissions := cmd.StringSlice("permissions")
  288. if name == "" && description == "" && len(permissions) == 0 {
  289. fmt.Println("No updates provided. Use flags to specify what to update.")
  290. return nil
  291. }
  292. c := client.New(cfg.ServerURL)
  293. c.SetToken(cfg.Token)
  294. input := make(map[string]interface{})
  295. if name != "" {
  296. input["name"] = name
  297. }
  298. if description != "" {
  299. input["description"] = description
  300. }
  301. if len(permissions) > 0 {
  302. input["permissions"] = permissions
  303. }
  304. mutation := `mutation UpdateRole($id: ID!, $input: UpdateRoleInput!) { updateRole(id: $id, input: $input) { id name description permissions { id code } } }`
  305. resp, err := c.Mutation(mutation, map[string]interface{}{"id": id, "input": input})
  306. if err != nil {
  307. return err
  308. }
  309. var result struct {
  310. UpdateRole *RoleDetail `json:"updateRole"`
  311. }
  312. if err := json.Unmarshal(resp.Data, &result); err != nil {
  313. return err
  314. }
  315. if result.UpdateRole == nil {
  316. return fmt.Errorf("role not found")
  317. }
  318. fmt.Printf("Role updated successfully!\n")
  319. fmt.Printf("ID: %s\n", result.UpdateRole.ID)
  320. fmt.Printf("Name: %s\n", result.UpdateRole.Name)
  321. return nil
  322. }
  323. func roleDelete(ctx context.Context, cmd *cli.Command) error {
  324. cfg, err := config.Load()
  325. if err != nil {
  326. return err
  327. }
  328. if err := RequireAuth(cfg); err != nil {
  329. return err
  330. }
  331. id := cmd.String("id")
  332. skipConfirm := cmd.Bool("yes")
  333. if !skipConfirm {
  334. confirm := false
  335. prompt := &survey.Confirm{
  336. Message: fmt.Sprintf("Are you sure you want to delete role %s?", id),
  337. Default: false,
  338. }
  339. if err := survey.AskOne(prompt, &confirm); err != nil {
  340. return err
  341. }
  342. if !confirm {
  343. fmt.Println("Deletion cancelled.")
  344. return nil
  345. }
  346. }
  347. c := client.New(cfg.ServerURL)
  348. c.SetToken(cfg.Token)
  349. mutation := `mutation DeleteRole($id: ID!) { deleteRole(id: $id) }`
  350. resp, err := c.Mutation(mutation, map[string]interface{}{"id": id})
  351. if err != nil {
  352. return err
  353. }
  354. var result struct {
  355. DeleteRole bool `json:"deleteRole"`
  356. }
  357. if err := json.Unmarshal(resp.Data, &result); err != nil {
  358. return err
  359. }
  360. if result.DeleteRole {
  361. fmt.Printf("Role %s deleted successfully.\n", id)
  362. } else {
  363. fmt.Printf("Failed to delete role %s.\n", id)
  364. }
  365. return nil
  366. }