aboutsummaryrefslogtreecommitdiff
path: root/pkg/service/auth_test.go
blob: 35b247575a785ddb5db5c0df0b810c2b6ec08fd8 (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
//go:build unit

package service

import (
	"context"
	"testing"

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

type (
	scene struct {
		ctx            context.Context
		authRepository repository.AuthRepository
		userRepository repository.UserRepository
		controller     *AuthController
	}
)

var (
	key = []byte("6368616e676520746869732070617373")
)

func setUp() *scene {
	userRepository := NewUserRepository()
	return &scene{
		ctx:            context.Background(),
		authRepository: userRepository,
		userRepository: userRepository,
		controller:     NewAuthController(userRepository, userRepository, key),
	}
}

func TestInitialRegisterAndLogin(t *testing.T) {
	testCases := []struct {
		name     string
		username string
		password []byte
	}{
		{
			name:     "Normal register",
			username: "username",
			password: []byte("this is an password"),
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			scene := setUp()

			err := scene.controller.InitialRegister(scene.ctx, []byte(tc.username), tc.password, []byte("/"))
			testkit.TestFatalError(t, "Register", err)

			users, err := scene.userRepository.List(scene.ctx)
			userID := users[0].ID

			user, err := scene.userRepository.Get(scene.ctx, userID)
			testkit.TestFatalError(t, "Get", err)
			testkit.TestValue(t, "Register", tc.username, user.Username)

			auth, err := scene.controller.Login(scene.ctx, []byte(tc.username), tc.password)
			testkit.TestFatalError(t, "Login", err)

			token, err := ext.ReadToken(auth, key)
			testkit.TestFatalError(t, "Login", err)

			testkit.TestValue(t, "Login", tc.username, token.Username)
			testkit.TestValue(t, "Login", userID, token.UserID)
		})
	}
}

func remove[T any](slice []T, s int) []T {
	return append(slice[:s], slice[s+1:]...)
}