feat: Add authentication and personal user endpoint (#29)

* feat: Add authentication and personal user endpoint

This contribution adds a lot of scaffolding for the database fake
and testability of coderd.

A new endpoint "/user" is added to return the currently authenticated
user to the requester.

* Use TestMain to catch leak instead

* Add userpassword package

* Add WIP

* Add user auth

* Fix test

* Add comments

* Fix login response

* Fix order

* Fix generated code

* Update httpapi/httpapi.go

Co-authored-by: Bryan <bryan@coder.com>

Co-authored-by: Bryan <bryan@coder.com>
This commit is contained in:
Kyle Carberry
2022-01-20 07:46:51 -06:00
committed by GitHub
parent 36b7b20e2a
commit 6a919aea79
39 changed files with 2232 additions and 61 deletions

View File

@ -0,0 +1,59 @@
package coderdtest
import (
"context"
"net/http/httptest"
"net/url"
"testing"
"github.com/stretchr/testify/require"
"cdr.dev/slog/sloggers/slogtest"
"github.com/coder/coder/coderd"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/database/databasefake"
)
// Server represents a test instance of coderd.
// The database is intentionally omitted from
// this struct to promote data being exposed via
// the API.
type Server struct {
Client *codersdk.Client
URL *url.URL
}
// New constructs a new coderd test instance.
func New(t *testing.T) Server {
// This can be hotswapped for a live database instance.
db := databasefake.New()
handler := coderd.New(&coderd.Options{
Logger: slogtest.Make(t, nil),
Database: db,
})
srv := httptest.NewServer(handler)
u, err := url.Parse(srv.URL)
require.NoError(t, err)
t.Cleanup(srv.Close)
client := codersdk.New(u)
_, err = client.CreateInitialUser(context.Background(), coderd.CreateUserRequest{
Email: "testuser@coder.com",
Username: "testuser",
Password: "testpassword",
})
require.NoError(t, err)
login, err := client.LoginWithPassword(context.Background(), coderd.LoginWithPasswordRequest{
Email: "testuser@coder.com",
Password: "testpassword",
})
require.NoError(t, err)
err = client.SetSessionToken(login.SessionToken)
require.NoError(t, err)
return Server{
Client: client,
URL: u,
}
}