composite_values.go 2.05 KB
Newer Older
1 2 3 4
package backend

import (
	"errors"
5
	"fmt"
6 7
	"strings"

8
	as "git.autistici.org/ai3/accountserver"
9 10
)

11 12
// Extend the AppSpecificPasswordInfo type, which only contains public
// information, with the encrypted password.
13
type appSpecificPassword struct {
14
	as.AppSpecificPasswordInfo
15 16 17 18 19 20 21 22 23 24 25
	Password string
}

func (p *appSpecificPassword) Encode() string {
	return strings.Join([]string{
		p.Service,
		p.Password,
		p.Comment,
	}, ":")
}

26
func newAppSpecificPassword(info as.AppSpecificPasswordInfo, pw string) *appSpecificPassword {
27 28 29 30 31 32 33 34 35 36 37
	return &appSpecificPassword{
		AppSpecificPasswordInfo: info,
		Password:                pw,
	}
}

func parseAppSpecificPassword(asp string) (*appSpecificPassword, error) {
	parts := strings.Split(asp, ":")
	if len(parts) != 3 {
		return nil, errors.New("badly encoded app-specific password")
	}
38
	return newAppSpecificPassword(as.AppSpecificPasswordInfo{
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
		Service: parts[0],
		Comment: parts[2],
	}, parts[1]), nil
}

func decodeAppSpecificPasswords(values []string) []*appSpecificPassword {
	var out []*appSpecificPassword
	for _, value := range values {
		if asp, err := parseAppSpecificPassword(value); err == nil {
			out = append(out, asp)
		}
	}
	return out
}

func encodeAppSpecificPasswords(asps []*appSpecificPassword) []string {
	var out []string
	for _, asp := range asps {
		out = append(out, asp.Encode())
	}
	return out
}

62 63
func getASPInfo(asps []*appSpecificPassword) []*as.AppSpecificPasswordInfo {
	var out []*as.AppSpecificPasswordInfo
64 65 66 67 68
	for _, asp := range asps {
		out = append(out, &asp.AppSpecificPasswordInfo)
	}
	return out
}
69

70 71
func decodeUserEncryptionKeys(values []string) []*as.UserEncryptionKey {
	var out []*as.UserEncryptionKey
72 73 74 75 76
	for _, value := range values {
		idx := strings.IndexByte(value, ':')
		if idx < 0 {
			continue
		}
77
		out = append(out, &as.UserEncryptionKey{
78 79 80 81 82 83 84
			ID:  value[:idx],
			Key: []byte(value[idx+1:]),
		})
	}
	return out
}

85
func encodeUserEncryptionKeys(keys []*as.UserEncryptionKey) []string {
86 87 88 89 90 91
	var out []string
	for _, key := range keys {
		out = append(out, fmt.Sprintf("%s:%s", key.ID, string(key.Key)))
	}
	return out
}