aboutsummaryrefslogtreecommitdiff
path: root/pkg/service/auth.go
blob: 0dbd960ff2a49368f531da1b5ceb58719c8537fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package service

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"

	"golang.org/x/crypto/bcrypt"
)

type (
	AuthService struct {
		authRepository authRepository
	}

	authRepository interface {
		GetPassphrase() []byte
		GetBase64AesKey() []byte
	}
)

var tokenSeed = []byte("this is a token for cerrado")

func NewAuthService(repostiory authRepository) *AuthService {
	return &AuthService{
		authRepository: repostiory,
	}
}

func (a *AuthService) CheckAuth(username, password string) bool {
	passphrase := a.authRepository.GetPassphrase()
	pass := []byte(fmt.Sprintf("%s:%s", username, password))

	err := bcrypt.CompareHashAndPassword(passphrase, pass)

	return err == nil
}

func (a *AuthService) IssueToken() ([]byte, error) {
	// TODO: do this block only once
	base := a.authRepository.GetBase64AesKey()

	dbuf, err := base64.StdEncoding.DecodeString(string(base))
	if err != nil {
		return nil, err
	}

	block, err := aes.NewCipher(dbuf)
	if err != nil {
		return nil, err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	nonce := make([]byte, gcm.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, err
	}

	ciphertext := gcm.Seal(nonce, nonce, tokenSeed, nil)

	return ciphertext, nil
}

func (a *AuthService) ValidateToken(token []byte) (bool, error) {
	base := a.authRepository.GetBase64AesKey()

	dbuf, err := base64.StdEncoding.DecodeString(string(base))
	if err != nil {
		return false, err
	}

	block, err := aes.NewCipher(dbuf)
	if err != nil {
		return false, err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return false, err
	}

	nonceSize := gcm.NonceSize()
	if len(token) < nonceSize {
		return false, fmt.Errorf("ciphertext too short")
	}

	nonce, ciphertext := token[:nonceSize], token[nonceSize:]
	plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		return false, err
	}

	return bytes.Equal(tokenSeed, plaintext), nil
}

func GenerateHash(username, password string) (string, error) {
	passphrase := fmt.Sprintf("%s:%s", username, password)
	bytes, err := bcrypt.GenerateFromPassword([]byte(passphrase), 14)
	if err != nil {
		return "", err
	}

	return string(bytes), nil
}

func GenerateAesKey() (string, error) {
	key := make([]byte, 32)

	_, err := rand.Read(key)
	if err != nil {
		return "", err
	}

	return base64.StdEncoding.EncodeToString(key), nil
}