// CreateToken creates a new token to access a project
496147
func (s *Server) CreateToken(ctx context.Context, q *ProjectTokenCreateRequest) (*ProjectTokenResponse, error) {
	if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionUpdate, q.Project); err != nil {
		return nil, err
	}
	project, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Project, metav1.GetOptions{})
	if err != nil {
		return nil, err
	}
	err = projectutil.ValidateProject(project)
	if err != nil {
		return nil, err
	}

	s.projectLock.Lock(q.Project)
	defer s.projectLock.Unlock(q.Project)

	_, index, err := projectutil.GetRoleByName(project, q.Role)
	if err != nil {
		return nil, status.Errorf(codes.NotFound, "project '%s' does not have role '%s'", q.Project, q.Role)
	}

	tokenName := fmt.Sprintf(JWTTokenSubFormat, q.Project, q.Role)
	jwtToken, err := s.sessionMgr.Create(tokenName, q.ExpiresIn)
	if err != nil {
		return nil, status.Error(codes.InvalidArgument, err.Error())
	}
	parser := &jwt.Parser{
		SkipClaimsValidation: true,
	}
	claims := jwt.StandardClaims{}
	_, _, err = parser.ParseUnverified(jwtToken, &claims)
	if err != nil {
		return nil, status.Error(codes.InvalidArgument, err.Error())
	}
	issuedAt := claims.IssuedAt
	expiresAt := claims.ExpiresAt

	project.Spec.Roles[index].JWTTokens = append(project.Spec.Roles[index].JWTTokens, v1alpha1.JWTToken{IssuedAt: issuedAt, ExpiresAt: expiresAt})
	_, err = s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Update(project)
	if err != nil {
		return nil, err
	}
	s.logEvent(project, ctx, argo.EventReasonResourceCreated, "created token")
	return &ProjectTokenResponse{Token: jwtToken}, nil

}
1078352
func CreateToken(t testing.T, state StateStore, index uint64, policies []string) *structs.ACLToken {
	t.Helper()

	// Create the ACLToken
	token := ACLToken()
	token.Policies = policies
	token.SetHash()
	assert.Nil(t, state.UpsertACLTokens(index, []*structs.ACLToken{token}))
	return token
}
1334956
func (cs ClientsService) Create(client Client, secret, token string) error {
	_, err := newNetworkClient(cs.config).MakeRequest(network.Request{
		Method:        "POST",
		Path:          "/oauth/clients",
		Authorization: network.NewTokenAuthorization(token),
		Body:          network.NewJSONRequestBody(client.toDocument(secret)),
		AcceptableStatusCodes: []int{http.StatusCreated},
	})
	if err != nil {
		return translateError(err)
	}

	return nil
}
1193659
func (m *GormExternalTokenRepository) Create(ctx context.Context, model *ExternalToken) error {
	defer goa.MeasureSince([]string{"goa", "db", "ExternalToken", "create"}, time.Now())
	if model.ID == uuid.Nil {
		model.ID = uuid.NewV4()
	}
	err := m.db.Create(model).Error
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"external_token_id": model.ID,
			"err":               err,
		}, "unable to create the external_token")
		return errs.WithStack(err)
	}
	log.Info(ctx, map[string]interface{}{
		"external_token_id": model.ID,
	}, "external_token created!")
	return nil
}
648822
func (s *GetCampaignsInput) SetToken(v string) *GetCampaignsInput {
	s.Token = &v
	return s
}
427595
func (m *Machine) CreateToken(ctx context.Context, notifier *observer.Notifier,
	machine *envelope.Machine, secret *base64.Value) (*registry.MachineTokenCreationSegment, error) {
	n := notifier.Notifier(2)

	n.Notify(observer.Progress, "Generating machine token", true)
	salt, err := crypto.GenerateSalt(ctx)
	if err != nil {
		return nil, err
	}

	keypair, err := crypto.DeriveLoginKeypair(ctx, *secret, salt)
	if err != nil {
		return nil, err
	}

	orgID := machine.Body.OrgID

	masterKey, err := crypto.CreateMasterKeyObject(ctx, *secret, nil)
	if err != nil {
		return nil, err
	}

	tokenBody := &primitive.MachineToken{
		OrgID:     orgID,
		MachineID: machine.ID,
		PublicKey: &primitive.LoginPublicKey{
			Salt:  keypair.Salt(),
			Value: keypair.PublicKey(),
			Alg:   crypto.EdDSA,
		},
		Master:      masterKey,
		CreatedBy:   m.engine.session.ID(),
		Created:     time.Now().UTC(),
		DestroyedBy: nil,
		Destroyed:   nil,
		State:       primitive.MachineTokenActiveState,
	}
	tokenID, err := identity.NewMutable(tokenBody)
	if err != nil {
		return nil, err
	}

	token := &envelope.MachineToken{
		ID:      &tokenID,
		Version: 1,
		Body:    tokenBody,
	}

	// Create an "empty" machine session in order to create a Crypto engine on
	// behalf of the machine for deriving and uploading these keys.
	sess := session.NewSession(m.engine.guard)
	err = sess.Set(apitypes.MachineSession, machine, token, *secret, []byte("hello"))
	if err != nil {
		return nil, err
	}
	c := crypto.NewEngine(sess, m.engine.guard)

	n.Notify(observer.Progress, "Generating token keypairs", true)
	kp, err := c.GenerateKeyPairs(ctx)
	if err != nil {
		log.Printf("Error generating machine keypairs: %s", err)
		return nil, err
	}

	authID := sess.AuthID()
	keypairs, err := generateKeypairs(ctx, c, orgID, authID, kp)
	if err != nil {
		return nil, err
	}

	return &registry.MachineTokenCreationSegment{
		Token:    token,
		Keypairs: keypairs,
	}, nil
}
422569
func (s *ActionExecution) SetToken(v string) *ActionExecution {
	s.Token = &v
	return s
}
1001795
func (c *FakeOAuthAccessTokens) Create(oAuthAccessToken *oauth.OAuthAccessToken) (result *oauth.OAuthAccessToken, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(oauthaccesstokensResource, oAuthAccessToken), &oauth.OAuthAccessToken{})
	if obj == nil {
		return nil, err
	}
	return obj.(*oauth.OAuthAccessToken), err
}
1251366
func (a *ACLTokens) Create(token *ACLToken, q *WriteOptions) (*ACLToken, *WriteMeta, error) {
	if token.AccessorID != "" {
		return nil, nil, fmt.Errorf("cannot specify Accessor ID")
	}
	var resp ACLToken
	wm, err := a.client.write("/v1/acl/token", token, &resp, q)
	if err != nil {
		return nil, nil, err
	}
	return &resp, wm, 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
}
790727
func (c *projects) Create(projectResource *project.Project) (result *project.Project, err error) {
	result = &project.Project{}
	err = c.client.Post().
		Resource("projects").
		Body(projectResource).
		Do().
		Into(result)
	return
}
1354100
func (s *GetCampaignActivitiesInput) SetToken(v string) *GetCampaignActivitiesInput {
	s.Token = &v
	return s
}
1310260
func (m *GormTokenRepository) Create(ctx context.Context, token *Token) error {
	defer goa.MeasureSince([]string{"goa", "db", "token", "create"}, time.Now())

	// If no identifier has been specified for the new token, then generate one
	if token.TokenID == uuid.Nil {
		token.TokenID = uuid.NewV4()
	}

	err := m.db.Create(token).Error
	if err != nil {
		if gormsupport.IsUniqueViolation(err, "token_pkey") {
			return errors.NewDataConflictError(fmt.Sprintf("token with ID %s already exists", token.TokenID))
		}

		log.Error(ctx, map[string]interface{}{
			"token_id": token.TokenID,
			"err":      err,
		}, "unable to create the token")
		return errs.WithStack(err)
	}

	log.Info(ctx, map[string]interface{}{
		"token_id": token.TokenID,
	}, "Token created!")
	return nil
}
1337604
func (as *AuthServer) CreateToken(ar *authRequest, ares []authzResult) (string, error) {
	now := time.Now().Unix()
	tc := &as.config.Token

	// Sign something dummy to find out which algorithm is used.
	_, sigAlg, err := tc.privateKey.Sign(strings.NewReader("dummy"), 0)
	if err != nil {
		return "", fmt.Errorf("failed to sign: %s", err)
	}
	header := token.Header{
		Type:       "JWT",
		SigningAlg: sigAlg,
		KeyID:      tc.publicKey.KeyID(),
	}
	headerJSON, err := json.Marshal(header)
	if err != nil {
		return "", fmt.Errorf("failed to marshal header: %s", err)
	}

	claims := token.ClaimSet{
		Issuer:     tc.Issuer,
		Subject:    ar.Account,
		Audience:   ar.Service,
		NotBefore:  now - 10,
		IssuedAt:   now,
		Expiration: now + tc.Expiration,
		JWTID:      fmt.Sprintf("%d", rand.Int63()),
		Access:     []*token.ResourceActions{},
	}
	for _, a := range ares {
		ra := &token.ResourceActions{
			Type:    a.scope.Type,
			Name:    a.scope.Name,
			Actions: a.autorizedActions,
		}
		if ra.Actions == nil {
			ra.Actions = []string{}
		}
		sort.Strings(ra.Actions)
		claims.Access = append(claims.Access, ra)
	}
	claimsJSON, err := json.Marshal(claims)
	if err != nil {
		return "", fmt.Errorf("failed to marshal claims: %s", err)
	}

	payload := fmt.Sprintf("%s%s%s", joseBase64UrlEncode(headerJSON), token.TokenSeparator, joseBase64UrlEncode(claimsJSON))

	sig, sigAlg2, err := tc.privateKey.Sign(strings.NewReader(payload), 0)
	if err != nil || sigAlg2 != sigAlg {
		return "", fmt.Errorf("failed to sign token: %s", err)
	}
	glog.Infof("New token for %s %+v: %s", *ar, ar.Labels, claimsJSON)
	return fmt.Sprintf("%s%s%s", payload, token.TokenSeparator, joseBase64UrlEncode(sig)), nil
}
170984
func (ts *TokenStore) createAccessor(ctx context.Context, entry *logical.TokenEntry) error {
	defer metrics.MeasureSince([]string{"token", "createAccessor"}, time.Now())

	var err error
	// Create a random accessor
	entry.Accessor, err = base62.Random(TokenLength)
	if err != nil {
		return err
	}

	tokenNS, err := NamespaceByID(ctx, entry.NamespaceID, ts.core)
	if err != nil {
		return err
	}
	if tokenNS == nil {
		return namespace.ErrNoNamespace
	}

	if tokenNS.ID != namespace.RootNamespaceID {
		entry.Accessor = fmt.Sprintf("%s.%s", entry.Accessor, tokenNS.ID)
	}

	// Create index entry, mapping the accessor to the token ID
	saltCtx := namespace.ContextWithNamespace(ctx, tokenNS)
	saltID, err := ts.SaltID(saltCtx, entry.Accessor)
	if err != nil {
		return err
	}

	aEntry := &accessorEntry{
		TokenID:     entry.ID,
		AccessorID:  entry.Accessor,
		NamespaceID: entry.NamespaceID,
	}

	aEntryBytes, err := jsonutil.EncodeJSON(aEntry)
	if err != nil {
		return errwrap.Wrapf("failed to marshal accessor index entry: {{err}}", err)
	}

	le := &logical.StorageEntry{Key: saltID, Value: aEntryBytes}
	if err := ts.accessorView(tokenNS).Put(ctx, le); err != nil {
		return errwrap.Wrapf("failed to persist accessor index entry: {{err}}", err)
	}
	return nil
}
595065
func (c *Client) OAuthTokenCreate(grant OAuthTokenCreateGrant, client OAuthTokenCreateClient, refreshToken OAuthTokenCreateRefreshToken) (*OAuthToken, error) {
	params := struct {
		Grant        OAuthTokenCreateGrant        `json:"grant"`
		Client       OAuthTokenCreateClient       `json:"client"`
		RefreshToken OAuthTokenCreateRefreshToken `json:"refresh_token"`
	}{
		Grant:        grant,
		Client:       client,
		RefreshToken: refreshToken,
	}
	var oauthTokenRes OAuthToken
	return &oauthTokenRes, c.Post(&oauthTokenRes, "/oauth/tokens", params)
}
1330276
func (s *CreateFileSystemInput) SetCreationToken(v string) *CreateFileSystemInput {
	s.CreationToken = &v
	return s
}