// generates all needed security files
// we currently only support itsyou.online oauth2 jwt token
558342
func (s *Server) generateSecurity() error {
	if !s.needJWT() {
		return nil
	}
	// libjwt
	if err := commons.GenerateFile(s, "./templates/nim/libjwt_nim.tmpl", "libjwt_nim", filepath.Join(s.Dir, "libjwt.nim"), true); err != nil {
		return err
	}

	// itsyouonline integration
	return commons.GenerateFile(s, "./templates/nim/oauth2_jwt_nim.tmpl", "oauth2_jwt_nim", filepath.Join(s.Dir, "oauth2_jwt.nim"), true)
}
691568
func generateSecureAdminToken(secret string) (string, error) {
	s := securecookie.New([]byte(secret), nil)
	return s.Encode(secureAdminTokenKey, secureAdminTokenValue)
}
526430
func (mw *GinJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time, error) {
	token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
	claims := token.Claims.(jwt.MapClaims)

	if mw.PayloadFunc != nil {
		for key, value := range mw.PayloadFunc(data) {
			claims[key] = value
		}
	}

	expire := mw.TimeFunc().UTC().Add(mw.Timeout)
	claims["exp"] = expire.Unix()
	claims["orig_iat"] = mw.TimeFunc().Unix()
	tokenString, err := mw.signedString(token)
	if err != nil {
		return "", time.Time{}, err
	}

	return tokenString, expire, nil
}
961083
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	s, err := New(g.API)
	if err != nil {
		return nil, err
	}

	swaggerDir := filepath.Join(g.OutDir, "swagger")
	os.RemoveAll(swaggerDir)
	if err = os.MkdirAll(swaggerDir, 0755); err != nil {
		return nil, err
	}
	g.genfiles = append(g.genfiles, swaggerDir)

	// JSON
	rawJSON, err := json.Marshal(s)
	if err != nil {
		return nil, err
	}
	swaggerFile := filepath.Join(swaggerDir, "swagger.json")
	if err := ioutil.WriteFile(swaggerFile, rawJSON, 0644); err != nil {
		return nil, err
	}
	g.genfiles = append(g.genfiles, swaggerFile)

	// YAML
	rawYAML, err := jsonToYAML(rawJSON)
	if err != nil {
		return nil, err
	}
	swaggerFile = filepath.Join(swaggerDir, "swagger.yaml")
	if err := ioutil.WriteFile(swaggerFile, rawYAML, 0644); err != nil {
		return nil, err
	}
	g.genfiles = append(g.genfiles, swaggerFile)

	return g.genfiles, nil
}
473605
func (c oauthClient) Files() ([]wl.File, error) {
	lists, err := c.Lists()
	if err != nil {
		return nil, err
	}

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

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

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

	allFiles := []wl.File{}
	for i := 0; i < listCount; i++ {
		files := <-filesChan
		allFiles = append(allFiles, files...)
	}

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

	return allFiles, nil
}
1345643
func (a *AuthServer) GenerateUserCerts(key []byte, username string, ttl time.Duration, compatibility string) ([]byte, []byte, error) {
	user, err := a.Identity.GetUser(username)
	if err != nil {
		return nil, nil, trace.Wrap(err)
	}
	checker, err := services.FetchRoles(user.GetRoles(), a.Access, user.GetTraits())
	if err != nil {
		return nil, nil, trace.Wrap(err)
	}
	certs, err := a.generateUserCert(certRequest{
		user:          user,
		roles:         checker,
		ttl:           ttl,
		compatibility: compatibility,
		publicKey:     key,
	})
	if err != nil {
		return nil, nil, trace.Wrap(err)
	}
	return certs.ssh, certs.tls, nil
}
446497
func (g *Generator) generateSecurity() (err error) {
	if len(g.API.SecuritySchemes) == 0 {
		return nil
	}

	var (
		secFile string
		secWr   *SecurityWriter
	)
	{
		secFile = filepath.Join(g.OutDir, "security.go")
		secWr, err = NewSecurityWriter(secFile)
		if err != nil {
			return
		}
	}
	defer func() {
		secWr.Close()
		if err == nil {
			err = secWr.FormatCode()
		}
	}()
	title := fmt.Sprintf("%s: Application Security", g.API.Context())
	imports := []*codegen.ImportSpec{
		codegen.SimpleImport("net/http"),
		codegen.SimpleImport("errors"),
		codegen.SimpleImport("context"),
		codegen.SimpleImport("github.com/goadesign/goa"),
	}
	if err = secWr.WriteHeader(title, g.Target, imports); err != nil {
		return err
	}
	g.genfiles = append(g.genfiles, secFile)
	err = secWr.Execute(design.Design.SecuritySchemes)

	return
}
484762
func (pr *pythonResource) generate(fileName, tmplFile, tmplName, dir string) error {
	return commons.GenerateFile(pr, tmplFile, tmplName, fileName, true)
}
319597
func JWTAuthentication(userName, password string) Authentication {
	return &userNameAuthentication{
		authType: AuthenticationTypeJWT,
		userName: userName,
		password: password,
	}
}
619555
func (m *mesosScheduler) createLoginToken() ([]byte, error) {
	// create a signer for rsa 256
	sm := jwt.GetSigningMethod("RS256")
	mc := jwt.MapClaims{}
	t := jwt.NewWithClaims(sm, mc)

	// set our claims
	mc["uid"] = m.uid

	// set the expire time
	// see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4
	mc["exp"] = time.Now().Add(defaultLoginExp).Unix()

	tokenString, err := t.SignedString(m.privateKey)
	if err != nil {
		log.Errorf("Token Signing error: %v\n", err)
		return nil, err
	}

	log.Debugf("Login Token: %s\n", tokenString)

	return []byte(tokenString), nil
}
635527
func generateConfig(f string) error {
	exists, err := pathExists(f)
	if err != nil {
		return err
	}
	if exists {
		return errors.New("output config file already exists: " + f)
	}
	ext := filepath.Ext(f)

	if len(ext) > 1 {
		ext = ext[1:]
	}

	supportedExts := []string{"json", "toml", "yaml", "yml"}

	if !stringInSlice(ext, supportedExts) {
		return errors.New("output config file must have one of supported extensions: " + strings.Join(supportedExts, ", "))
	}

	var t *template.Template

	switch ext {
	case "json":
		t, err = template.New("config").Parse(jsonConfigTemplate)
	case "toml":
		t, err = template.New("config").Parse(tomlConfigTemplate)
	case "yaml", "yml":
		t, err = template.New("config").Parse(yamlConfigTemplate)
	}
	if err != nil {
		return err
	}

	var output bytes.Buffer
	t.Execute(&output, struct {
		Secret        string
		AdminPassword string
		AdminSecret   string
		APIKey        string
	}{
		uuid.NewV4().String(),
		uuid.NewV4().String(),
		uuid.NewV4().String(),
		uuid.NewV4().String(),
	})

	err = ioutil.WriteFile(f, output.Bytes(), 0644)
	if err != nil {
		return err
	}

	err = validateConfig(f)
	if err != nil {
		_ = os.Remove(f)
		return err
	}

	return nil
}
326959
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	if g.Timeout == 0 {
		g.Timeout = 20 * time.Second
	}
	if g.Scheme == "" && len(g.API.Schemes) > 0 {
		g.Scheme = g.API.Schemes[0]
	}
	if g.Scheme == "" {
		g.Scheme = "http"
	}
	if g.Host == "" {
		g.Host = g.API.Host
	}
	if g.Host == "" {
		return nil, fmt.Errorf("missing host value, set it with --host")
	}

	g.OutDir = filepath.Join(g.OutDir, "js")
	if err := os.RemoveAll(g.OutDir); err != nil {
		return nil, err
	}
	if err := os.MkdirAll(g.OutDir, 0755); err != nil {
		return nil, err
	}
	g.genfiles = append(g.genfiles, g.OutDir)

	// Generate client.js
	exampleAction, err := g.generateJS(filepath.Join(g.OutDir, "client.js"))
	if err != nil {
		return
	}

	// Generate axios.html
	if err = g.generateAxiosJS(); err != nil {
		return
	}

	if exampleAction != nil && !g.NoExample {
		// Generate index.html
		if err = g.generateIndexHTML(filepath.Join(g.OutDir, "index.html"), exampleAction); err != nil {
			return
		}

		// Generate example
		if err = g.generateExample(); err != nil {
			return
		}
	}

	return g.genfiles, nil
}
500061
func (u *User) GenerateEmailActivateCode(email string) string {
	code := tool.CreateTimeLimitCode(
		com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
		setting.Service.ActiveCodeLives, nil)

	// Add tail hex username
	code += hex.EncodeToString([]byte(u.LowerName))
	return code
}
740581
func (api UsersAPI) GenerateIyoID(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	azp, _ := context.Get(r, "client_id").(string)

	mgr := iyoid.NewManager(r)

	// might have an id collision, retry at most maxIDGenerationAttempts time
	var err error
	var id string
	for attempts := 0; attempts < maxIDGenerationAttempts; attempts++ {
		// Generate id
		id, err = tools.GenerateRandomString()
		if handleServerError(w, "generating iyoid", err) {
			return
		}
		err = mgr.UpsertIdentifier(username, azp, id)
		if err != nil && err != iyoid.ErrIDLimitReached && !db.IsDup(err) {
			handleServerError(w, "saving iyoid", err)
			return
		}
		// If the user has too many iyoids report it
		if err == iyoid.ErrIDLimitReached {
			// Max amount of iyoids reached
			log.Debugf("Max iyoid treshold reached for %s - %s", username, azp)
			http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
			return
		}

		// If we got ourselves a dup lets retry
		if db.IsDup(err) {
			continue
		}

		break
	}

	// If there is still an error, we have issues
	if handleServerError(w, "saving new id after multiple tries", err) {
		return
	}

	// If we manage to get here, all is good an the new id has been saved

	// Load ids again
	idObj, err := mgr.GetByUsernameAndAZP(username, azp)
	if err != nil && !db.IsNotFound(err) {
		handleServerError(w, "listing user iyo-ids", err)
		return
	}

	// Only keep the latest id generated
	idObj.IyoIDs = idObj.IyoIDs[len(idObj.IyoIDs)-1 : len(idObj.IyoIDs)]

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(idObj)
}
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
}
1294878
func (s *SanicServer) Generate() error {
	if err := generateJSONSchema(s.APIDef, filepath.Join(s.targetDir, handlersDir)); err != nil {
		return err
	}
	if err := s.generateResources(s.targetDir); err != nil {
		return err
	}

	// security scheme
	if err := generateServerSecurity(s.APIDef.SecuritySchemes, s.Template, s.targetDir); err != nil {
		return err
	}

	// python classes and it's helper
	if err := commons.GenerateFile(nil, "./templates/python/client_support.tmpl",
		"client_support", filepath.Join(s.targetDir, "types", "client_support.py"), true); err != nil {
		return err
	}

	_, err := GenerateAllClasses(s.APIDef, filepath.Join(s.targetDir, typesDir), false)
	if err != nil {
		return err
	}

	if err := s.generateMain(s.targetDir); err != nil {
		return err
	}

	return generateEmptyInitPy(s.targetDir)
}
672681
func (c *Client) CreateUserWithU2FToken(token string, password string, u2fRegisterResponse u2f.RegisterResponse) (services.WebSession, error) {
	out, err := c.PostJSON(c.Endpoint("u2f", "users"), createUserWithU2FTokenReq{
		Token:               token,
		Password:            password,
		U2FRegisterResponse: u2fRegisterResponse,
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}