<commit_before>package handler

import (
	"context"
	"encoding/json"
	"strings"
	"sync"
	"time"

	"github.com/google/uuid"

	pb "github.com/micro/micro/v3/proto/auth"
	"github.com/micro/micro/v3/service/auth"
	"github.com/micro/micro/v3/service/errors"
	"github.com/micro/micro/v3/service/logger"
	"github.com/micro/micro/v3/service/store"
	authns "github.com/micro/micro/v3/util/auth/namespace"
	"github.com/micro/micro/v3/util/auth/token"
	"github.com/micro/micro/v3/util/auth/token/basic"
	"github.com/micro/micro/v3/util/namespace"
	"golang.org/x/crypto/bcrypt"
)

const (
	storePrefixAccounts      = "account"
	storePrefixRefreshTokens = "refresh"

	// used to enable login with username rather than ID (username can change e.g. email, id is stable)
	storePrefixAccountsByName = "accountByName"
)

var defaultAccount = auth.Account{
	ID:     "admin",
	Type:   "user",
	Scopes: []string{"admin"},
	Secret: "micro",
}

// Auth processes RPC calls
type Auth struct {
	Options       auth.Options
	TokenProvider token.Provider

	namespaces map[string]bool
	sync.Mutex
	// Prevent the generation of default accounts
	DisableAdmin bool
}

// Init the auth
func (a *Auth) Init(opts ...auth.Option) {
	for _, o := range opts {
		o(&a.Options)
	}

	// setup a token provider
	if a.TokenProvider == nil {
		a.TokenProvider = basic.NewTokenProvider(token.WithStore(store.DefaultStore))
	}
}

func (a *Auth) setupDefaultAccount(ns string) error {
	if ns != namespace.DefaultNamespace {
		return nil
	}
	if a.DisableAdmin {
		return nil
	}
	a.Lock()
	defer a.Unlock()

	// setup the namespace cache if not yet done
	if a.namespaces == nil {
		a.namespaces = make(map[string]bool)
	}

	// check to see if the default account has already been verified
	if _, ok := a.namespaces[ns]; ok {
		return nil
	}

	// check to see if we need to create the default account
	prefix := strings.Join([]string{storePrefixAccounts, ns, ""}, joinKey)
	recs, err := store.Read(prefix, store.ReadPrefix())
	if err != nil {
		return err
	}

	hasUser := false
	for _, rec := range recs {
		acc := &auth.Account{}
		err := json.Unmarshal(rec.Value, acc)
		if err != nil {
			return err
		}
		if acc.Type == "user" {
			hasUser = true
			break
		}
	}

	// create the account if none exist in the namespace
	if !hasUser {
		acc := defaultAccount
		acc.Issuer = ns
		if err := a.createAccount(&acc); err != nil {
			return err
		}
	}

	// set the namespace in the cache
	a.namespaces[ns] = true
	return nil
}

