// AccessTokensCreate "creates" the token by jwt signing it and setting the
// Token value.
438491
func (s *Server) AccessTokensCreate(token *AccessToken) (*AccessToken, error) {
	signed, err := signToken(s.Secret, token)
	if err != nil {
		return token, err
	}

	token.Token = signed

	return token, token.IsValid()
}
620718
func CreateWithToken(serverURL, clusterName, userName string, caCert []byte, token string) *clientcmdapi.Config {
	config := CreateBasic(serverURL, clusterName, userName, caCert)
	config.AuthInfos[userName] = &clientcmdapi.AuthInfo{
		Token: token,
	}
	return config
}
981476
func (a *API) CreateToken(token *Token) (*Token, error) {
	dst := new(Token)
	url := a.BuildURL("/v2/agent/token")
	err := a.Post(url, Params{}, token, dst)
	return dst, err
}
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
}
450991
func (s *Service) CreateAuthorization(ctx context.Context, a *platform.Authorization) error {
	op := OpPrefix + platform.OpCreateAuthorization

	_, pErr := s.FindUserByID(ctx, a.UserID)
	if pErr != nil {
		return platform.ErrUnableToCreateToken
	}

	_, pErr = s.FindOrganizationByID(ctx, a.OrgID)
	if pErr != nil {
		return platform.ErrUnableToCreateToken
	}

	var err error
	a.Token, err = s.TokenGenerator.Token()
	if err != nil {
		return &platform.Error{
			Err: err,
			Op:  op,
		}
	}

	a.ID = s.IDGenerator.ID()
	a.Status = platform.Active

	return s.PutAuthorization(ctx, a)
}
1089817
func (c *FakeOAuthClientAuthorizations) Create(oAuthClientAuthorization *oauth.OAuthClientAuthorization) (result *oauth.OAuthClientAuthorization, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(oauthclientauthorizationsResource, oAuthClientAuthorization), &oauth.OAuthClientAuthorization{})
	if obj == nil {
		return nil, err
	}
	return obj.(*oauth.OAuthClientAuthorization), err
}
644280
func (m *Sqlbridge) parseCreate() (*SqlCreate, error) {

	req := NewSqlCreate()
	m.Next() // Consume CREATE token
	req.Raw = m.l.RawInput()

	if m.Cur().T == lex.TokenOr {
		m.Next() // Consume OR
		if m.Next().T != lex.TokenReplace {
			return nil, m.ErrMsg("Expected CREATE OR REPLACE")
		}
		req.OrReplace = true
	}
	// CREATE {DATABASE|SCHEMA|TABLE|VIEW|SOURCE|CONTINUOUSVIEW} <identity>
	switch m.Cur().T {
	case lex.TokenTable, lex.TokenSource, lex.TokenDatabase, lex.TokenSchema:
		req.Tok = m.Next()
	case lex.TokenView, lex.TokenContinuousView:
		req.Tok = m.Next()
		if m.Cur().T != lex.TokenIdentity {
			return nil, m.ErrMsg("Expected CREATE [OR REPLACE] {VIEW|CONTINIOUSVIEW} <identity> AS <select_stmt>")
		}
		req.Identity = m.Next().V

		// Grab remainder which will be SELECT (we have already lexed AS)
		selSQL, _ := m.l.Remainder()

		if m.Next().T != lex.TokenAs {
			return nil, m.ErrMsg("Expected CREATE [OR REPLACE] {VIEW|CONTINIOUSVIEW} <identity> AS <select_stmt>")
		}
		if m.Cur().T != lex.TokenSelect {
			return nil, m.ErrMsg("Expected CREATE [OR REPLACE] {VIEW|CONTINIOUSVIEW} <identity> AS <select_stmt>")
		}

		sel, err := ParseSqlSelect(selSQL)
		if err != nil {
			return nil, err
		}
		req.Select = sel
		return req, nil
	default:
		return nil, m.ErrMsg("Expected view, table, source, schema, database, continuousview for CREATE got")
	}

	// [IF NOT EXISTS]
	if m.Cur().T == lex.TokenIf {
		m.Next() // Consume IF
		if m.Next().T != lex.TokenNegate {
			return nil, m.ErrMsg("Expected CREATE {TABLE|SCHEMA|DATABASE} IF NOT EXISTS <identity>")
		}
		if m.Next().T != lex.TokenExists {
			return nil, m.ErrMsg("Expected CREATE {TABLE|SCHEMA|DATABASE} IF NOT EXISTS <identity>")
		}
		req.IfNotExists = true
	}

	switch m.Cur().T {
	case lex.TokenTable, lex.TokenIdentity:
		req.Identity = m.Next().V
	default:
		return nil, m.ErrMsg("Expected identity after CREATE (TABLE|VIEW|SOURCE|SCHEMA|DATABASE) ")
	}

	switch req.Tok.T {
	case lex.TokenTable:
		discardComments(m)
		if m.Cur().T != lex.TokenLeftParenthesis {
			return nil, m.ErrMsg("Expected (cols) ")
		}
		m.Next() // consume paren

		// list of columns comma separated
		cols, err := m.parseCreateCols()
		if err != nil {
			u.Error(err)
			return nil, err
		}
		req.Cols = cols

		// ENGINE
		discardComments(m)
		if strings.ToLower(m.Cur().V) != "engine" {
			return nil, m.ErrMsg("Expected (cols) ENGINE ... ")
		}
		engine, err := ParseWith(m.SqlTokenPager)
		if err != nil {
			return nil, err
		}
		req.Engine = engine
	case lex.TokenSource:
		// just with
	case lex.TokenSchema:
		// just with for now
	default:
		return nil, fmt.Errorf("not implemented %v", req.Tok.V)
	}

	// WITH
	discardComments(m)
	with, err := ParseWith(m.SqlTokenPager)
	if err != nil {
		return nil, err
	}
	req.With = with

	return req, nil
}
839016
func (m *MockServiceAccountInterface) CreateToken(arg0 string, arg1 *v1.TokenRequest) (*v1.TokenRequest, error) {
	ret := m.ctrl.Call(m, "CreateToken", arg0, arg1)
	ret0, _ := ret[0].(*v1.TokenRequest)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
548430
func AccessToken(s string) Strategy {
	return &accessToken{
		accessToken: s,
		manager:     tokens.HTTPManager("", s, tokens.NullStore),
	}
}
673085
func (s *SetUserSettingsInput) SetAccessToken(v string) *SetUserSettingsInput {
	s.AccessToken = &v
	return s
}
1108855
func TokensCreate(w http.ResponseWriter, r *http.Request) {
	// Decode the request
	var input TokensCreateRequest
	err := utils.ParseRequest(r, &input)
	if err != nil {
		env.Log.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Warn("Unable to decode a request")

		utils.JSONResponse(w, 409, &TokensCreateResponse{
			Success: false,
			Message: "Invalid input format",
		})
		return
	}

	// We can only create "auth" tokens now
	if input.Type != "auth" {
		utils.JSONResponse(w, 409, &TokensCreateResponse{
			Success: false,
			Message: "Only auth tokens are implemented",
		})
		return
	}

	input.Username = utils.RemoveDots(
		utils.NormalizeUsername(input.Username),
	)

	// Check if account exists
	user, err := env.Accounts.FindAccountByName(input.Username)
	if err != nil {
		utils.JSONResponse(w, 403, &TokensCreateResponse{
			Success: false,
			Message: "Wrong username or password",
		})
		return
	}

	// "registered" accounts can't log in
	if user.Status == "registered" {
		utils.JSONResponse(w, 403, &TokensCreateResponse{
			Success: false,
			Message: "Your account is not confirmed",
		})
		return
	}

	// Verify the password
	valid, updated, err := user.VerifyPassword(input.Password)
	if err != nil || !valid {
		utils.JSONResponse(w, 403, &TokensCreateResponse{
			Success: false,
			Message: "Wrong username or password",
		})
		return
	}

	// Update the user if password was updated
	if updated {
		user.DateModified = time.Now()
		err := env.Accounts.UpdateID(user.ID, user)
		if err != nil {
			env.Log.WithFields(logrus.Fields{
				"user":  user.Name,
				"error": err.Error(),
			}).Error("Could not update user")

			// DO NOT RETURN!
		}
	}

	// Check for 2nd factor
	if user.FactorType != "" {
		factor, ok := env.Factors[user.FactorType]
		if ok {
			// Verify the 2FA
			verified, challenge, err := user.Verify2FA(factor, input.Token)
			if err != nil {
				utils.JSONResponse(w, 500, &TokensCreateResponse{
					Success: false,
					Message: "Internal 2FA error",
				})

				env.Log.WithFields(logrus.Fields{
					"err":    err.Error(),
					"factor": user.FactorType,
				}).Warn("2FA authentication error")
				return
			}

			// Token was probably empty. Return the challenge.
			if !verified && challenge != "" {
				utils.JSONResponse(w, 403, &TokensCreateResponse{
					Success:         false,
					Message:         "2FA token was not passed",
					FactorType:      user.FactorType,
					FactorChallenge: challenge,
				})
				return
			}

			// Token was incorrect
			if !verified {
				utils.JSONResponse(w, 403, &TokensCreateResponse{
					Success:    false,
					Message:    "Invalid token passed",
					FactorType: user.FactorType,
				})
				return
			}
		}
	}

	// Calculate the expiry date
	expDate := time.Now().Add(time.Hour * time.Duration(env.Config.SessionDuration))

	// Create a new token
	token := &models.Token{
		Expiring: models.Expiring{ExpiryDate: expDate},
		Resource: models.MakeResource(user.ID, "Auth token expiring on "+expDate.Format(time.RFC3339)),
		Type:     input.Type,
	}

	// Insert int into the database
	env.Tokens.Insert(token)

	// Respond with the freshly created token
	utils.JSONResponse(w, 201, &TokensCreateResponse{
		Success: true,
		Message: "Authentication successful",
		Token:   token,
	})
}
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
}
596661
func (c *serviceAccounts) CreateToken(name string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {
	result := &authenticationv1.TokenRequest{}
	err := c.client.Post().
		Namespace(c.ns).
		Resource("serviceaccounts").
		SubResource("token").
		Name(name).
		Body(tr).
		Do().
		Into(result)
	return result, err
}
555165
func accessTokenHash(alg jose.SignatureAlgorithm, accessToken string) (string, error) {
	newHash, ok := hashForSigAlg[alg]
	if !ok {
		return "", fmt.Errorf("unsupported signature algorithm: %s", alg)
	}

	hash := newHash()
	if _, err := io.WriteString(hash, accessToken); err != nil {
		return "", fmt.Errorf("computing hash: %v", err)
	}
	sum := hash.Sum(nil)
	return base64.RawURLEncoding.EncodeToString(sum[:len(sum)/2]), nil
}
493358
func CreateNewTokens(client clientset.Interface, tokens []kubeadmapi.BootstrapToken) error {
	return UpdateOrCreateTokens(client, true, tokens)
}
388673
func (c *Itsyouonline) CreateJWTToken(scopes, auds []string) (string, error) {
	// build request
	url := strings.TrimSuffix(c.BaseURI, "/api")
	req, err := http.NewRequest("GET", url+"/v1/oauth/jwt", nil)
	if err != nil {
		return "", err
	}

	// set auth header
	if c.AuthHeader == "" {
		return "", fmt.Errorf("you need to create an oauth token in order to create JWT token")
	}

	req.Header.Set("Authorization", c.AuthHeader)

	// query params
	q := req.URL.Query()
	if len(scopes) > 0 {
		q.Add("scope", strings.Join(scopes, ","))
	}
	if len(auds) > 0 {
		q.Add("aud", strings.Join(auds, ","))
	}
	req.URL.RawQuery = q.Encode()

	// do the request
	rsp, err := c.client.Do(req)
	if err != nil {
		return "", err
	}
	defer rsp.Body.Close()

	if rsp.StatusCode != 200 {
		return "", fmt.Errorf("invalid response's status code :%v", rsp.StatusCode)
	}

	b, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return "", err
	}
	return string(b), nil
}
626530
func (s *GlobalSecondaryIndexUpdate) SetCreate(v *CreateGlobalSecondaryIndexAction) *GlobalSecondaryIndexUpdate {
	s.Create = v
	return s
}