// CreateAuth corresponds to the POST /tokens/auth endpoint.
//
// Exchange a login token for a general use auth token
182680
func (c *TokensClient) CreateAuth(ctx context.Context, authorization string, authTokenRequest *AuthTokenRequest) (*AuthToken, error) {
	p := "/tokens/auth"

	req, err := c.backend.NewRequest(http.MethodPost, p, nil, authTokenRequest)
	if err != nil {
		return nil, err
	}

	req.Header.Set("authorization", authorization)

	var resp AuthToken
	_, err = c.backend.Do(ctx, req, &resp, func(code int) error {
		return &Error{}
	})
	if err != nil {
		return nil, err
	}

	return &resp, nil
}
1197704
func CreateAuthMiddleware() (*jwt.Middleware, error) {
	err := variables.LoadTokenKeys()
	if err != nil {
		return nil, err
	}

	authMiddleware := &jwt.Middleware{
		Realm:            "numapp",
		SigningAlgorithm: variables.SigningAlgorithm,
		Key:              variables.TokenSignKey,
		VerifyKey:        variables.TokenVerifyKey,
		Timeout:          time.Hour,
		MaxRefresh:       time.Hour * 24,
		Authenticator: func(username string, password string) error {
			return errors.New("This message should never be seen")
		},
	}
	return authMiddleware, nil
}
1350726
func (m *Middleware) CreateToken(identity string) (string, error) {
	// For now, the header will be static
	header, err := encode(fmt.Sprintf(`{"typ":%q,"alg":%q}`, typ, alg))
	if err != nil {
		return "encoding header", ErrEncoding
	}

	// Generate claims for user
	claims, err := m.claims(identity)
	if err != nil {
		return "generating claims", err
	}

	claimsJSON, err := json.Marshal(claims)
	if err != nil {
		return "mashalling claims", ErrEncoding
	}

	claimsSet, err := encode(claimsJSON)
	if err != nil {
		return "encoding claims", ErrEncoding
	}

	toSig := strings.Join([]string{header, claimsSet}, ".")

	h := hmac.New(sha256.New, []byte(m.secret))
	h.Write([]byte(toSig))
	sig, err := encode(h.Sum(nil))
	if err != nil {
		return "encoding signature", ErrEncoding
	}

	response := strings.Join([]string{toSig, sig}, ".")
	return response, nil
}
882145
func (issuer *TokenIssuer) CreateJWT(subject string, audience string, grantedAccessList []auth.Access) (string, error) {
	// Make a set of access entries to put in the token's claimset.
	resourceActionSets := make(map[auth.Resource]map[string]struct{}, len(grantedAccessList))
	for _, access := range grantedAccessList {
		actionSet, exists := resourceActionSets[access.Resource]
		if !exists {
			actionSet = map[string]struct{}{}
			resourceActionSets[access.Resource] = actionSet
		}
		actionSet[access.Action] = struct{}{}
	}

	accessEntries := make([]*token.ResourceActions, 0, len(resourceActionSets))
	for resource, actionSet := range resourceActionSets {
		actions := make([]string, 0, len(actionSet))
		for action := range actionSet {
			actions = append(actions, action)
		}

		accessEntries = append(accessEntries, &token.ResourceActions{
			Type:    resource.Type,
			Class:   resource.Class,
			Name:    resource.Name,
			Actions: actions,
		})
	}

	randomBytes := make([]byte, 15)
	_, err := io.ReadFull(rand.Reader, randomBytes)
	if err != nil {
		return "", err
	}
	randomID := base64.URLEncoding.EncodeToString(randomBytes)

	now := time.Now()

	signingHash := crypto.SHA256
	var alg string
	switch issuer.SigningKey.KeyType() {
	case "RSA":
		alg = "RS256"
	case "EC":
		alg = "ES256"
	default:
		panic(fmt.Errorf("unsupported signing key type %q", issuer.SigningKey.KeyType()))
	}

	joseHeader := token.Header{
		Type:       "JWT",
		SigningAlg: alg,
	}

	if x5c := issuer.SigningKey.GetExtendedField("x5c"); x5c != nil {
		joseHeader.X5c = x5c.([]string)
	} else {
		var jwkMessage json.RawMessage
		jwkMessage, err = issuer.SigningKey.PublicKey().MarshalJSON()
		if err != nil {
			return "", err
		}
		joseHeader.RawJWK = &jwkMessage
	}

	exp := issuer.Expiration
	if exp == 0 {
		exp = 5 * time.Minute
	}

	claimSet := token.ClaimSet{
		Issuer:     issuer.Issuer,
		Subject:    subject,
		Audience:   audience,
		Expiration: now.Add(exp).Unix(),
		NotBefore:  now.Unix(),
		IssuedAt:   now.Unix(),
		JWTID:      randomID,

		Access: accessEntries,
	}

	var (
		joseHeaderBytes []byte
		claimSetBytes   []byte
	)

	if joseHeaderBytes, err = json.Marshal(joseHeader); err != nil {
		return "", fmt.Errorf("unable to encode jose header: %s", err)
	}
	if claimSetBytes, err = json.Marshal(claimSet); err != nil {
		return "", fmt.Errorf("unable to encode claim set: %s", err)
	}

	encodedJoseHeader := joseBase64Encode(joseHeaderBytes)
	encodedClaimSet := joseBase64Encode(claimSetBytes)
	encodingToSign := fmt.Sprintf("%s.%s", encodedJoseHeader, encodedClaimSet)

	var signatureBytes []byte
	if signatureBytes, _, err = issuer.SigningKey.Sign(strings.NewReader(encodingToSign), signingHash); err != nil {
		return "", fmt.Errorf("unable to sign jwt payload: %s", err)
	}

	signature := joseBase64Encode(signatureBytes)

	return fmt.Sprintf("%s.%s", encodingToSign, signature), nil
}
146008
func (a *Account) CreateOAuthClient(client *OAuthClient) (c *OAuthClient, err error) {
	err = a.post(a.auth.WithScope(scope.Clients), "/api/v2/clients", client, &c)
	return c, err
}
570319
func NewRequestAuth(req *http.Request, creds *Credentials, tsOffset time.Duration) *Auth {
	auth := &Auth{
		Method:      req.Method,
		Credentials: *creds,
		Timestamp:   Now().Add(tsOffset),
		Nonce:       nonce(),
		RequestURI:  req.URL.RequestURI(),
	}
	auth.Host, auth.Port = extractReqHostPort(req)
	return auth
}
798560
func (c *Client) CreateAuthorization(opts CreateAuthorizationOptions) (*Authorization, error) {
	f := struct {
		Scopes       []string `json:"scopes"`
		ClientID     string   `json:"client_id"`
		ClientSecret string   `json:"client_secret"`
	}{
		Scopes:       c.Scopes,
		ClientID:     c.ClientID,
		ClientSecret: c.ClientSecret,
	}

	req, err := c.NewRequest("POST", "/authorizations", f)
	if err != nil {
		return nil, err
	}

	req.SetBasicAuth(opts.Username, opts.Password)

	// If a two factor auth code is present, set the `X-GitHub-OTP` header
	// value. See http://goo.gl/Lumn6s.
	if opts.OTP != "" {
		req.Header.Set(HeaderTwoFactor, opts.OTP)
	}

	var a Authorization
	resp, err := c.Do(req, &a)
	if err != nil {
		if resp != nil && resp.StatusCode == 401 {
			// When the `X-GitHub-OTP` header is present in the response, it means
			// a two factor auth code needs to be provided.
			if resp.Header.Get(HeaderTwoFactor) != "" {
				return nil, errTwoFactor
			}

			return nil, errUnauthorized
		}

		return nil, err
	}

	if a.Token == "" {
		return nil, errNoToken
	}

	return &a, nil
}
892433
func (auth *Auth) CreateUser(ctx context.Context, user *User) (string, error) {
	var err error
	var userID string

	if len(user.UserID) == 0 {
		userID, err = auth.createUserAutoID(ctx, user)
	} else {
		userID = user.UserID
		err = auth.createUserCustomID(ctx, user)
	}
	if err != nil {
		return "", err
	}
	return userID, nil
}
667187
func (s *AuthorizationService) CreateAuthorization(ctx context.Context, a *platform.Authorization) (err error) {
	defer func() {
		if err != nil {
			s.Logger.Info("error creating authorization", zap.Error(err))
		}
	}()

	return s.AuthorizationService.CreateAuthorization(ctx, a)
}
373512
func (s *AuthorizationsService) Create(ctx context.Context, auth *AuthorizationRequest) (*Authorization, *Response, error) {
	u := "authorizations"

	req, err := s.client.NewRequest("POST", u, auth)
	if err != nil {
		return nil, nil, err
	}

	a := new(Authorization)
	resp, err := s.client.Do(ctx, req, a)
	if err != nil {
		return nil, resp, err
	}
	return a, resp, nil
}
92070
func (c *FakeOAuthAuthorizeTokens) Create(oAuthAuthorizeToken *oauth.OAuthAuthorizeToken) (result *oauth.OAuthAuthorizeToken, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(oauthauthorizetokensResource, oAuthAuthorizeToken), &oauth.OAuthAuthorizeToken{})
	if obj == nil {
		return nil, err
	}
	return obj.(*oauth.OAuthAuthorizeToken), err
}
1080562
func (s *Server) Create(ctx context.Context, q *SessionCreateRequest) (*SessionResponse, error) {
	if q.Token != "" {
		return nil, status.Errorf(codes.Unauthenticated, "token-based session creation no longer supported. please upgrade argocd cli to v0.7+")
	}
	if q.Username == "" || q.Password == "" {
		return nil, status.Errorf(codes.Unauthenticated, "no credentials supplied")
	}
	err := s.mgr.VerifyUsernamePassword(q.Username, q.Password)
	if err != nil {
		return nil, err
	}
	jwtToken, err := s.mgr.Create(q.Username, 0)
	if err != nil {
		return nil, err
	}
	return &SessionResponse{Token: jwtToken}, nil
}
627756
func (c *UsersClient) CreateForgotPasswordToken(ctx context.Context, forgotPasswordCreate *ForgotPasswordCreate) error {
	p := "/users/forgot-password/token"

	req, err := c.backend.NewRequest(http.MethodPost, p, nil, forgotPasswordCreate)
	if err != nil {
		return err
	}

	_, err = c.backend.Do(ctx, req, nil, func(code int) error {
		return &Error{}
	})
	if err != nil {
		return err
	}

	return nil
}
1055347
func CreateAuthMiddleware() (*jwt.Middleware, error) {
	err := variables.LoadTokenKeys()
	if err != nil {
		return nil, err
	}

	authMiddleware := &jwt.Middleware{
		Realm:            "numapp",
		SigningAlgorithm: variables.SigningAlgorithm,
		Key:              variables.TokenSignKey,
		VerifyKey:        &variables.TokenSignKey.PublicKey,
		Timeout:          time.Hour,
		MaxRefresh:       time.Hour * 24,
		Authenticator: func(username string, password string) error {
			// Log the user in
			err := login.Login(username, password)
			if err != nil {
				return err
			}
			return nil
		},
	}
	return authMiddleware, nil
}
825667
func (auth *Auth) CreateUser(email, first, last, clear string) (User, error) {
	return auth.users.Create(email, first, last, clear)
}
179739
func (c *Client) OAuthClientCreate(name string, redirectUri string) (*OAuthClient, error) {
	params := struct {
		Name        string `json:"name"`
		RedirectUri string `json:"redirect_uri"`
	}{
		Name:        name,
		RedirectUri: redirectUri,
	}
	var oauthClientRes OAuthClient
	return &oauthClientRes, c.Post(&oauthClientRes, "/oauth/clients", params)
}
461663
func Login(c *client.Client, username, password string) (string, error) {
	user := api.AuthLoginRequest{Username: username, Password: password}
	reqBody, err := json.Marshal(user)

	if err != nil {
		return "", err
	}

	body, err := c.BasicRequest("POST", "/v1/auth/login/", reqBody)

	if err != nil {
		return "", err
	}

	token := api.AuthLoginResponse{}
	if err = json.Unmarshal([]byte(body), &token); err != nil {
		return "", err
	}

	return token.Token, nil
}