go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/lucictx/local_auth.go (about) 1 // Copyright 2016 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package lucictx 16 17 import ( 18 "context" 19 20 "go.chromium.org/luci/common/errors" 21 ) 22 23 // ErrNoLocalAuthAccount is returned by SwitchLocalAccount if requested account 24 // is not available in the LUCI_CONTEXT. 25 var ErrNoLocalAuthAccount = errors.New("the requested logical account is not present in LUCI_CONTEXT") 26 27 // GetLocalAuth calls Lookup and returns a copy of the current LocalAuth from 28 // LUCI_CONTEXT if it was present. If no LocalAuth is in the context, this 29 // returns nil. 30 func GetLocalAuth(ctx context.Context) *LocalAuth { 31 ret := LocalAuth{} 32 ok, err := Lookup(ctx, "local_auth", &ret) 33 if err != nil { 34 panic(err) 35 } 36 if !ok { 37 return nil 38 } 39 return &ret 40 } 41 42 // SetLocalAuth sets the LocalAuth in the LUCI_CONTEXT. 43 func SetLocalAuth(ctx context.Context, la *LocalAuth) context.Context { 44 return Set(ctx, "local_auth", la) 45 } 46 47 // SwitchLocalAccount changes default logical account selected in the context. 48 // 49 // For example, it can be used to switch the context into using "system" account 50 // by default. The default account is transparently used by LUCI-aware tools. 51 // 52 // If the requested account is available, modifies LUCI_CONTEXT["local_auth"] 53 // in the context and returns the new modified context. 54 // 55 // If the given account is already default, returns the context unchanged. 56 // 57 // If the given account is not available, returns (nil, ErrNoLocalAuthAccount). 58 func SwitchLocalAccount(ctx context.Context, accountID string) (context.Context, error) { 59 if la := GetLocalAuth(ctx); la != nil { 60 if la.DefaultAccountId == accountID { 61 return ctx, nil 62 } 63 for _, acc := range la.Accounts { 64 if acc.Id == accountID { 65 la.DefaultAccountId = accountID 66 return SetLocalAuth(ctx, la), nil 67 } 68 } 69 } 70 return nil, ErrNoLocalAuthAccount 71 }