// Generate an account
func (a *Auth) Generate(ctx context.Context, req *pb.GenerateRequest, rsp *pb.GenerateResponse) error {
	// validate the request
	if len(req.Id) == 0 {
		return errors.BadRequest("auth.Auth.Generate", "ID required")
	}

	// set the defaults
	if len(req.Type) == 0 {
		req.Type = "user"
	}
	if len(req.Secret) == 0 {
		req.Secret = uuid.New().String()
	}
	if req.Options == nil {
		req.Options = &pb.Options{}
	}
	if len(req.Options.Namespace) == 0 {
		req.Options.Namespace = namespace.FromContext(ctx)
	}

	// authorize the request
	if err := authns.AuthorizeAdmin(ctx, req.Options.Namespace, "auth.Auth.Generate"); err != nil {
		return err
	}

	// check the user does not already exists
	key := strings.Join([]string{storePrefixAccounts, req.Options.Namespace, req.Id}, joinKey)
	if _, err := store.Read(key); err != store.ErrNotFound {
		return errors.BadRequest("auth", "Account with this ID already exists")
	}

	// construct the account
	acc := &auth.Account{
		ID:       req.Id,
		Type:     req.Type,
		Scopes:   req.Scopes,
		Metadata: req.Metadata,
		Issuer:   req.Options.Namespace,
		Secret:   req.Secret,
		Name:     req.Name,
	}

	// create the account
	if err := a.createAccount(acc); err != nil {
		return err
	}

	// return the account
	rsp.Account = serializeAccount(acc)
	rsp.Account.Secret = req.Secret // return unhashed secret
	return nil
}
func (a *Auth) createAccount(acc *auth.Account) error {
	// check the user does not already exists
	key := strings.Join([]string{storePrefixAccounts, acc.Issuer, acc.ID}, joinKey)
	if _, err := store.Read(key); err != store.ErrNotFound {
		return errors.BadRequest("auth.Auth.Generate", "Account with this ID already exists")
	}
	if acc.Metadata == nil {
		acc.Metadata = map[string]string{}
	}
	if acc.Name == "" {
		acc.Name = acc.ID
	}
	usernameKey := strings.Join([]string{storePrefixAccountsByName, acc.Issuer, acc.Name}, joinKey)<commit_msg>add created timestamp to auth accounts (#1863)<commit_after>package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"strings"
	"sync"
	"time"

	"github.com/google/uuid"

	pb "github.com/micro/micro/v3/proto/auth"
	"github.com/micro/micro/v3/service/auth"
	"github.com/micro/micro/v3/service/errors"
	"github.com/micro/micro/v3/service/logger"
	"github.com/micro/micro/v3/service/store"
	authns "github.com/micro/micro/v3/util/auth/namespace"
	"github.com/micro/micro/v3/util/auth/token"
	"github.com/micro/micro/v3/util/auth/token/basic"
	"github.com/micro/micro/v3/util/namespace"
	"golang.org/x/crypto/bcrypt"
)

const (
	storePrefixAccounts      = "account"
	storePrefixRefreshTokens = "refresh"

	// used to enable login with username rather than ID (username can change e.g. email, id is stable)
	storePrefixAccountsByName = "accountByName"
)

var defaultAccount = auth.Account{
	ID:       "admin",
	Type:     "user",
	Scopes:   []string{"admin"},
	Secret:   "micro",
	Metadata: map[string]string{},
}

// Auth processes RPC calls
type Auth struct {
	Options       auth.Options
	TokenProvider token.Provider

	namespaces map[string]bool
	sync.Mutex
	// Prevent the generation of default accounts
	DisableAdmin bool
}

// Init the auth
func (a *Auth) Init(opts ...auth.Option) {
	for _, o := range opts {
		o(&a.Options)
	}

	// setup a token provider
	if a.TokenProvider == nil {
		a.TokenProvider = basic.NewTokenProvider(token.WithStore(store.DefaultStore))
	}
}

func (a *Auth) setupDefaultAccount(ns string) error {
	if ns != namespace.DefaultNamespace {
		return nil
	}
	if a.DisableAdmin {
		return nil
	}
	a.Lock()
	defer a.Unlock()

	// setup the namespace cache if not yet done
	if a.namespaces == nil {
		a.namespaces = make(map[string]bool)
	}

	// check to see if the default account has already been verified
	if _, ok := a.namespaces[ns]; ok {
		return nil
	}

	// check to see if we need to create the default account
	prefix := strings.Join([]string{storePrefixAccounts, ns, ""}, joinKey)
	recs, err := store.Read(prefix, store.ReadPrefix())
	if err != nil {
		return err
	}

	hasUser := false
	for _, rec := range recs {
		acc := &auth.Account{}
		err := json.Unmarshal(rec.Value, acc)
		if err != nil {
			return err
		}
		if acc.Type == "user" {
			hasUser = true
			break
		}
	}

	// create the account if none exist in the namespace
	if !hasUser {
		acc := defaultAccount
		acc.Issuer = ns
		acc.Metadata["created"] = fmt.Sprintf("%d", time.Now().Unix())
		if err := a.createAccount(&acc); err != nil {
			return err
		}
	}

	// set the namespace in the cache
	a.namespaces[ns] = true
	return nil
}

// Generate an account
func (a *Auth) Generate(ctx context.Context, req *pb.GenerateRequest, rsp *pb.GenerateResponse) error {
	// validate the request
	if len(req.Id) == 0 {
		return errors.BadRequest("auth.Auth.Generate", "ID required")
	}

	// set the defaults
	if len(req.Type) == 0 {
		req.Type = "user"
	}
	if len(req.Secret) == 0 {
		req.Secret = uuid.New().String()
	}
	if req.Options == nil {
		req.Options = &pb.Options{}
	}
	if len(req.Options.Namespace) == 0 {
		req.Options.Namespace = namespace.FromContext(ctx)
	}

	// authorize the request
	if err := authns.AuthorizeAdmin(ctx, req.Options.Namespace, "auth.Auth.Generate"); err != nil {
		return err
	}

	// check the user does not already exists
	key := strings.Join([]string{storePrefixAccounts, req.Options.Namespace, req.Id}, joinKey)
	if _, err := store.Read(key); err != store.ErrNotFound {
		return errors.BadRequest("auth", "Account with this ID already exists")
	}

	// construct the account
	acc := &auth.Account{
		ID:       req.Id,
		Type:     req.Type,
		Scopes:   req.Scopes,
		Metadata: req.Metadata,
		Issuer:   req.Options.Namespace,
		Secret:   req.Secret,
		Name:     req.Name,
	}

	// create the account
	if err := a.createAccount(acc); err != nil {
		return err
	}

	// return the account
	rsp.Account = serializeAccount(acc)
	rsp.Account.Secret = req.Secret // return unhashed secret
	return nil
}
func (a *Auth) createAccount(acc *auth.Account) error {
	// check the user does not already exists
	key := strings.Join([]string{storePrefixAccounts, acc.Issuer, acc.ID}, joinKey)
	if _, err := store.Read(key); err != store.ErrNotFound {
		return errors.BadRequest("auth.Auth.Generate", "Account with this ID already exists")
	}
	if acc.Metadata == nil {
		acc.Metadata = map[string]string{
			"created": fmt.Sprintf("%d", time.Now().Unix()),
		}
	}

	// set created time if not defined
	if _, ok := acc.Metadata["created"]; !ok {
		acc.Metadata["created"] = fmt.Sprintf("%d", time.Now().Unix())
	}

	if acc.Name == "" {
		acc.Name = acc.ID
	}

	usernameKey := strings.Join([]string{storePrefixAccountsByName, acc.Issuer, acc.Name}, joinKey)
{'fraction_non_alphanumeric': 0.14115850332715174, 'fraction_numerical': 0.003272608268790226, 'mean_word_length': 3.5029469548133596, 'pattern_counts': {'":': 1, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5422075', 'n_tokens_mistral': 3310, 'n_tokens_neox': 3134, 'n_words': 817}