repos / pico

pico services - prose.sh, pastes.sh, imgs.sh, feeds.sh, pgs.sh
git clone https://github.com/picosh/pico.git

pico / tui
Eric Bower · 30 Nov 24

util.go

 1package tui
 2
 3import (
 4	"errors"
 5	"fmt"
 6	"strings"
 7
 8	"github.com/picosh/pico/db"
 9	"github.com/picosh/pico/tui/common"
10	"github.com/picosh/utils"
11)
12
13func findUser(shrd *common.SharedModel) (*db.User, error) {
14	logger := shrd.Cfg.Logger
15	var user *db.User
16	usr := shrd.Session.User()
17
18	if shrd.Session.PublicKey() == nil {
19		return nil, fmt.Errorf("unable to find public key")
20	}
21
22	key := utils.KeyForKeyText(shrd.Session.PublicKey())
23
24	user, err := shrd.Dbpool.FindUserForKey(usr, key)
25	if err != nil {
26		logger.Error("no user found for public key", "err", err.Error())
27		// we only want to throw an error for specific cases
28		if errors.Is(err, &db.ErrMultiplePublicKeys{}) {
29			return nil, err
30		}
31		// no user and not error indicates we need to create an account
32		return nil, nil
33	}
34
35	// impersonation
36	adminPrefix := "admin__"
37	if strings.HasPrefix(usr, adminPrefix) {
38		hasFeature := shrd.Dbpool.HasFeatureForUser(user.ID, "admin")
39		if !hasFeature {
40			return nil, fmt.Errorf("only admins can impersonate a user")
41		}
42		impersonate := strings.Replace(usr, adminPrefix, "", 1)
43		user, err = shrd.Dbpool.FindUserForName(impersonate)
44		if err != nil {
45			return nil, err
46		}
47		shrd.Impersonated = true
48	}
49
50	return user, nil
51}
52
53func findPlusFeatureFlag(shrd *common.SharedModel) (*db.FeatureFlag, error) {
54	if shrd.User == nil {
55		return nil, nil
56	}
57
58	ff, err := shrd.Dbpool.FindFeatureForUser(shrd.User.ID, "plus")
59	if err != nil {
60		return nil, err
61	}
62
63	return ff, nil
64}