2016-09-26 18:48:55 +00:00
|
|
|
package service
|
2016-09-05 19:50:57 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
2016-09-15 22:53:47 +00:00
|
|
|
"time"
|
2016-09-05 19:50:57 +00:00
|
|
|
|
2021-08-04 13:40:04 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/datastore/mysql"
|
2021-06-26 04:46:51 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/test"
|
2016-09-05 19:50:57 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
2016-09-15 19:27:55 +00:00
|
|
|
"github.com/stretchr/testify/require"
|
2016-09-05 19:50:57 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestAuthenticate(t *testing.T) {
|
2021-08-04 13:40:04 +00:00
|
|
|
ds := mysql.CreateMySQLDS(t)
|
|
|
|
defer ds.Close()
|
|
|
|
|
2021-06-03 23:24:15 +00:00
|
|
|
svc := newTestService(ds, nil, nil)
|
2021-06-24 20:42:29 +00:00
|
|
|
createTestUsers(t, ds)
|
2016-09-29 02:44:05 +00:00
|
|
|
|
2016-09-15 19:27:55 +00:00
|
|
|
var loginTests = []struct {
|
2021-06-24 20:42:29 +00:00
|
|
|
name string
|
|
|
|
email string
|
2016-09-15 19:27:55 +00:00
|
|
|
password string
|
|
|
|
wantErr error
|
|
|
|
}{
|
|
|
|
{
|
2021-06-24 20:42:29 +00:00
|
|
|
name: "admin1",
|
|
|
|
email: testUsers["admin1"].Email,
|
2016-09-29 02:44:05 +00:00
|
|
|
password: testUsers["admin1"].PlaintextPassword,
|
2016-09-15 19:27:55 +00:00
|
|
|
},
|
|
|
|
{
|
2021-06-24 20:42:29 +00:00
|
|
|
name: "user1",
|
|
|
|
email: testUsers["user1"].Email,
|
2016-09-29 02:44:05 +00:00
|
|
|
password: testUsers["user1"].PlaintextPassword,
|
2016-09-15 19:27:55 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, tt := range loginTests {
|
2021-06-24 20:42:29 +00:00
|
|
|
t.Run(tt.email, func(st *testing.T) {
|
|
|
|
loggedIn, token, err := svc.Login(test.UserContext(test.UserAdmin), tt.email, tt.password)
|
2017-12-22 02:37:32 +00:00
|
|
|
require.Nil(st, err, "login unsuccessful")
|
2021-06-24 20:42:29 +00:00
|
|
|
assert.Equal(st, tt.email, loggedIn.Email)
|
2016-09-15 19:27:55 +00:00
|
|
|
assert.NotEmpty(st, token)
|
2016-09-15 22:53:47 +00:00
|
|
|
|
2021-06-24 20:42:29 +00:00
|
|
|
sessions, err := svc.GetInfoAboutSessionsForUser(test.UserContext(test.UserAdmin), loggedIn.ID)
|
2016-09-15 22:53:47 +00:00
|
|
|
require.Nil(st, err)
|
|
|
|
require.Len(st, sessions, 1, "user should have one session")
|
|
|
|
session := sessions[0]
|
2021-06-24 20:42:29 +00:00
|
|
|
assert.NotZero(st, session.UserID)
|
2016-09-15 22:53:47 +00:00
|
|
|
assert.WithinDuration(st, time.Now(), session.AccessedAt, 3*time.Second,
|
|
|
|
"access time should be set with current time at session creation")
|
2016-09-15 19:27:55 +00:00
|
|
|
})
|
|
|
|
}
|
2017-01-14 20:00:09 +00:00
|
|
|
}
|