aboutsummaryrefslogtreecommitdiff
path: root/internal/db/two_factors_test.go
blob: c841221399228bc506e9efb62cf33eac7181e6e6 (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
// Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package db

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"

	"gogs.io/gogs/internal/errutil"
)

func Test_twoFactors(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}

	t.Parallel()

	tables := []interface{}{new(TwoFactor), new(TwoFactorRecoveryCode)}
	db := &twoFactors{
		DB: initTestDB(t, "twoFactors", tables...),
	}

	for _, tc := range []struct {
		name string
		test func(*testing.T, *twoFactors)
	}{
		{"Create", test_twoFactors_Create},
		{"GetByUserID", test_twoFactors_GetByUserID},
		{"IsUserEnabled", test_twoFactors_IsUserEnabled},
	} {
		t.Run(tc.name, func(t *testing.T) {
			t.Cleanup(func() {
				err := clearTables(t, db.DB, tables...)
				if err != nil {
					t.Fatal(err)
				}
			})
			tc.test(t, db)
		})
		if t.Failed() {
			break
		}
	}
}

func test_twoFactors_Create(t *testing.T, db *twoFactors) {
	// Create a 2FA token
	err := db.Create(1, "secure-key", "secure-secret")
	if err != nil {
		t.Fatal(err)
	}

	// Get it back and check the Created field
	tf, err := db.GetByUserID(1)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, db.NowFunc().Format(time.RFC3339), tf.Created.UTC().Format(time.RFC3339))

	// Verify there are 10 recover codes generated
	var count int64
	err = db.Model(new(TwoFactorRecoveryCode)).Count(&count).Error
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, int64(10), count)
}

func test_twoFactors_GetByUserID(t *testing.T, db *twoFactors) {
	// Create a 2FA token for user 1
	err := db.Create(1, "secure-key", "secure-secret")
	if err != nil {
		t.Fatal(err)
	}

	// We should be able to get it back
	_, err = db.GetByUserID(1)
	if err != nil {
		t.Fatal(err)
	}

	// Try to get a non-existent 2FA token
	_, err = db.GetByUserID(2)
	expErr := ErrTwoFactorNotFound{args: errutil.Args{"userID": int64(2)}}
	assert.Equal(t, expErr, err)
}

func test_twoFactors_IsUserEnabled(t *testing.T, db *twoFactors) {
	// Create a 2FA token for user 1
	err := db.Create(1, "secure-key", "secure-secret")
	if err != nil {
		t.Fatal(err)
	}

	assert.True(t, db.IsUserEnabled(1))
	assert.False(t, db.IsUserEnabled(2))
}