Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add register auth route #280

Merged
merged 26 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
e634e00
add JWT_SECRET in setupEnv function for tests
juancwu Dec 20, 2024
6199c1c
add cors middleware
juancwu Dec 20, 2024
98c5773
add queries for new users and check user existence
juancwu Dec 20, 2024
a9c64b3
add cookies helper functions
juancwu Dec 20, 2024
1db36e4
setup register route
juancwu Dec 20, 2024
e19a0f3
add register route test
juancwu Dec 20, 2024
587b966
Merge branch 'main' into feat/180/register-route
juancwu Dec 21, 2024
37061ce
add remove test user after registration test
juancwu Dec 21, 2024
aa1015a
Merge branch 'main' into feat/180/register-route
juancwu Dec 21, 2024
f9ee00a
update the login/register request/response to use the same struct
juancwu Dec 21, 2024
ea27c77
update register route response to use the AuthResponse struct
juancwu Dec 21, 2024
f81c464
update the login handler tests to use new structs
juancwu Dec 21, 2024
b1e5fba
abstract away the cookie setting in login handler
juancwu Dec 21, 2024
4d467ce
use the request validator to validate auth request body in register r…
juancwu Dec 21, 2024
2ba02fd
pass as reference
juancwu Dec 22, 2024
b8468f8
set the original logger back after substitution
juancwu Dec 22, 2024
e3487f7
check token with constant
juancwu Dec 22, 2024
fb1944c
update register tests
juancwu Dec 22, 2024
c76e959
add test for invalid body register route
juancwu Dec 22, 2024
5d6e62a
send verification email upon successful registration
juancwu Dec 23, 2024
79eb62c
Merge branch 'main' into feat/180/register-route
juancwu Dec 23, 2024
d1b3ace
remove reset logger
juancwu Dec 23, 2024
3cb8d24
fail with status created on failure to generate tokens
juancwu Dec 23, 2024
c605bb2
log new user created
juancwu Dec 23, 2024
2a69219
add auth rate limiter
juancwu Dec 23, 2024
76b9657
increase rate limit in test
juancwu Dec 23, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions backend/.sqlc/queries/email_tokens.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,13 @@ WHERE id = $1;

-- name: RemoveVerifyEmailTokenByID :exec
DELETE FROM verify_email_tokens WHERE id = $1;

-- name: NewVerifyEmailToken :one
INSERT INTO verify_email_tokens (user_id, expires_at)
VALUES ($1, $2) RETURNING id;

-- name: ExistsVerifyEmailTokenByUserID :one
SELECT EXISTS(SELECT 1 FROM verify_email_tokens WHERE user_id = $1);

-- name: RemoveVerifyEmailTokenByUserID :exec
DELETE FROM verify_email_tokens WHERE user_id = $1;
9 changes: 9 additions & 0 deletions backend/.sqlc/queries/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ WHERE id = $1;
-- name: GetUserEmailVerifiedStatusByEmail :one
SELECT email_verified FROM users WHERE email = $1;

-- name: UserExistsByEmail :one
SELECT EXISTS(SELECT 1 FROM users WHERE email = $1);

-- name: NewUser :one
INSERT INTO users
(email, password, role)
VALUES
($1, $2, $3) RETURNING id, email, email_verified, role, token_salt;

-- name: GetUserByEmail :one
SELECT * FROM users WHERE email = $1 LIMIT 1;

Expand Down
37 changes: 37 additions & 0 deletions backend/db/email_tokens.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

