// CreateToken generates a new machine token given a machine and a secret value.
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
}
1322571
func (s *GitHubCodeDestination) SetToken(v string) *GitHubCodeDestination {
	s.Token = &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,
	})
}
685212
func (s *GetSegmentsInput) SetToken(v string) *GetSegmentsInput {
	s.Token = &v
	return s
}
1343133
func (j *JWT) Create(ctx context.Context, user Principal) (Token, error) {
	// Create a new token object, specifying signing method and the claims
	// you would like it to contain.
	claims := &Claims{
		StandardClaims: gojwt.StandardClaims{
			Subject:   user.Subject,
			Issuer:    user.Issuer,
			ExpiresAt: user.ExpiresAt.Unix(),
			IssuedAt:  user.IssuedAt.Unix(),
			NotBefore: user.IssuedAt.Unix(),
		},
		Organization: user.Organization,
		Group:        user.Group,
	}
	token := gojwt.NewWithClaims(gojwt.SigningMethodHS256, claims)
	// Sign and get the complete encoded token as a string using the secret
	t, err := token.SignedString([]byte(j.Secret))
	// this will only fail if the JSON can't be encoded correctly
	if err != nil {
		return "", err
	}
	return Token(t), nil
}
1215820
func (s *GetSegmentVersionsInput) SetToken(v string) *GetSegmentVersionsInput {
	s.Token = &v
	return s
}
1056204
func NewAuthToken(signer Signer, tokenType string, expireIn int,
	submoduleName, version string, rh AuthTokenRefreshHandler) *AuthToken {
	clientName := fmt.Sprintf("go %s %s %s",
		submoduleName, libkb.GetPlatformString(), runtime.GOARCH)
	authToken := &AuthToken{
		signer:         signer,
		tokenType:      tokenType,
		expireIn:       expireIn,
		clientName:     clientName,
		clientVersion:  version,
		refreshHandler: rh,
	}
	return authToken
}
769572
func (s *GetSegmentImportJobsInput) SetToken(v string) *GetSegmentImportJobsInput {
	s.Token = &v
	return s
}
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
}
898600
func NewAuthToken() string {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	raw := strconv.Itoa(r.Int())
	md := md5.New()
	data := base64.StdEncoding.EncodeToString(md.Sum([]byte(raw)))
	return data
}
663704
func (s *PutApprovalResultInput) SetToken(v string) *PutApprovalResultInput {
	s.Token = &v
	return s
}
172032
func (s *GetCampaignVersionsInput) SetToken(v string) *GetCampaignVersionsInput {
	s.Token = &v
	return s
}
69539
func (c *Client) CreateMachine(opts CreateMachineOpts) (*Machine, error) {
	var resp Machine
	req := request{
		method:         client.POST,
		url:            apiMachines,
		reqValue:       opts,
		resp:           &resp,
		expectedStatus: http.StatusCreated,
	}
	if _, err := c.sendRequest(req); err != nil {
		return nil, errors.Newf(err, "failed to create machine with name: %s", opts.Name)
	}
	return &resp, nil
}
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

}
57908
func (c *TokensClient) CreateLogin(ctx context.Context, loginTokenRequest *LoginTokenRequest) (*LoginTokenResponse, error) {
	p := "/tokens/login"

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

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

	return &resp, 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
}
590507
func (t *dcosRoundtripper) GenerateToken() error {
	t.Lock()
	defer t.Unlock()

	sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: t.secret}, (&jose.SignerOptions{}).WithType("JWT"))
	if err != nil {
		return err
	}

	cl := struct {
		UID string `json:"uid"`
		Exp int64  `json:"exp"`
	}{
		t.uid,
		time.Now().Add(t.expire).Unix(),
	}
	tokenStr, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
	if err != nil {
		return err
	}

	if tokenStr == "" {
		return ErrEmptyToken
	}

	authReq := struct {
		UID   string `json:"uid"`
		Token string `json:"token,omitempty"`
		Exp   int64  `json:"exp,omitempty"`
	}{
		UID:   t.uid,
		Token: tokenStr,
		Exp:   time.Now().Add(t.expire).Unix(),
	}

	b, err := json.Marshal(authReq)
	if err != nil {
		return err
	}

	authBody := bytes.NewBuffer(b)
	req, err := http.NewRequest("POST", t.loginEndpoint, authBody)
	if err != nil {
		return err
	}

	req.Header.Add("Content-type", "application/json")
	resp, err := t.transport.RoundTrip(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return ErrTokenRefresh{
			msg: fmt.Sprintf("POST %s failed, expect response code 200. Got %d", t.loginEndpoint, resp.StatusCode),
		}
	}

	var authResp struct {
		Token string `json:"token"`
	}

	if err = json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
		return err
	}

	t.token = authResp.Token
	return nil
}