crossplane
85 строк · 2.4 Кб
1/*
2Copyright 2023 The Crossplane Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package xpkg
18
19import (
20"context"
21"fmt"
22"net/http"
23
24"github.com/alecthomas/kong"
25"github.com/upbound/up-sdk-go"
26
27"github.com/crossplane/crossplane-runtime/pkg/errors"
28
29"github.com/crossplane/crossplane/internal/xpkg/upbound"
30)
31
32const (
33logoutPath = "/v1/logout"
34
35errLogoutFailed = "unable to logout"
36errRemoveTokenFailed = "failed to remove token"
37)
38
39// AfterApply sets default values in login after assignment and validation.
40func (c *logoutCmd) AfterApply(kongCtx *kong.Context) error {
41upCtx, err := upbound.NewFromFlags(c.Flags)
42if err != nil {
43return err
44}
45kongCtx.Bind(upCtx)
46cfg, err := upCtx.BuildSDKConfig()
47if err != nil {
48return err
49}
50c.client = cfg.Client
51return nil
52}
53
54// logoutCmd invalidates a stored session token for a given profile.
55type logoutCmd struct {
56// Common Upbound API configuration
57Flags upbound.Flags `embed:""`
58
59// Internal state. These aren't part of the user-exposed CLI structure.
60client up.Client
61}
62
63// Run executes the logout command.
64func (c *logoutCmd) Run(k *kong.Context, upCtx *upbound.Context) error {
65ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
66defer cancel()
67req, err := c.client.NewRequest(ctx, http.MethodPost, logoutPath, "", nil)
68if err != nil {
69return errors.Wrap(err, errLogoutFailed)
70}
71if err := c.client.Do(req, nil); err != nil {
72return errors.Wrap(err, errLogoutFailed)
73}
74// Logout is successful, remove token from config and update.
75upCtx.Profile.Session = ""
76if err := upCtx.Cfg.AddOrUpdateUpboundProfile(upCtx.ProfileName, upCtx.Profile); err != nil {
77return errors.Wrap(err, errRemoveTokenFailed)
78}
79if err := upCtx.CfgSrc.UpdateConfig(upCtx.Cfg); err != nil {
80return errors.Wrap(err, "failed to update config file")
81}
82
83_, _ = fmt.Fprintf(k.Stdout, "%s logged out.\n", upCtx.Profile.ID)
84return nil
85}
86