aboutsummaryrefslogtreecommitdiff
path: root/pkg/service/auth.go
diff options
context:
space:
mode:
authorGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-06-29 23:33:02 +0200
committerGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-06-29 23:33:02 +0200
commit7a414da9a802d5eeee911b3536790a061e1d7503 (patch)
treee009cd94e72bf908701ca6067833ed14f6860b43 /pkg/service/auth.go
parent1ae70dbd9124675d4a510954619b01edd5f1f6c3 (diff)
downloadlens-7a414da9a802d5eeee911b3536790a061e1d7503.tar.gz
lens-7a414da9a802d5eeee911b3536790a061e1d7503.tar.bz2
lens-7a414da9a802d5eeee911b3536790a061e1d7503.zip
ref: Move all controller under the same folder
Move all controller to the same folder and rename them to service. Moving them to the same folder allow an easier setup for testing.
Diffstat (limited to 'pkg/service/auth.go')
-rw-r--r--pkg/service/auth.go76
1 files changed, 76 insertions, 0 deletions
diff --git a/pkg/service/auth.go b/pkg/service/auth.go
new file mode 100644
index 0000000..4358a8a
--- /dev/null
+++ b/pkg/service/auth.go
@@ -0,0 +1,76 @@
+package service
+
+import (
+ "context"
+
+ "golang.org/x/crypto/bcrypt"
+
+ "git.sr.ht/~gabrielgio/img/pkg/database/repository"
+ "git.sr.ht/~gabrielgio/img/pkg/ext"
+)
+
+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 := &ext.Token{
+ UserID: id,
+ Username: string(username),
+ }
+ return ext.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,
+ Path: string(path),
+ })
+
+ return err
+}