aboutsummaryrefslogtreecommitdiff
path: root/pkg/service/auth.go
blob: f27cf885dc73e0bd3b3ff706a129388ea0b65a9a (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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package service

import (
	"bytes"
	"context"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/gob"
	"errors"
	"io"

	"golang.org/x/crypto/bcrypt"

	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
)

type AuthController struct {
	authRepository repository.AuthRepository
	userRepository repository.UserRepository
	key            []byte
}

func NewAuthController(
	authRepository repository.AuthRepository,
	userRepository repository.UserRepository,
	key []byte,
) *AuthController {
	return &AuthController{
		authRepository: authRepository,
		userRepository: userRepository,
		key:            key,
	}
}

func (c *AuthController) Login(ctx context.Context, username, password []byte) ([]byte, error) {
	id, err := c.authRepository.GetIDByUsername(ctx, string(username))
	if err != nil {
		return nil, err
	}

	hashedPassword, err := c.authRepository.GetPassword(ctx, id)
	if err != nil {
		return nil, err
	}

	if err := bcrypt.CompareHashAndPassword(hashedPassword, password); err != nil {
		return nil, err
	}

	token := &Token{
		UserID:   id,
		Username: string(username),
	}
	return WriteToken(token, c.key)
}

// InitialRegister register a initial user, it will validate if there is another
// user stored already. If so an error `InvlidaInput` will be returned
func (c *AuthController) InitialRegister(ctx context.Context, username, password []byte, path []byte) error {
	exist, err := c.userRepository.Any(ctx)
	if err != nil {
		return err
	}

	if exist {
		return InvlidInput
	}

	hash, err := bcrypt.GenerateFromPassword(password, bcrypt.MinCost)
	if err != nil {
		return err
	}

	_, err = c.userRepository.Create(ctx, &repository.CreateUser{
		Username: string(username),
		Password: hash,
		IsAdmin:  true,
		Path:     string(path),
	})

	return err
}

func (u *AuthController) List(ctx context.Context) ([]*repository.User, error) {
	return u.userRepository.List(ctx)
}

func (u *AuthController) Get(ctx context.Context, id uint) (*repository.User, error) {
	return u.userRepository.Get(ctx, id)
}

func (u *AuthController) Delete(ctx context.Context, id uint) error {
	return u.userRepository.Delete(ctx, id)
}

func (u *AuthController) Upsert(
	ctx context.Context,
	id *uint,
	username string,
	name string,
	password []byte,
	isAdmin bool,
	path string,
) error {
	if id != nil {
		if err := u.userRepository.Update(ctx, *id, &repository.UpdateUser{
			Username: string(username),
			Name:     name,
			IsAdmin:  isAdmin,
			Path:     path,
		}); err != nil {
			return err
		}

		if len(password) > 0 {
			hash, err := bcrypt.GenerateFromPassword(password, bcrypt.MinCost)
			if err != nil {
				return err
			}

			return u.userRepository.UpdatePassword(ctx, *id, hash)
		}
		return nil
	}

	hash, err := bcrypt.GenerateFromPassword(password, bcrypt.MinCost)
	if err != nil {
		return err
	}

	_, err = u.userRepository.Create(ctx, &repository.CreateUser{
		Username: username,
		Name:     name,
		Password: hash,
		IsAdmin:  isAdmin,
		Path:     path,
	})

	return err
}

type Token struct {
	UserID   uint
	Username string
}

func ReadToken(data []byte, key []byte) (*Token, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err.Error())
	}

	nonceSize := aesgcm.NonceSize()
	if len(data) < nonceSize {
		return nil, errors.New("nonce size greater than data's size")
	}

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

	r := bytes.NewReader(plaintext)
	var token Token
	dec := gob.NewDecoder(r)
	if err = dec.Decode(&token); err != nil {
		return nil, err
	}
	return &token, nil
}

func WriteToken(token *Token, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

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

	var buffer bytes.Buffer
	enc := gob.NewEncoder(&buffer)
	if err := enc.Encode(token); err != nil {
		return nil, err
	}
	nonce := make([]byte, aesgcm.NonceSize())
	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, err
	}

	ciphertext := aesgcm.Seal(nonce, nonce, buffer.Bytes(), nil)
	return ciphertext, nil
}