// This code takes a bot token and creates a permanent webhook.
498061
func main() {
	opts := &Options{}
	_, err := flags.Parse(opts)
	if err != nil {
		log.Fatal(err)
	}

	err = config.LoadDotEnvSkipEmpty(os.Getenv("ENV_PATH"), "./.env")
	if err != nil {
		log.Fatal(err)
	}

	apiClient, err := Initialize()
	if err != nil {
		log.Fatal(err)
	}

	req := rc.ExtensionUpdateRequest{
		Contact: rc.ContactInfoUpdateRequest{
			FirstName: opts.FirstName,
			LastName:  opts.LastName}}

	info, resp, err := apiClient.UserSettingsApi.UpdateExtension(
		context.Background(), "~", "~", req)
	if err != nil {
		log.Fatal(err)
	} else if resp.StatusCode >= 300 {
		log.Fatal(fmt.Sprintf("API Status %v", resp.StatusCode))
	}

	fmt.Printf("Status: %v\n", resp.StatusCode)

	fmtutil.PrintJSON(info)

	fmt.Println("DONE")
}
1142768
func (p *tokenManager) CreateTokenFromCertificate(cert *x509.Certificate, tags []string) ([]byte, error) {

	// Combine the application claims with the standard claims
	claims := &verifierClaims{
		X:    cert.PublicKey.(*ecdsa.PublicKey).X,
		Y:    cert.PublicKey.(*ecdsa.PublicKey).Y,
		Tags: tags,
	}
	claims.ExpiresAt = cert.NotAfter.Unix()

	// Create the token and sign with our key
	strtoken, err := jwt.NewWithClaims(p.signMethod, claims).SignedString(p.privateKey)
	if err != nil {
		return []byte{}, err
	}

	return []byte(strtoken), nil
}
1261289
func CreateWebhook(w *Webhook) error {
	_, err := x.Insert(w)
	return err
}
1198297
func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
	bot := &BotAPI{
		Token:  token,
		Client: client,
		Buffer: 100,
		shutdownChannel: make(chan interface{}),
	}

	self, err := bot.GetMe()
	if err != nil {
		return nil, err
	}

	bot.Self = self

	return bot, nil
}
654560
func CreateHook(c *context.APIContext, form api.CreateHookOption) {
	if !models.IsValidHookTaskType(form.Type) {
		c.Error(422, "", "Invalid hook type")
		return
	}
	for _, name := range []string{"url", "content_type"} {
		if _, ok := form.Config[name]; !ok {
			c.Error(422, "", "Missing config option: "+name)
			return
		}
	}
	if !models.IsValidHookContentType(form.Config["content_type"]) {
		c.Error(422, "", "Invalid content type")
		return
	}

	if len(form.Events) == 0 {
		form.Events = []string{"push"}
	}
	w := &models.Webhook{
		RepoID:      c.Repo.Repository.ID,
		URL:         form.Config["url"],
		ContentType: models.ToHookContentType(form.Config["content_type"]),
		Secret:      form.Config["secret"],
		HookEvent: &models.HookEvent{
			ChooseEvents: true,
			HookEvents: models.HookEvents{
				Create:       com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_CREATE)),
				Delete:       com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_DELETE)),
				Fork:         com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_FORK)),
				Push:         com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PUSH)),
				Issues:       com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_ISSUES)),
				IssueComment: com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_ISSUE_COMMENT)),
				PullRequest:  com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PULL_REQUEST)),
				Release:      com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_RELEASE)),
			},
		},
		IsActive:     form.Active,
		HookTaskType: models.ToHookTaskType(form.Type),
	}
	if w.HookTaskType == models.SLACK {
		channel, ok := form.Config["channel"]
		if !ok {
			c.Error(422, "", "Missing config option: channel")
			return
		}
		meta, err := jsoniter.Marshal(&models.SlackMeta{
			Channel:  channel,
			Username: form.Config["username"],
			IconURL:  form.Config["icon_url"],
			Color:    form.Config["color"],
		})
		if err != nil {
			c.Error(500, "slack: JSON marshal failed", err)
			return
		}
		w.Meta = string(meta)
	}

	if err := w.UpdateEvent(); err != nil {
		c.Error(500, "UpdateEvent", err)
		return
	} else if err := models.CreateWebhook(w); err != nil {
		c.Error(500, "CreateWebhook", err)
		return
	}

	c.JSON(201, convert.ToHook(c.Repo.RepoLink, w))
}
279028
func (ga *GoogleAuth) doGoogleAuthCreateToken(rw http.ResponseWriter, code string) {
	resp, err := ga.client.PostForm(
		"https://www.googleapis.com/oauth2/v3/token",
		url.Values{
			"code":          []string{string(code)},
			"client_id":     []string{ga.config.ClientId},
			"client_secret": []string{ga.config.ClientSecret},
			"redirect_uri":  []string{"postmessage"},
			"grant_type":    []string{"authorization_code"},
		})
	if err != nil {
		http.Error(rw, fmt.Sprintf("Error talking to Google auth backend: %s", err), http.StatusServiceUnavailable)
		return
	}
	codeResp, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	glog.V(2).Infof("Code to token resp: %s", strings.Replace(string(codeResp), "\n", " ", -1))

	var c2t CodeToTokenResponse
	err = json.Unmarshal(codeResp, &c2t)
	if err != nil || c2t.Error != "" || c2t.ErrorDescription != "" {
		var et string
		if err != nil {
			et = err.Error()
		} else {
			et = fmt.Sprintf("%s: %s", c2t.Error, c2t.ErrorDescription)
		}
		http.Error(rw, fmt.Sprintf("Failed to get token: %s", et), http.StatusBadRequest)
		return
	}

	if c2t.RefreshToken == "" {
		http.Error(rw, "Google did not return refresh token, please sign out and sign in again.", http.StatusBadRequest)
		return
	}

	if c2t.ExpiresIn < 60 {
		http.Error(rw, "New token is too short-lived", http.StatusInternalServerError)
		return
	}

	ti, err := ga.getIDTokenInfo(c2t.IDToken)
	if err != nil {
		glog.Errorf("Newly-acquired token is invalid: %+v %s", c2t, err)
		http.Error(rw, "Newly-acquired token is invalid", http.StatusInternalServerError)
		return
	}
	user := ti.Email

	glog.Infof("New Google auth token for %s (exp %d)", user, c2t.ExpiresIn)

	v := &TokenDBValue{
		TokenType:    c2t.TokenType,
		AccessToken:  c2t.AccessToken,
		RefreshToken: c2t.RefreshToken,
		ValidUntil:   time.Now().Add(time.Duration(c2t.ExpiresIn-30) * time.Second),
	}
	dp, err := ga.db.StoreToken(user, v, true)
	if err != nil {
		glog.Errorf("Failed to record server token: %s", err)
		http.Error(rw, "Failed to record server token: %s", http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(rw, `Server logged in; now run "docker login YOUR_REGISTRY_FQDN", use %s as login and %s as password.`, user, dp)
}
796977
func (c oauthClient) Webhooks() ([]wl.Webhook, error) {
	lists, err := c.Lists()
	if err != nil {
		return nil, err
	}

	listCount := len(lists)
	c.logger.Debug(
		"webhooks",
		map[string]interface{}{"listCount": listCount},
	)

	webhooksChan := make(chan []wl.Webhook, listCount)
	idErrChan := make(chan idErr, listCount)
	for _, l := range lists {
		go func(list wl.List) {
			c.logger.Debug(
				"webhooks - getting webhooks for list",
				map[string]interface{}{"listID": list.ID},
			)
			webhooks, err := c.WebhooksForListID(list.ID)
			idErrChan <- idErr{idType: "list", id: list.ID, err: err}
			webhooksChan <- webhooks
		}(l)
	}

	e := multiIDErr{}
	for i := 0; i < listCount; i++ {
		idErr := <-idErrChan
		if idErr.err != nil {
			c.logger.Debug(
				"webhooks - error received getting webhooks for list",
				map[string]interface{}{"listID": idErr.id, "err": err},
			)
			e.addError(idErr)
		}
	}

	totalWebhooks := []wl.Webhook{}
	for i := 0; i < listCount; i++ {
		webhooks := <-webhooksChan
		totalWebhooks = append(totalWebhooks, webhooks...)
	}

	if len(e.errors()) > 0 {
		return totalWebhooks, e
	}

	return totalWebhooks, nil
}
858010
func (c *Client) CreateSignupToken(user services.UserV1, ttl time.Duration) (string, error) {
	if err := user.Check(); err != nil {
		return "", trace.Wrap(err)
	}
	out, err := c.PostJSON(c.Endpoint("signuptokens"), createSignupTokenReq{
		User: user,
		TTL:  ttl,
	})
	if err != nil {
		return "", trace.Wrap(err)
	}
	var token string
	if err := json.Unmarshal(out.Bytes(), &token); err != nil {
		return "", trace.Wrap(err)
	}
	return token, nil
}
198311
func (s *Service) OAuthTokenCreate(ctx context.Context, o OAuthTokenCreateOpts) (*OAuthToken, error) {
	var oauthToken OAuthToken
	return &oauthToken, s.Post(ctx, &oauthToken, fmt.Sprintf("/oauth/tokens"), o)
}
606897
func CreateAuthMiddleware() (*jwt.Middleware, error) {
	err := variables.LoadTokenVerifyKey()
	if err != nil {
		log.Println("Error loading TokenVerifyKey:", err)
	}

	authMiddleware := &jwt.Middleware{
		Realm:            "numapp",
		SigningAlgorithm: variables.SigningAlgorithm,
		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
}
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
}
815305
func (s *Session) WebhookCreate(channelID, name, avatar string) (st *Webhook, err error) {

	data := struct {
		Name   string `json:"name"`
		Avatar string `json:"avatar,omitempty"`
	}{name, avatar}

	body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID))
	if err != nil {
		return
	}

	err = unmarshal(body, &st)

	return
}
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
}
337485
func callServiceDecoratorHook(ctx *workflowContext) error {
	if ctx.userdata.workflowHooks == nil {
		return nil
	}
	serviceHooks := ctx.userdata.workflowHooks.ServiceDecorators
	if ctx.userdata.workflowHooks.ServiceDecorator != nil {
		ctx.logger.Warn("DEPRECATED: Single ServiceDecorator hook superseded by ServiceDecorators slice")
		serviceHooks = append(serviceHooks,
			ServiceDecoratorHookFunc(ctx.userdata.workflowHooks.ServiceDecorator))
	}
	// If there's an API gateway definition, include the resources that provision it.
	// Since this export will likely
	// generate outputs that the s3 site needs, we'll use a temporary outputs accumulator,
	// pass that to the S3Site
	// if it's defined, and then merge it with the normal output map.-
	for _, eachServiceHook := range serviceHooks {
		hookName := runtime.FuncForPC(reflect.ValueOf(eachServiceHook).Pointer()).Name()
		ctx.logger.WithFields(logrus.Fields{
			"ServiceDecoratorHook": hookName,
			"WorkflowHookContext":  ctx.context.workflowHooksContext,
		}).Info("Calling WorkflowHook")

		serviceTemplate := gocf.NewTemplate()
		decoratorError := eachServiceHook.DecorateService(ctx.context.workflowHooksContext,
			ctx.userdata.serviceName,
			serviceTemplate,
			ctx.userdata.s3Bucket,
			codeZipKey(ctx.context.s3CodeZipURL),
			ctx.userdata.buildID,
			ctx.context.awsSession,
			ctx.userdata.noop,
			ctx.logger)
		if nil != decoratorError {
			return decoratorError
		}
		safeMergeErrs := gocc.SafeMerge(serviceTemplate, ctx.context.cfTemplate)
		if len(safeMergeErrs) != 0 {
			return errors.Errorf("Failed to merge templates: %#v", safeMergeErrs)
		}
	}
	return nil
}
172330
func (srv *endlessServer) RegisterSignalHook(prePost int, sig os.Signal, f func()) (err error) {
	if prePost != PRE_SIGNAL && prePost != POST_SIGNAL {
		err = fmt.Errorf("Cannot use %v for prePost arg. Must be endless.PRE_SIGNAL or endless.POST_SIGNAL.", sig)
		return
	}
	for _, s := range hookableSignals {
		if s == sig {
			srv.SignalHooks[prePost][sig] = append(srv.SignalHooks[prePost][sig], f)
			return
		}
	}
	err = fmt.Errorf("Signal %v is not supported.", sig)
	return
}
1276783
func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string) (st *Role, err error) {

	data := struct {
		Name   string `json:"name,omitempty"`
		Avatar string `json:"avatar,omitempty"`
	}{name, avatar}

	body, err := s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""))
	if err != nil {
		return
	}

	err = unmarshal(body, &st)

	return
}
614957
func (m *Meta) uiHook() *UiHook {
	return &UiHook{
		Colorize: m.Colorize(),
		Ui:       m.Ui,
	}
}