// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode
// that can be used with CheckForUserCompletion or WaitForUserCompletion.
426769
func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) {
	v := url.Values{
		"client_id": []string{clientID},
		"resource":  []string{resource},
	}

	s := v.Encode()
	body := ioutil.NopCloser(strings.NewReader(s))

	req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body)
	if err != nil {
		return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error())
	}

	req.ContentLength = int64(len(s))
	req.Header.Set(contentType, mimeTypeFormPost)
	resp, err := sender.Do(req)
	if err != nil {
		return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error())
	}
	defer resp.Body.Close()

	rb, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error())
	}

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK)
	}

	if len(strings.Trim(string(rb), " ")) == 0 {
		return nil, ErrDeviceCodeEmpty
	}

	var code DeviceCode
	err = json.Unmarshal(rb, &code)
	if err != nil {
		return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error())
	}

	code.ClientID = clientID
	code.Resource = resource
	code.OAuthConfig = oauthConfig

	return &code, nil
}
1114217
func (a *ActiveDevice) DeviceID() keybase1.DeviceID {
	a.RLock()
	defer a.RUnlock()
	return a.deviceID
}
1348275
func CreateSnapDevice(poolName string, deviceID int, baseName string, baseDeviceID int) error {
	devinfo, _ := GetInfo(baseName)
	doSuspend := devinfo != nil && devinfo.Exists != 0

	if doSuspend {
		if err := SuspendDevice(baseName); err != nil {
			return err
		}
	}

	if err := CreateSnapDeviceRaw(poolName, deviceID, baseDeviceID); err != nil {
		if doSuspend {
			if err2 := ResumeDevice(baseName); err2 != nil {
				return fmt.Errorf("CreateSnapDeviceRaw Error: (%v): ResumeDevice Error: (%v)", err, err2)
			}
		}
		return err
	}

	if doSuspend {
		if err := ResumeDevice(baseName); err != nil {
			return err
		}
	}

	return nil
}
799036
func (p *PoolDevice) createDevice(ctx context.Context, info *DeviceInfo) error {
	if err := p.transition(ctx, info.Name, Creating, Created, func() error {
		return dmsetup.CreateDevice(p.poolName, info.DeviceID)
	}); err != nil {
		return errors.Wrapf(err, "failed to create new thin device %q (dev: %d)", info.Name, info.DeviceID)
	}

	return nil
}
630027
func createDeviceNode(rootfs string, node *configs.Device, bind bool) error {
	dest := filepath.Join(rootfs, node.Path)
	if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
		return err
	}

	if bind {
		return bindMountDeviceNode(dest, node)
	}
	if err := mknodDevice(dest, node); err != nil {
		if os.IsExist(err) {
			return nil
		} else if os.IsPermission(err) {
			return bindMountDeviceNode(dest, node)
		}
		return err
	}
	return nil
}
296888
func (p *PoolDevice) DeactivateDevice(ctx context.Context, deviceName string, deferred bool) error {
	if !p.IsActivated(deviceName) {
		return nil
	}

	opts := []dmsetup.RemoveDeviceOpt{dmsetup.RemoveWithForce, dmsetup.RemoveWithRetries}
	if deferred {
		opts = append(opts, dmsetup.RemoveDeferred)
	}

	if err := p.transition(ctx, deviceName, Deactivating, Deactivated, func() error {
		return dmsetup.RemoveDevice(deviceName, opts...)
	}); err != nil {
		return errors.Wrapf(err, "failed to deactivate device %q", deviceName)
	}

	return nil
}
1199269
func (a *Authenticator) ensureInitialized() error {
	// Already initialized (successfully or not)?
	if initialized, err := a.checkInitialized(); initialized {
		return err
	}

	// SelectBestMethod may do heavy calls like talking to GCE metadata server,
	// call it lazily here rather than in NewAuthenticator.
	if a.opts.Method == AutoSelectMethod {
		a.opts.Method = SelectBestMethod(a.ctx, *a.opts)
	}

	// In Actor mode, make the base token IAM-scoped, to be able to use SignBlob
	// API. In non-actor mode, the base token is also the main auth token, so
	// scope it to whatever options were requested.
	scopes := a.opts.Scopes
	if a.isActing() {
		scopes = []string{iam.OAuthScope}
	}
	a.baseToken = &tokenWithProvider{}
	a.baseToken.provider, a.err = makeBaseTokenProvider(a.ctx, a.opts, scopes)
	if a.err != nil {
		return a.err // note: this can be ErrInsufficientAccess
	}

	// In non-actor mode, the token we must check in 'CheckLoginRequired' is the
	// same as returned by 'GetAccessToken'. In actor mode, they are different.
	// See comments for 'baseToken' and 'authToken'.
	if a.isActing() {
		a.authToken = &tokenWithProvider{}
		a.authToken.provider, a.err = makeIAMTokenProvider(a.ctx, a.opts)
		if a.err != nil {
			return a.err
		}
	} else {
		a.authToken = a.baseToken
	}

	// Initialize the token cache. Use the disk cache only if SecretsDir is given
	// and any of the providers is not "lightweight" (so it makes sense to
	// actually hit the disk, rather then call the provider each time new token is
	// needed).
	//
	// Note also that tests set a.testingCache before ensureInitialized() is
	// called to mock the cache. Respect this.
	if a.testingCache != nil {
		a.baseToken.cache = a.testingCache
		a.authToken.cache = a.testingCache
	} else {
		cache := internal.ProcTokenCache
		if !a.baseToken.provider.Lightweight() || !a.authToken.provider.Lightweight() {
			if a.opts.SecretsDir != "" {
				cache = &internal.DiskTokenCache{
					Context:    a.ctx,
					SecretsDir: a.opts.SecretsDir,
				}
			} else {
				logging.Warningf(a.ctx, "Disabling auth disk token cache. Not configured.")
			}
		}
		// Use the disk cache only for non-lightweight providers to avoid
		// unnecessarily leaks of tokens to the disk.
		if a.baseToken.provider.Lightweight() {
			a.baseToken.cache = internal.ProcTokenCache
		} else {
			a.baseToken.cache = cache
		}
		if a.authToken.provider.Lightweight() {
			a.authToken.cache = internal.ProcTokenCache
		} else {
			a.authToken.cache = cache
		}
	}

	// Interactive providers need to know whether there's a cached token (to ask
	// to run interactive login if there's none). Non-interactive providers do not
	// care about state of the cache that much (they know how to update it
	// themselves). So examine the cache here only when using interactive
	// provider. Non interactive providers will do it lazily on a first
	// refreshToken(...) call.
	if a.baseToken.provider.RequiresInteraction() {
		// Broken token cache is not a fatal error. So just log it and forget, a new
		// token will be minted in Login.
		if err := a.baseToken.fetchFromCache(a.ctx); err != nil {
			logging.Warningf(a.ctx, "Failed to read auth token from cache: %s", err)
		}
	}

	// Note: a.authToken.provider is either equal to a.baseToken.provider (if not
	// using actor mode), or (when using actor mode) it doesn't require
	// interaction (because it is an IAM one). So don't bother with fetching
	// 'authToken' from cache. It will be fetched lazily on the first use.

	return nil
}
627106
func NewRevokeDeviceSessionStatus(Success bool) *RevokeDeviceSessionStatus {
	s := new(RevokeDeviceSessionStatus)
	s.Success = Success
	return s
}
310642
func CreateDeviceProfileCache(p *redis.Pool, dp DeviceProfile) error {
	var buf bytes.Buffer
	if err := gob.NewEncoder(&buf).Encode(dp); err != nil {
		return errors.Wrap(err, "gob encode device-profile error")
	}

	c := p.Get()
	defer c.Close()

	key := fmt.Sprintf(DeviceProfileKeyTempl, dp.ID)
	exp := int64(deviceSessionTTL) / int64(time.Millisecond)

	_, err := c.Do("PSETEX", key, exp, buf.Bytes())
	if err != nil {
		return errors.Wrap(err, "set device-profile error")
	}

	return nil
}
894182
func (c *SQLiteConn) AuthEnabled() (exists bool) {
	rv := c.authEnabled()
	if rv == 1 {
		exists = true
	}

	return
}
1115081
func (s *DomainsService) InitiatePush(accountID, domainID string, pushAttributes DomainPushAttributes) (*domainPushResponse, error) {
	path := versioned(fmt.Sprintf("/%v/pushes", domainPath(accountID, domainID)))
	pushResponse := &domainPushResponse{}

	resp, err := s.client.post(path, pushAttributes, pushResponse)
	if err != nil {
		return nil, err
	}

	pushResponse.HttpResponse = resp
	return pushResponse, nil
}
819182
func (n *NetworkServerAPI) GetDeviceActivation(ctx context.Context, req *ns.GetDeviceActivationRequest) (*ns.GetDeviceActivationResponse, error) {
	var devEUI lorawan.EUI64
	copy(devEUI[:], req.DevEui)

	ds, err := storage.GetDeviceSession(storage.RedisPool(), devEUI)
	if err != nil {
		return nil, errToRPCError(err)
	}

	return &ns.GetDeviceActivationResponse{
		DeviceActivation: &ns.DeviceActivation{
			DevEui:        ds.DevEUI[:],
			DevAddr:       ds.DevAddr[:],
			SNwkSIntKey:   ds.SNwkSIntKey[:],
			FNwkSIntKey:   ds.FNwkSIntKey[:],
			NwkSEncKey:    ds.NwkSEncKey[:],
			FCntUp:        ds.FCntUp,
			NFCntDown:     ds.NFCntDown,
			AFCntDown:     ds.AFCntDown,
			SkipFCntCheck: ds.SkipFCntValidation,
		},
	}, nil
}
879703
func (sp *ServiceProvider) InitiateLogin(w http.ResponseWriter) error {
	acsURL, _ := url.Parse(sp.AcsURL)

	binding := HTTPRedirectBinding
	bindingLocation := sp.GetSSOBindingLocation(binding)
	if bindingLocation == "" {
		binding = HTTPPostBinding
		bindingLocation = sp.GetSSOBindingLocation(binding)
	}

	req, err := sp.MakeAuthenticationRequest(bindingLocation)
	if err != nil {
		return err
	}

	relayState := base64.URLEncoding.EncodeToString(randomBytes(42))
	state := jwt.New(jwt.GetSigningMethod("HS256"))
	claims := state.Claims.(jwt.MapClaims)
	claims["id"] = req.ID
	signedState, err := state.SignedString(sp.cookieSecret())
	if err != nil {
		return err
	}

	http.SetCookie(w, &http.Cookie{
		Name:     fmt.Sprintf("saml_%s", relayState),
		Value:    signedState,
		MaxAge:   int(MaxIssueDelay.Seconds()),
		HttpOnly: false,
		Path:     acsURL.Path,
	})

	if binding == HTTPRedirectBinding {
		redirectURL := req.Redirect(relayState)
		w.Header().Add("Location", redirectURL.String())
		w.WriteHeader(http.StatusFound)
		return nil
	}
	if binding == HTTPPostBinding {
		w.Header().Set("Content-Security-Policy", ""+
			"default-src; "+
			"script-src 'sha256-D8xB+y+rJ90RmLdP72xBqEEc0NUatn7yuCND0orkrgk='; "+
			"reflected-xss block; "+
			"referrer no-referrer;")
		w.Header().Add("Content-type", "text/html")
		w.Write([]byte(`<!DOCTYPE html><html><body>`))
		w.Write(req.Post(relayState))
		w.Write([]byte(`</body></html>`))
		return nil
	}
	panic("not reached")
}
1159013
func (s *ChildWorkflowExecutionTerminatedEventAttributes) SetInitiatedEventId(v int64) *ChildWorkflowExecutionTerminatedEventAttributes {
	s.InitiatedEventId = &v
	return s
}
319776
func (m *MobileGateway) IPAddressAt(index int) string {
	if len(m.Interfaces) <= index {
		return ""
	}
	if index == 0 {
		return m.Interfaces[0].IPAddress
	}

	ipaddresses := m.Settings.MobileGateway.Interfaces[index].IPAddress
	if len(ipaddresses) < 1 {
		return ""
	}
	return ipaddresses[0]
}
11382
func (authy *Authy) StartPhoneVerification(countryCode int, phoneNumber string, via string, params url.Values) (*PhoneVerificationStart, error) {
	params.Set("country_code", strconv.Itoa(countryCode))
	params.Set("phone_number", phoneNumber)
	params.Set("via", via)

	path := fmt.Sprintf("/protected/json/phones/verification/start")
	response, err := authy.DoRequest("POST", path, params)
	if err != nil {
		return nil, err
	}

	defer closeResponseBody(response)
	return NewPhoneVerificationStart(response)
}
780609
func ActivateDevice(poolName string, deviceName string, deviceID uint32, size uint64, external string) error {
	mapping := makeThinMapping(poolName, deviceID, size, external)
	_, err := dmsetup("create", deviceName, "--table", mapping)
	return err
}