45 changes: 45 additions & 0 deletions backend/db/users.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/internal/server/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ func (s *Server) setupMiddlewares() {

s.Echo.Use(middleware.RequestID())
s.Echo.Use(middleware.LoggerMiddleware())
s.Echo.Use(middleware.CORS())
}
14 changes: 7 additions & 7 deletions backend/internal/tests/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func TestAuthEndpoints(t *testing.T) {
t.Run("Login Endpoint", func(t *testing.T) {
tests := []struct {
name string
payload v1_auth.LoginRequest
payload v1_auth.AuthRequest
expectedStatus int
checkResponse bool
expectedError *struct {
Expand All @@ -75,7 +75,7 @@ func TestAuthEndpoints(t *testing.T) {
}{
{
name: "Valid Login",
payload: v1_auth.LoginRequest{
payload: v1_auth.AuthRequest{
Email: "[email protected]",
Password: "testpassword123",
},
Expand All @@ -84,7 +84,7 @@ func TestAuthEndpoints(t *testing.T) {
},
{
name: "Invalid Password",
payload: v1_auth.LoginRequest{
payload: v1_auth.AuthRequest{
Email: "[email protected]",
Password: "wrongpassword",
},
Expand All @@ -99,7 +99,7 @@ func TestAuthEndpoints(t *testing.T) {
},
{
name: "Invalid Email",
payload: v1_auth.LoginRequest{
payload: v1_auth.AuthRequest{
Email: "[email protected]",
Password: "testpassword123",
},
Expand All @@ -114,7 +114,7 @@ func TestAuthEndpoints(t *testing.T) {
},
{
name: "Invalid Email Format",
payload: v1_auth.LoginRequest{
payload: v1_auth.AuthRequest{
Email: "invalid-email",
Password: "testpassword123",
},
Expand All @@ -141,7 +141,7 @@ func TestAuthEndpoints(t *testing.T) {
assert.Equal(t, tc.expectedStatus, rec.Code)

if tc.checkResponse {
var response v1_auth.LoginResponse
var response v1_auth.AuthResponse
err := json.Unmarshal(rec.Body.Bytes(), &response)
assert.NoError(t, err)
assert.NotEmpty(t, response.AccessToken)
Expand All @@ -153,7 +153,7 @@ func TestAuthEndpoints(t *testing.T) {
cookies := rec.Result().Cookies()
var foundRefreshToken bool
for _, cookie := range cookies {
if cookie.Name == "token" {
if cookie.Name == v1_auth.COOKIE_REFRESH_TOKEN {
foundRefreshToken = true
assert.True(t, cookie.HttpOnly)
assert.True(t, cookie.Secure)
Expand Down
23 changes: 14 additions & 9 deletions backend/internal/tests/logger_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package tests

import (
customMiddleware "KonferCA/SPUR/internal/middleware"
"bytes"
"encoding/json"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/stretchr/testify/assert"
customMiddleware "KonferCA/SPUR/internal/middleware"
"net/http"
"net/http/httptest"
"testing"
Expand All @@ -23,12 +23,14 @@ TestLogger verifies that the logger middleware:
*/
func TestLogger(t *testing.T) {
// capture log output for testing
originalLogger := log.Logger
defer func() { log.Logger = originalLogger }()
var buf bytes.Buffer
log.Logger = zerolog.New(&buf)

// setup echo
e := echo.New()

// setup request ID middleware with a config that ensures ID generation
e.Use(middleware.RequestIDWithConfig(middleware.RequestIDConfig{
Generator: func() string {
Expand Down Expand Up @@ -60,22 +62,22 @@ func TestLogger(t *testing.T) {

// verify each log entry
var logEntry map[string]interface{}

// check info log
err := json.Unmarshal(logs[0], &logEntry)
assert.NoError(t, err)
assert.Equal(t, "info", logEntry["level"])
assert.Equal(t, "test info message", logEntry["message"])
assert.Equal(t, "test-request-id", logEntry["request_id"])
assert.Equal(t, "/test", logEntry["path"])

// check warning log
err = json.Unmarshal(logs[1], &logEntry)
assert.NoError(t, err)
assert.Equal(t, "warn", logEntry["level"])
assert.Equal(t, "test warning", logEntry["message"])
assert.Equal(t, "test-request-id", logEntry["request_id"])

// check error log
err = json.Unmarshal(logs[2], &logEntry)
assert.NoError(t, err)
Expand All @@ -90,19 +92,22 @@ TestLoggerWithoutContext verifies that GetLogger returns
a default logger when called without proper context
*/
func TestLoggerWithoutContext(t *testing.T) {
originalLogger := log.Logger
defer func() { log.Logger = originalLogger }()
var buf bytes.Buffer
log.Logger = zerolog.New(&buf)

e := echo.New()
c := e.NewContext(nil, nil)

logger := customMiddleware.GetLogger(c)
assert.NotNil(t, logger, "should return default logger")

logger.Info("test message")

var logEntry map[string]interface{}
err := json.Unmarshal(buf.Bytes(), &logEntry)
assert.NoError(t, err)
assert.Equal(t, "test message", logEntry["message"])
}
}

Loading
Loading