From e05e6ed2ec7c536cf38b86331a3178f84b97705e Mon Sep 17 00:00:00 2001 From: AmirAgassi <33383085+AmirAgassi@users.noreply.github.com> Date: Sat, 7 Dec 2024 14:47:32 -0500 Subject: [PATCH 1/6] yeet --- backend/internal/server/auth.go | 194 +++++++++++++++++++++------ backend/internal/server/auth_test.go | 132 +++++++++++++++++- backend/internal/server/index.go | 29 +++- frontend/src/pages/Register.tsx | 13 +- frontend/src/services/auth.ts | 78 +++++++++-- 5 files changed, 383 insertions(+), 63 deletions(-) diff --git a/backend/internal/server/auth.go b/backend/internal/server/auth.go index e3deab57..e25cf867 100644 --- a/backend/internal/server/auth.go +++ b/backend/internal/server/auth.go @@ -12,12 +12,31 @@ import ( "KonferCA/SPUR/internal/service" "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" "github.com/labstack/echo/v4" "github.com/rs/zerolog/log" "golang.org/x/crypto/bcrypt" ) +type SignupResponse struct { + AccessToken string `json:"access_token"` + User UserResponse `json:"user"` +} + +type SigninResponse struct { + AccessToken string `json:"access_token"` + User UserResponse `json:"user"` +} + +type UserResponse struct { + ID string `json:"id"` + Email string `json:"email"` + FirstName *string `json:"first_name"` + LastName *string `json:"last_name"` + Role db.UserRole `json:"role"` + WalletAddress *string `json:"wallet_address,omitempty"` + EmailVerified bool `json:"email_verified"` +} + func (s *Server) setupAuthRoutes() { auth := s.apiV1.Group("/auth") auth.Use(s.authLimiter.RateLimit()) // special rate limit for auth routes @@ -25,13 +44,14 @@ func (s *Server) setupAuthRoutes() { auth.POST("/signin", s.handleSignin, mw.ValidateRequestBody(reflect.TypeOf(SigninRequest{}))) auth.GET("/verify-email", s.handleVerifyEmail) auth.GET("/ami-verified", s.handleEmailVerifiedStatus) + auth.POST("/refresh", s.handleRefreshToken) + auth.POST("/signout", s.handleSignout) } func (s *Server) handleSignup(c echo.Context) error { var req *SignupRequest req, ok := c.Get(mw.REQUEST_BODY_KEY).(*SignupRequest) if !ok { - // not good... no bueno return echo.NewHTTPError(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) } @@ -39,27 +59,23 @@ func (s *Server) handleSignup(c echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } - ctx := c.Request().Context() - existingUser, err := s.queries.GetUserByEmail(ctx, req.Email) - if err == nil && existingUser.ID != "" { - return echo.NewHTTPError(http.StatusConflict, "email already registered") - } - + // Hash password hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, "failed to hash password") } + ctx := context.Background() user, err := s.queries.CreateUser(ctx, db.CreateUserParams{ Email: req.Email, PasswordHash: string(hashedPassword), Role: req.Role, }) if err != nil { - return echo.NewHTTPError(http.StatusInternalServerError, "failed to create user") + return echo.NewHTTPError(http.StatusConflict, "email already exists") } - // Get user's token salt + // Get user's token salt that was generated during creation salt, err := s.queries.GetUserTokenSalt(ctx, user.ID) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, "failed to get user's token salt") @@ -67,42 +83,51 @@ func (s *Server) handleSignup(c echo.Context) error { accessToken, refreshToken, err := jwt.GenerateWithSalt(user.ID, user.Role, salt) if err != nil { - return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate token") + return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate tokens") } - // send verification email - // db pool is passed to not lose reference to the s object once - // the function returns the response. - go func(pool *pgxpool.Pool, email string) { - ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) - defer cancel() - q := db.New(pool) - exp := time.Now().Add(time.Minute * 30) - token, err := q.CreateVerifyEmailToken(ctx, db.CreateVerifyEmailTokenParams{ - Email: email, - // default expires after 30 minutes - ExpiresAt: exp, + // Set refresh token as HTTP-only cookie + cookie := new(http.Cookie) + cookie.Name = "refresh_token" + cookie.Value = refreshToken + cookie.HttpOnly = true + cookie.Secure = true // only send over HTTPS + cookie.SameSite = http.SameSiteStrictMode + cookie.Path = "/api/v1/auth" // only accessible by auth endpoints + cookie.MaxAge = 7 * 24 * 60 * 60 // 7 days in seconds + + c.SetCookie(cookie) + + // Send verification email asynchronously + go func() { + token, err := s.queries.CreateVerifyEmailToken(context.Background(), db.CreateVerifyEmailTokenParams{ + Email: user.Email, + ExpiresAt: time.Now().Add(30 * time.Minute), }) if err != nil { - log.Error().Err(err).Str("email", email).Msg("Failed to create verify email token in db.") + log.Error().Err(err).Msg("Failed to create verification token") return } - tokenStr, err := jwt.GenerateVerifyEmailToken(email, token.ID, exp) + + // Generate JWT for email verification + tokenStr, err := jwt.GenerateVerifyEmailToken(token.Email, token.ID, token.ExpiresAt) if err != nil { - log.Error().Err(err).Str("email", email).Msg("Failed to generate signed verify email token.") + log.Error().Err(err).Msg("Failed to generate verification token") return } - err = service.SendVerficationEmail(ctx, email, tokenStr) - if err != nil { - log.Error().Err(err).Str("email", email).Msg("Failed to send verification email.") + + // Send verification email + if err := service.SendVerficationEmail(context.Background(), user.Email, tokenStr); err != nil { + log.Error().Err(err).Msg("Failed to send verification email") return } - }(s.DBPool, user.Email) - return c.JSON(http.StatusCreated, AuthResponse{ - AccessToken: accessToken, - RefreshToken: refreshToken, - User: User{ + log.Info().Str("token_id", token.ID).Msg("Verification email sent") + }() + + return c.JSON(http.StatusCreated, SignupResponse{ + AccessToken: accessToken, + User: UserResponse{ ID: user.ID, Email: user.Email, FirstName: user.FirstName, @@ -138,13 +163,24 @@ func (s *Server) handleSignin(c echo.Context) error { accessToken, refreshToken, err := jwt.GenerateWithSalt(user.ID, user.Role, salt) if err != nil { - return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate token") + return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate tokens") } - return c.JSON(http.StatusOK, AuthResponse{ - AccessToken: accessToken, - RefreshToken: refreshToken, - User: User{ + // Set refresh token as HTTP-only cookie + cookie := new(http.Cookie) + cookie.Name = "refresh_token" + cookie.Value = refreshToken + cookie.HttpOnly = true + cookie.Secure = true // only send over HTTPS + cookie.SameSite = http.SameSiteStrictMode + cookie.Path = "/api/v1/auth" // only accessible by auth endpoints + cookie.MaxAge = 7 * 24 * 60 * 60 // 7 days in seconds + + c.SetCookie(cookie) + + return c.JSON(http.StatusOK, SigninResponse{ + AccessToken: accessToken, + User: UserResponse{ ID: user.ID, Email: user.Email, FirstName: user.FirstName, @@ -248,6 +284,86 @@ func (s *Server) handleEmailVerifiedStatus(c echo.Context) error { return c.JSON(http.StatusOK, EmailVerifiedStatusResponse{Verified: user.EmailVerified}) } +func (s *Server) handleRefreshToken(c echo.Context) error { + // Get refresh token from HTTP-only cookie + cookie, err := c.Cookie("refresh_token") + if err != nil { + return echo.NewHTTPError(http.StatusUnauthorized, "no refresh token provided") + } + + // Parse claims without verification to get userID + unverifiedClaims, err := jwt.ParseUnverifiedClaims(cookie.Value) + if err != nil { + return echo.NewHTTPError(http.StatusUnauthorized, "invalid token format") + } + + // Get user's salt from database + ctx := context.Background() + salt, err := s.queries.GetUserTokenSalt(ctx, unverifiedClaims.UserID) + if err != nil { + return echo.NewHTTPError(http.StatusUnauthorized, "invalid token") + } + + // Verify the refresh token with user's salt + claims, err := jwt.VerifyTokenWithSalt(cookie.Value, salt) + if err != nil { + return echo.NewHTTPError(http.StatusUnauthorized, "invalid token") + } + + // Verify it's actually a refresh token + if claims.TokenType != jwt.REFRESH_TOKEN_TYPE { + return echo.NewHTTPError(http.StatusUnauthorized, "invalid token type") + } + + // Update user's token salt to invalidate old tokens + if err := s.queries.UpdateUserTokenSalt(ctx, claims.UserID); err != nil { + return echo.NewHTTPError(http.StatusInternalServerError, "failed to rotate token salt") + } + + // Get the new salt + newSalt, err := s.queries.GetUserTokenSalt(ctx, claims.UserID) + if err != nil { + return echo.NewHTTPError(http.StatusInternalServerError, "failed to get new token salt") + } + + // Generate new tokens with the new salt + accessToken, refreshToken, err := jwt.GenerateWithSalt(claims.UserID, claims.Role, newSalt) + if err != nil { + return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate tokens") + } + + // Set new refresh token cookie + refreshCookie := new(http.Cookie) + refreshCookie.Name = "refresh_token" + refreshCookie.Value = refreshToken + refreshCookie.HttpOnly = true + refreshCookie.Secure = true + refreshCookie.SameSite = http.SameSiteStrictMode + refreshCookie.Path = "/api/v1/auth" + refreshCookie.MaxAge = 7 * 24 * 60 * 60 // 7 days + + c.SetCookie(refreshCookie) + + return c.JSON(http.StatusOK, map[string]string{ + "access_token": accessToken, + }) +} + +func (s *Server) handleSignout(c echo.Context) error { + // Create an expired cookie to clear the refresh token + cookie := new(http.Cookie) + cookie.Name = "refresh_token" + cookie.Value = "" + cookie.HttpOnly = true + cookie.Secure = true + cookie.SameSite = http.SameSiteStrictMode + cookie.Path = "/api/v1/auth" + cookie.MaxAge = -1 // immediately expires the cookie + + c.SetCookie(cookie) + return c.NoContent(http.StatusOK) +} + // helper function to convert pgtype.Text to *string func getStringPtr(t pgtype.Text) *string { if !t.Valid { diff --git a/backend/internal/server/auth_test.go b/backend/internal/server/auth_test.go index 69dcb015..f6288ad1 100644 --- a/backend/internal/server/auth_test.go +++ b/backend/internal/server/auth_test.go @@ -57,12 +57,23 @@ func TestAuth(t *testing.T) { assert.Equal(t, http.StatusCreated, rec.Code) - var response AuthResponse + var response SignupResponse err := json.NewDecoder(rec.Body).Decode(&response) assert.NoError(t, err) assert.NotEmpty(t, response.AccessToken) - assert.NotEmpty(t, response.RefreshToken) assert.Equal(t, payload.Email, response.User.Email) + + // Check refresh token cookie + cookies := rec.Result().Cookies() + var refreshCookie *http.Cookie + for _, cookie := range cookies { + if cookie.Name == "refresh_token" { + refreshCookie = cookie + break + } + } + assert.NotNil(t, refreshCookie, "Refresh token cookie should be set") + assert.True(t, refreshCookie.HttpOnly, "Cookie should be HTTP-only") }) // test duplicate email @@ -97,12 +108,23 @@ func TestAuth(t *testing.T) { s.echoInstance.ServeHTTP(rec, req) assert.Equal(t, http.StatusOK, rec.Code) - var response AuthResponse + var response SigninResponse err := json.Unmarshal(rec.Body.Bytes(), &response) assert.NoError(t, err) assert.NotEmpty(t, response.AccessToken) - assert.NotEmpty(t, response.RefreshToken) assert.Equal(t, payload.Email, response.User.Email) + + // Check refresh token cookie + cookies := rec.Result().Cookies() + var refreshCookie *http.Cookie + for _, cookie := range cookies { + if cookie.Name == "refresh_token" { + refreshCookie = cookie + break + } + } + assert.NotNil(t, refreshCookie, "Refresh token cookie should be set") + assert.True(t, refreshCookie.HttpOnly, "Cookie should be HTTP-only") }) // test invalid credentials @@ -188,4 +210,106 @@ func TestAuth(t *testing.T) { s.echoInstance.ServeHTTP(rec, req) assert.Equal(t, http.StatusBadRequest, rec.Code) }) + + // test refresh token endpoint + t.Run("refresh token", func(t *testing.T) { + // First sign in to get a refresh token cookie + signinPayload := SigninRequest{ + Email: "test@example.com", + Password: "password123", + } + body, _ := json.Marshal(signinPayload) + + signinReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/signin", bytes.NewReader(body)) + signinReq.Header.Set("Content-Type", "application/json") + signinRec := httptest.NewRecorder() + + s.echoInstance.ServeHTTP(signinRec, signinReq) + assert.Equal(t, http.StatusOK, signinRec.Code) + + // Get the refresh token cookie + cookies := signinRec.Result().Cookies() + var refreshCookie *http.Cookie + for _, cookie := range cookies { + if cookie.Name == "refresh_token" { + refreshCookie = cookie + break + } + } + assert.NotNil(t, refreshCookie, "Refresh token cookie should be set") + assert.True(t, refreshCookie.HttpOnly, "Cookie should be HTTP-only") + assert.True(t, refreshCookie.Secure, "Cookie should be secure") + assert.Equal(t, http.SameSiteStrictMode, refreshCookie.SameSite, "Cookie should have strict same-site policy") + assert.Equal(t, "/api/v1/auth", refreshCookie.Path, "Cookie should be limited to auth endpoints") + + // Test refresh endpoint + refreshReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/refresh", nil) + refreshReq.AddCookie(refreshCookie) + refreshRec := httptest.NewRecorder() + + s.echoInstance.ServeHTTP(refreshRec, refreshReq) + assert.Equal(t, http.StatusOK, refreshRec.Code) + + var refreshResponse map[string]string + err := json.NewDecoder(refreshRec.Body).Decode(&refreshResponse) + assert.NoError(t, err) + assert.NotEmpty(t, refreshResponse["access_token"], "Should return new access token") + + // Verify new refresh token cookie is set + newCookies := refreshRec.Result().Cookies() + var newRefreshCookie *http.Cookie + for _, cookie := range newCookies { + if cookie.Name == "refresh_token" { + newRefreshCookie = cookie + break + } + } + assert.NotNil(t, newRefreshCookie, "New refresh token cookie should be set") + assert.NotEqual(t, refreshCookie.Value, newRefreshCookie.Value, "New refresh token should be different") + }) + + // test signout endpoint + t.Run("signout", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/signout", nil) + rec := httptest.NewRecorder() + + s.echoInstance.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + + // Check that refresh token cookie is cleared + cookies := rec.Result().Cookies() + var refreshCookie *http.Cookie + for _, cookie := range cookies { + if cookie.Name == "refresh_token" { + refreshCookie = cookie + break + } + } + assert.NotNil(t, refreshCookie, "Refresh token cookie should be present") + assert.Equal(t, "", refreshCookie.Value, "Cookie value should be empty") + assert.True(t, refreshCookie.MaxAge < 0, "Cookie should be expired") + }) + + // test refresh with invalid token + t.Run("refresh with invalid token", func(t *testing.T) { + invalidCookie := &http.Cookie{ + Name: "refresh_token", + Value: "invalid-token", + } + req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/refresh", nil) + req.AddCookie(invalidCookie) + rec := httptest.NewRecorder() + + s.echoInstance.ServeHTTP(rec, req) + assert.Equal(t, http.StatusUnauthorized, rec.Code) + }) + + // test refresh without token + t.Run("refresh without token", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/refresh", nil) + rec := httptest.NewRecorder() + + s.echoInstance.ServeHTTP(rec, req) + assert.Equal(t, http.StatusUnauthorized, rec.Code) + }) } diff --git a/backend/internal/server/index.go b/backend/internal/server/index.go index c0603a01..7baf04cd 100644 --- a/backend/internal/server/index.go +++ b/backend/internal/server/index.go @@ -121,8 +121,13 @@ func New(testing bool) (*Server, error) { echo.HeaderContentType, echo.HeaderAccept, echo.HeaderContentLength, + echo.HeaderAuthorization, "X-Request-ID", }, + AllowCredentials: true, + ExposeHeaders: []string{ + "Set-Cookie", + }, })) } else if os.Getenv("APP_ENV") == common.STAGING_ENV { e.Use(echoMiddleware.CORSWithConfig(echoMiddleware.CORSConfig{ @@ -133,12 +138,32 @@ func New(testing bool) (*Server, error) { echo.HeaderContentType, echo.HeaderAccept, echo.HeaderContentLength, + echo.HeaderAuthorization, "X-Request-ID", }, + AllowCredentials: true, + ExposeHeaders: []string{ + "Set-Cookie", + }, })) } else { - // use default cors middleware for development - e.Use(echoMiddleware.CORS()) + // development environment + e.Use(echoMiddleware.CORSWithConfig(echoMiddleware.CORSConfig{ + AllowOrigins: []string{"http://localhost:5173"}, + AllowMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete}, + AllowHeaders: []string{ + echo.HeaderOrigin, + echo.HeaderContentType, + echo.HeaderAccept, + echo.HeaderContentLength, + echo.HeaderAuthorization, + "X-Request-ID", + }, + AllowCredentials: true, + ExposeHeaders: []string{ + "Set-Cookie", + }, + })) } e.Use(middleware.Logger()) diff --git a/frontend/src/pages/Register.tsx b/frontend/src/pages/Register.tsx index 98252345..e18cb14a 100644 --- a/frontend/src/pages/Register.tsx +++ b/frontend/src/pages/Register.tsx @@ -1,6 +1,6 @@ import { useState, useEffect, FormEvent } from 'react'; import { Button, TextInput, TextArea } from '@components'; -import { register, RegisterError, saveRefreshToken } from '@services'; +import { register, RegisterError } from '@services'; import { useAuth } from '@/contexts/AuthContext'; type RegistrationStep = @@ -27,8 +27,8 @@ interface FormErrors { } const Register = () => { - const [currentStep, setCurrentStep] = - useState('login-register'); + const { setUser, setCompanyId } = useAuth(); + const [currentStep, setCurrentStep] = useState('login-register'); const [formData, setFormData] = useState({ firstName: '', lastName: '', @@ -39,7 +39,6 @@ const Register = () => { password: '', }); const [errors, setErrors] = useState({}); - const { setUser, setCompanyId } = useAuth(); const LINKEDIN_REGEX = /^(https?:\/\/)?([\w]+\.)?linkedin\.com\/(pub|in|profile)\/([-a-zA-Z0-9]+)\/?$/; @@ -90,13 +89,9 @@ const Register = () => { e.preventDefault(); try { const regResp = await register(formData.email, formData.password); - console.log(regResp); - + setUser(regResp.user); - saveRefreshToken(regResp.refreshToken); - setCompanyId('mock-company-id'); - setCurrentStep('verify-email'); } catch (error) { if (error instanceof RegisterError) { diff --git a/frontend/src/services/auth.ts b/frontend/src/services/auth.ts index 3b0cf3b1..e94a514e 100644 --- a/frontend/src/services/auth.ts +++ b/frontend/src/services/auth.ts @@ -7,9 +7,13 @@ import { RegisterError } from './errors'; import type { User, UserRole } from '@t'; -export interface RegisterReponse { +export interface RegisterResponse { + accessToken: string; + user: User; +} + +export interface SigninResponse { accessToken: string; - refreshToken: string; user: User; } @@ -20,7 +24,7 @@ export async function register( email: string, password: string, role: UserRole = 'startup_owner' -): Promise { +): Promise { const url = getApiUrl('/auth/signup'); const body = { email, @@ -34,21 +38,77 @@ export async function register( headers: { 'Content-Type': 'application/json', }, + credentials: 'include', // needed for cookies }); - // the backend should always return json for the api calls + const json = await res.json(); if (res.status !== HttpStatusCode.CREATED) { throw new RegisterError('Failed to register', res.status, json); } - return json as RegisterReponse; + return json as RegisterResponse; } /** - * Saves the refresh token in localStorage. + * Signs in a user with email and password. */ -export function saveRefreshToken(refreshToken: string) { - // IMPORTANT: The location on where the token is saved must be revisited. - localStorage.setItem('refresh_token', refreshToken); +export async function signin( + email: string, + password: string +): Promise { + const url = getApiUrl('/auth/signin'); + const body = { + email, + password, + }; + + const res = await fetch(url, { + method: 'POST', + body: JSON.stringify(body), + headers: { + 'Content-Type': 'application/json', + }, + credentials: 'include', // needed for cookies + }); + + const json = await res.json(); + + if (res.status !== HttpStatusCode.OK) { + throw new RegisterError('Failed to sign in', res.status, json); + } + + return json as SigninResponse; +} + +/** + * Refreshes the access token using the refresh token stored in HTTP-only cookie. + * Returns the new access token if successful. + */ +export async function refreshAccessToken(): Promise { + const url = getApiUrl('/auth/refresh'); + + const res = await fetch(url, { + method: 'POST', + credentials: 'include', // needed for cookies + }); + + if (!res.ok) { + throw new Error('Failed to refresh access token'); + } + + const json = await res.json(); + return json.access_token; +} + +/** + * Signs out the user by clearing the refresh token cookie. + */ +export async function signout(): Promise { + const url = getApiUrl('/auth/signout'); + + await fetch(url, { + method: 'POST', + credentials: 'include', + }); } From b20d936444bcfbc56362fc90fe4b05aeedfa16b8 Mon Sep 17 00:00:00 2001 From: AmirAgassi <33383085+AmirAgassi@users.noreply.github.com> Date: Sat, 7 Dec 2024 17:02:44 -0500 Subject: [PATCH 2/6] Seed test accounts --- .../20241221000001_update_seed_accounts.sql | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 backend/.sqlc/migrations/20241221000001_update_seed_accounts.sql diff --git a/backend/.sqlc/migrations/20241221000001_update_seed_accounts.sql b/backend/.sqlc/migrations/20241221000001_update_seed_accounts.sql new file mode 100644 index 00000000..bb7b5802 --- /dev/null +++ b/backend/.sqlc/migrations/20241221000001_update_seed_accounts.sql @@ -0,0 +1,72 @@ +-- +goose Up +-- +goose StatementBegin + +-- clean up any existing seed accounts +DELETE FROM users WHERE email IN ('admin@spur.com', 'startup@test.com', 'investor@test.com'); + +-- create admin user +INSERT INTO users ( + email, + password_hash, + first_name, + last_name, + role, + email_verified, + token_salt +) VALUES ( + 'admin@spur.com', + -- hash for 'admin123' + '$2a$10$jltnaECAYSCQozp5UNZi7OZQlyuTR3sJFj5Hr1nLEVmI9uSAxDKnq', + 'Admin', + 'User', + 'admin', + true, + gen_random_bytes(32) +); + +-- create startup owner +INSERT INTO users ( + email, + password_hash, + first_name, + last_name, + role, + email_verified, + token_salt +) VALUES ( + 'startup@test.com', + -- hash for 'startup123' + '$2a$10$Cu72xg8m59GjDHKiFzK7pO8rLYjFL7XsPD6YezNkyZw8ItZBSnvfy', + 'Startup', + 'Owner', + 'startup_owner', + true, + gen_random_bytes(32) +); + +-- create investor +INSERT INTO users ( + email, + password_hash, + first_name, + last_name, + role, + email_verified, + token_salt +) VALUES ( + 'investor@test.com', + -- hash for 'investor123' + '$2a$10$/7Mq7D4hlh0zisjOryL.KeeWSUU30tL5mJdYLAjcqeOodSPrbB.hK', + 'Test', + 'Investor', + 'investor', + true, + gen_random_bytes(32) +); + +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DELETE FROM users WHERE email IN ('admin@spur.com', 'startup@test.com', 'investor@test.com'); +-- +goose StatementEnd \ No newline at end of file From 118a99154ccd1cfd7322e6dff311cefc008fd982 Mon Sep 17 00:00:00 2001 From: AmirAgassi <33383085+AmirAgassi@users.noreply.github.com> Date: Sat, 7 Dec 2024 17:03:02 -0500 Subject: [PATCH 3/6] Hash generator --- backend/scripts/generate_password_hash.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 backend/scripts/generate_password_hash.go diff --git a/backend/scripts/generate_password_hash.go b/backend/scripts/generate_password_hash.go new file mode 100644 index 00000000..305d6ab3 --- /dev/null +++ b/backend/scripts/generate_password_hash.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "golang.org/x/crypto/bcrypt" + "log" +) + +func main() { + passwords := []string{"admin123", "startup123", "investor123"} + + for _, password := range passwords { + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + log.Fatalf("failed to hash password: %v", err) + } + + fmt.Printf("Password: %s\nHash: %s\n\n", password, string(hash)) + } +} \ No newline at end of file From a8f7a5308687ed37976269cbfacebab738c5b224 Mon Sep 17 00:00:00 2001 From: AmirAgassi <33383085+AmirAgassi@users.noreply.github.com> Date: Sat, 7 Dec 2024 17:05:55 -0500 Subject: [PATCH 4/6] Implement sign in and fix auth --- frontend/src/contexts/AuthContext.tsx | 55 ++++++++------------ frontend/src/pages/Register.tsx | 72 +++++++++++++++++++++++---- frontend/src/services/auth.ts | 52 +++++-------------- frontend/src/services/index.ts | 2 +- 4 files changed, 97 insertions(+), 84 deletions(-) diff --git a/frontend/src/contexts/AuthContext.tsx b/frontend/src/contexts/AuthContext.tsx index 088334e0..f5f3689b 100644 --- a/frontend/src/contexts/AuthContext.tsx +++ b/frontend/src/contexts/AuthContext.tsx @@ -1,11 +1,12 @@ -import React, { createContext, useContext, useState, useEffect } from 'react'; +import React, { createContext, useContext, useState } from 'react'; import type { User } from '@/types'; interface AuthContextType { user: User | null; companyId: string | null; - setUser: (user: User | null) => void; - setCompanyId: (id: string | null) => void; + accessToken: string | null; + setAuth: (user: User | null, token: string | null, companyId?: string | null) => void; + clearAuth: () => void; } const AuthContext = createContext(undefined); @@ -13,40 +14,28 @@ const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [companyId, setCompanyId] = useState(null); + const [accessToken, setAccessToken] = useState(null); - // Load user from localStorage on mount - useEffect(() => { - const storedUser = localStorage.getItem('user'); - const storedCompanyId = localStorage.getItem('company_id'); - - if (storedUser) { - setUser(JSON.parse(storedUser)); - } - if (storedCompanyId) { - setCompanyId(storedCompanyId); - } - }, []); + const setAuth = (user: User | null, token: string | null, companyId: string | null = null) => { + setUser(user); + setAccessToken(token); + setCompanyId(companyId); + }; - // Save user to localStorage when it changes - useEffect(() => { - if (user) { - localStorage.setItem('user', JSON.stringify(user)); - } else { - localStorage.removeItem('user'); - } - }, [user]); - - // Save companyId to localStorage when it changes - useEffect(() => { - if (companyId) { - localStorage.setItem('company_id', companyId); - } else { - localStorage.removeItem('company_id'); - } - }, [companyId]); + const clearAuth = () => { + setUser(null); + setAccessToken(null); + setCompanyId(null); + }; return ( - + {children} ); diff --git a/frontend/src/pages/Register.tsx b/frontend/src/pages/Register.tsx index e18cb14a..6dbb768b 100644 --- a/frontend/src/pages/Register.tsx +++ b/frontend/src/pages/Register.tsx @@ -1,7 +1,8 @@ import { useState, useEffect, FormEvent } from 'react'; import { Button, TextInput, TextArea } from '@components'; -import { register, RegisterError } from '@services'; +import { register, signin, RegisterError, ApiError } from '@services'; import { useAuth } from '@/contexts/AuthContext'; +import { useNavigate } from 'react-router-dom'; type RegistrationStep = | 'login-register' @@ -27,7 +28,8 @@ interface FormErrors { } const Register = () => { - const { setUser, setCompanyId } = useAuth(); + const navigate = useNavigate(); + const { setAuth } = useAuth(); const [currentStep, setCurrentStep] = useState('login-register'); const [formData, setFormData] = useState({ firstName: '', @@ -39,6 +41,7 @@ const Register = () => { password: '', }); const [errors, setErrors] = useState({}); + const [isLoading, setIsLoading] = useState(false); const LINKEDIN_REGEX = /^(https?:\/\/)?([\w]+\.)?linkedin\.com\/(pub|in|profile)\/([-a-zA-Z0-9]+)\/?$/; @@ -87,18 +90,56 @@ const Register = () => { const handleInitialSubmit = async (e: FormEvent) => { e.preventDefault(); + setIsLoading(true); try { const regResp = await register(formData.email, formData.password); - - setUser(regResp.user); - setCompanyId('mock-company-id'); + setAuth(regResp.user, regResp.accessToken, 'mock-company-id'); setCurrentStep('verify-email'); } catch (error) { if (error instanceof RegisterError) { - console.log('do something here', error.statusCode, error.body); + setErrors(prev => ({ + ...prev, + email: error.body.message || 'Registration failed' + })); + } else { + setErrors(prev => ({ + ...prev, + email: 'An unexpected error occurred' + })); + } + } finally { + setIsLoading(false); + } + }; + + const handleLogin = async () => { + setIsLoading(true); + try { + const signinResp = await signin(formData.email, formData.password); + setAuth(signinResp.user, signinResp.accessToken); + + // Redirect based on user role + if (signinResp.user.role === 'admin') { + navigate('/admin/dashboard'); + } else if (signinResp.user.role === 'startup_owner') { + navigate('/dashboard'); + } else if (signinResp.user.role === 'investor') { + navigate('/dashboard'); // or a specific investor dashboard + } + } catch (error) { + if (error instanceof ApiError) { + setErrors(prev => ({ + ...prev, + email: 'Invalid email or password' + })); } else { - // TODO: handle error with some kind of notification + setErrors(prev => ({ + ...prev, + email: 'An unexpected error occurred' + })); } + } finally { + setIsLoading(false); } }; @@ -134,6 +175,7 @@ const Register = () => { name="email" value={formData.email} onChange={handleChange} + error={errors.email} /> { name="password" value={formData.password} onChange={handleChange} + error={errors.password} /> -
@@ -155,9 +204,10 @@ const Register = () => { type="button" liquid size="lg" - // TODO: onClick to handle login + onClick={handleLogin} + disabled={isLoading} > - Login + {isLoading ? 'Please wait...' : 'Login'}
diff --git a/frontend/src/services/auth.ts b/frontend/src/services/auth.ts index e94a514e..4b57ab8e 100644 --- a/frontend/src/services/auth.ts +++ b/frontend/src/services/auth.ts @@ -3,19 +3,17 @@ */ import { getApiUrl, HttpStatusCode } from '@utils'; -import { RegisterError } from './errors'; +import { RegisterError, ApiError } from './errors'; import type { User, UserRole } from '@t'; -export interface RegisterResponse { +export interface AuthResponse { accessToken: string; user: User; } -export interface SigninResponse { - accessToken: string; - user: User; -} +export interface RegisterReponse extends AuthResponse {} +export interface SigninResponse extends AuthResponse {} /** * Registers a user if the given email is not already registered. @@ -24,7 +22,7 @@ export async function register( email: string, password: string, role: UserRole = 'startup_owner' -): Promise { +): Promise { const url = getApiUrl('/auth/signup'); const body = { email, @@ -38,20 +36,19 @@ export async function register( headers: { 'Content-Type': 'application/json', }, - credentials: 'include', // needed for cookies }); - + // the backend should always return json for the api calls const json = await res.json(); if (res.status !== HttpStatusCode.CREATED) { throw new RegisterError('Failed to register', res.status, json); } - return json as RegisterResponse; + return json as RegisterReponse; } /** - * Signs in a user with email and password. + * Signs in a user with email and password */ export async function signin( email: string, @@ -69,46 +66,23 @@ export async function signin( headers: { 'Content-Type': 'application/json', }, - credentials: 'include', // needed for cookies }); const json = await res.json(); if (res.status !== HttpStatusCode.OK) { - throw new RegisterError('Failed to sign in', res.status, json); + throw new ApiError('Failed to sign in', res.status, json); } return json as SigninResponse; } /** - * Refreshes the access token using the refresh token stored in HTTP-only cookie. - * Returns the new access token if successful. - */ -export async function refreshAccessToken(): Promise { - const url = getApiUrl('/auth/refresh'); - - const res = await fetch(url, { - method: 'POST', - credentials: 'include', // needed for cookies - }); - - if (!res.ok) { - throw new Error('Failed to refresh access token'); - } - - const json = await res.json(); - return json.access_token; -} - -/** - * Signs out the user by clearing the refresh token cookie. + * Signs out the current user by: + * 1. Calling the signout endpoint to clear the refresh token cookie + * 2. Clearing the auth context */ export async function signout(): Promise { const url = getApiUrl('/auth/signout'); - - await fetch(url, { - method: 'POST', - credentials: 'include', - }); + await fetch(url, { method: 'POST' }); } diff --git a/frontend/src/services/index.ts b/frontend/src/services/index.ts index 58303032..68d3232e 100644 --- a/frontend/src/services/index.ts +++ b/frontend/src/services/index.ts @@ -1,4 +1,4 @@ -export { register, saveRefreshToken } from './auth'; +export { register, signin, signout } from './auth'; export { RegisterError, ApiError, API_ERROR, REGISTER_ERROR } from './errors'; export { createProject } from './project'; export { createCompany } from './company'; From a6b8549c35e3f2bf6a5ff1241db988cf99447bba Mon Sep 17 00:00:00 2001 From: AmirAgassi <33383085+AmirAgassi@users.noreply.github.com> Date: Sat, 7 Dec 2024 22:59:43 -0500 Subject: [PATCH 5/6] seed demo companies --- .../20241221000002_seed_demo_companies.sql | 165 ++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 backend/.sqlc/migrations/20241221000002_seed_demo_companies.sql diff --git a/backend/.sqlc/migrations/20241221000002_seed_demo_companies.sql b/backend/.sqlc/migrations/20241221000002_seed_demo_companies.sql new file mode 100644 index 00000000..de950a0e --- /dev/null +++ b/backend/.sqlc/migrations/20241221000002_seed_demo_companies.sql @@ -0,0 +1,165 @@ +-- +goose Up +-- +goose StatementBegin + +-- get the startup owner's user id +WITH startup_user AS ( + SELECT id FROM users WHERE email = 'startup@test.com' LIMIT 1 +) +-- create demo companies +INSERT INTO companies ( + id, + owner_user_id, + name, + description, + is_verified, + created_at, + updated_at +) +SELECT + gen_random_uuid(), + startup_user.id, + name, + description, + is_verified, + created_at, + updated_at +FROM startup_user, (VALUES + ( + 'TechVision AI', + 'An AI company focusing on computer vision solutions for autonomous vehicles', + true, + NOW() - INTERVAL '30 days', + NOW() - INTERVAL '2 days' + ), + ( + 'GreenEnergy Solutions', + 'Developing innovative solar panel technology for residential use', + true, + NOW() - INTERVAL '60 days', + NOW() - INTERVAL '5 days' + ), + ( + 'HealthTech Pro', + 'Healthcare technology focusing on remote patient monitoring', + false, + NOW() - INTERVAL '1 day', + NOW() - INTERVAL '1 day' + ), + ( + 'EduLearn Platform', + 'Online education platform with AI-powered personalized learning', + true, + NOW() - INTERVAL '90 days', + NOW() - INTERVAL '10 days' + ), + ( + 'FinTech Solutions', + 'Blockchain-based payment solutions for cross-border transactions', + false, + NOW() - INTERVAL '2 days', + NOW() - INTERVAL '2 days' + ) +) AS t(name, description, is_verified, created_at, updated_at); + +-- Add some company financials +WITH companies_to_update AS ( + SELECT id, name FROM companies + WHERE name IN ('TechVision AI', 'GreenEnergy Solutions', 'EduLearn Platform') +) +INSERT INTO company_financials ( + company_id, + financial_year, + revenue, + expenses, + profit, + sales, + amount_raised, + arr, + grants_received +) +SELECT + id, + 2023, + 1000000.00, -- revenue + 800000.00, -- expenses + 200000.00, -- profit + 1200000.00, -- sales + 500000.00, -- amount raised + 960000.00, -- arr + 50000.00 -- grants +FROM companies_to_update; + +-- Add some employees +WITH companies_to_update AS ( + SELECT id, name FROM companies + WHERE name IN ('TechVision AI', 'GreenEnergy Solutions') +) +INSERT INTO employees ( + company_id, + name, + email, + role, + bio +) +SELECT + c.id, + e.name, + e.email, + e.role, + e.bio +FROM companies_to_update c +CROSS JOIN (VALUES + ( + 'John Smith', + 'john@techvision.ai', + 'CTO', + 'Experienced AI researcher with 10+ years in computer vision' + ), + ( + 'Sarah Johnson', + 'sarah@techvision.ai', + 'Lead Engineer', + 'Senior software engineer specializing in deep learning' + ), + ( + 'Michael Green', + 'michael@greenenergy.com', + 'CEO', + 'Serial entrepreneur with background in renewable energy' + ), + ( + 'Lisa Chen', + 'lisa@greenenergy.com', + 'Head of R&D', + 'PhD in Material Science with focus on solar technology' + ) +) AS e(name, email, role, bio) +WHERE + (c.name = 'TechVision AI' AND e.email LIKE '%techvision%') OR + (c.name = 'GreenEnergy Solutions' AND e.email LIKE '%greenenergy%'); + +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin + +-- Delete seeded employees +DELETE FROM employees +WHERE email IN ( + 'john@techvision.ai', + 'sarah@techvision.ai', + 'michael@greenenergy.com', + 'lisa@greenenergy.com' +); + +-- Delete seeded financials and companies +DELETE FROM companies +WHERE name IN ( + 'TechVision AI', + 'GreenEnergy Solutions', + 'HealthTech Pro', + 'EduLearn Platform', + 'FinTech Solutions' +); + +-- +goose StatementEnd \ No newline at end of file From 1514cdfea1806491e6a6846f7bf494b200eafa1f Mon Sep 17 00:00:00 2001 From: AmirAgassi <33383085+AmirAgassi@users.noreply.github.com> Date: Mon, 9 Dec 2024 14:12:24 -0500 Subject: [PATCH 6/6] move seed data from migrations to seeds directory --- .../20241221000001_update_seed_accounts.sql | 72 ---- .../20241221000002_seed_demo_companies.sql | 165 -------- backend/.sqlc/seeds/development_seed.sql | 365 ++++++++++++++++++ backend/Makefile | 6 +- 4 files changed, 370 insertions(+), 238 deletions(-) delete mode 100644 backend/.sqlc/migrations/20241221000001_update_seed_accounts.sql delete mode 100644 backend/.sqlc/migrations/20241221000002_seed_demo_companies.sql create mode 100644 backend/.sqlc/seeds/development_seed.sql diff --git a/backend/.sqlc/migrations/20241221000001_update_seed_accounts.sql b/backend/.sqlc/migrations/20241221000001_update_seed_accounts.sql deleted file mode 100644 index bb7b5802..00000000 --- a/backend/.sqlc/migrations/20241221000001_update_seed_accounts.sql +++ /dev/null @@ -1,72 +0,0 @@ --- +goose Up --- +goose StatementBegin - --- clean up any existing seed accounts -DELETE FROM users WHERE email IN ('admin@spur.com', 'startup@test.com', 'investor@test.com'); - --- create admin user -INSERT INTO users ( - email, - password_hash, - first_name, - last_name, - role, - email_verified, - token_salt -) VALUES ( - 'admin@spur.com', - -- hash for 'admin123' - '$2a$10$jltnaECAYSCQozp5UNZi7OZQlyuTR3sJFj5Hr1nLEVmI9uSAxDKnq', - 'Admin', - 'User', - 'admin', - true, - gen_random_bytes(32) -); - --- create startup owner -INSERT INTO users ( - email, - password_hash, - first_name, - last_name, - role, - email_verified, - token_salt -) VALUES ( - 'startup@test.com', - -- hash for 'startup123' - '$2a$10$Cu72xg8m59GjDHKiFzK7pO8rLYjFL7XsPD6YezNkyZw8ItZBSnvfy', - 'Startup', - 'Owner', - 'startup_owner', - true, - gen_random_bytes(32) -); - --- create investor -INSERT INTO users ( - email, - password_hash, - first_name, - last_name, - role, - email_verified, - token_salt -) VALUES ( - 'investor@test.com', - -- hash for 'investor123' - '$2a$10$/7Mq7D4hlh0zisjOryL.KeeWSUU30tL5mJdYLAjcqeOodSPrbB.hK', - 'Test', - 'Investor', - 'investor', - true, - gen_random_bytes(32) -); - --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin -DELETE FROM users WHERE email IN ('admin@spur.com', 'startup@test.com', 'investor@test.com'); --- +goose StatementEnd \ No newline at end of file diff --git a/backend/.sqlc/migrations/20241221000002_seed_demo_companies.sql b/backend/.sqlc/migrations/20241221000002_seed_demo_companies.sql deleted file mode 100644 index de950a0e..00000000 --- a/backend/.sqlc/migrations/20241221000002_seed_demo_companies.sql +++ /dev/null @@ -1,165 +0,0 @@ --- +goose Up --- +goose StatementBegin - --- get the startup owner's user id -WITH startup_user AS ( - SELECT id FROM users WHERE email = 'startup@test.com' LIMIT 1 -) --- create demo companies -INSERT INTO companies ( - id, - owner_user_id, - name, - description, - is_verified, - created_at, - updated_at -) -SELECT - gen_random_uuid(), - startup_user.id, - name, - description, - is_verified, - created_at, - updated_at -FROM startup_user, (VALUES - ( - 'TechVision AI', - 'An AI company focusing on computer vision solutions for autonomous vehicles', - true, - NOW() - INTERVAL '30 days', - NOW() - INTERVAL '2 days' - ), - ( - 'GreenEnergy Solutions', - 'Developing innovative solar panel technology for residential use', - true, - NOW() - INTERVAL '60 days', - NOW() - INTERVAL '5 days' - ), - ( - 'HealthTech Pro', - 'Healthcare technology focusing on remote patient monitoring', - false, - NOW() - INTERVAL '1 day', - NOW() - INTERVAL '1 day' - ), - ( - 'EduLearn Platform', - 'Online education platform with AI-powered personalized learning', - true, - NOW() - INTERVAL '90 days', - NOW() - INTERVAL '10 days' - ), - ( - 'FinTech Solutions', - 'Blockchain-based payment solutions for cross-border transactions', - false, - NOW() - INTERVAL '2 days', - NOW() - INTERVAL '2 days' - ) -) AS t(name, description, is_verified, created_at, updated_at); - --- Add some company financials -WITH companies_to_update AS ( - SELECT id, name FROM companies - WHERE name IN ('TechVision AI', 'GreenEnergy Solutions', 'EduLearn Platform') -) -INSERT INTO company_financials ( - company_id, - financial_year, - revenue, - expenses, - profit, - sales, - amount_raised, - arr, - grants_received -) -SELECT - id, - 2023, - 1000000.00, -- revenue - 800000.00, -- expenses - 200000.00, -- profit - 1200000.00, -- sales - 500000.00, -- amount raised - 960000.00, -- arr - 50000.00 -- grants -FROM companies_to_update; - --- Add some employees -WITH companies_to_update AS ( - SELECT id, name FROM companies - WHERE name IN ('TechVision AI', 'GreenEnergy Solutions') -) -INSERT INTO employees ( - company_id, - name, - email, - role, - bio -) -SELECT - c.id, - e.name, - e.email, - e.role, - e.bio -FROM companies_to_update c -CROSS JOIN (VALUES - ( - 'John Smith', - 'john@techvision.ai', - 'CTO', - 'Experienced AI researcher with 10+ years in computer vision' - ), - ( - 'Sarah Johnson', - 'sarah@techvision.ai', - 'Lead Engineer', - 'Senior software engineer specializing in deep learning' - ), - ( - 'Michael Green', - 'michael@greenenergy.com', - 'CEO', - 'Serial entrepreneur with background in renewable energy' - ), - ( - 'Lisa Chen', - 'lisa@greenenergy.com', - 'Head of R&D', - 'PhD in Material Science with focus on solar technology' - ) -) AS e(name, email, role, bio) -WHERE - (c.name = 'TechVision AI' AND e.email LIKE '%techvision%') OR - (c.name = 'GreenEnergy Solutions' AND e.email LIKE '%greenenergy%'); - --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin - --- Delete seeded employees -DELETE FROM employees -WHERE email IN ( - 'john@techvision.ai', - 'sarah@techvision.ai', - 'michael@greenenergy.com', - 'lisa@greenenergy.com' -); - --- Delete seeded financials and companies -DELETE FROM companies -WHERE name IN ( - 'TechVision AI', - 'GreenEnergy Solutions', - 'HealthTech Pro', - 'EduLearn Platform', - 'FinTech Solutions' -); - --- +goose StatementEnd \ No newline at end of file diff --git a/backend/.sqlc/seeds/development_seed.sql b/backend/.sqlc/seeds/development_seed.sql new file mode 100644 index 00000000..38068e63 --- /dev/null +++ b/backend/.sqlc/seeds/development_seed.sql @@ -0,0 +1,365 @@ +-- development seed data + +-- clean up any existing seed accounts +DELETE FROM users WHERE email IN ('admin@spur.com', 'startup@test.com', 'investor@test.com'); + +-- create admin user +INSERT INTO users ( + email, + password_hash, + first_name, + last_name, + role, + email_verified, + token_salt +) VALUES ( + 'admin@spur.com', + -- hash for 'admin123' + '$2a$10$jltnaECAYSCQozp5UNZi7OZQlyuTR3sJFj5Hr1nLEVmI9uSAxDKnq', + 'Admin', + 'User', + 'admin', + true, + gen_random_bytes(32) +); + +-- create startup owner +INSERT INTO users ( + email, + password_hash, + first_name, + last_name, + role, + email_verified, + token_salt +) VALUES ( + 'startup@test.com', + -- hash for 'startup123' + '$2a$10$Cu72xg8m59GjDHKiFzK7pO8rLYjFL7XsPD6YezNkyZw8ItZBSnvfy', + 'Startup', + 'Owner', + 'startup_owner', + true, + gen_random_bytes(32) +); + +-- create investor +INSERT INTO users ( + email, + password_hash, + first_name, + last_name, + role, + email_verified, + token_salt +) VALUES ( + 'investor@test.com', + -- hash for 'investor123' + '$2a$10$/7Mq7D4hlh0zisjOryL.KeeWSUU30tL5mJdYLAjcqeOodSPrbB.hK', + 'Test', + 'Investor', + 'investor', + true, + gen_random_bytes(32) +); + +-- clean up existing demo data +DELETE FROM employees WHERE email IN ( + 'john@techvision.ai', + 'sarah@techvision.ai', + 'michael@greenenergy.com', + 'lisa@greenenergy.com' +); +DELETE FROM companies WHERE name IN ( + 'TechVision AI', + 'GreenEnergy Solutions', + 'HealthTech Pro', + 'EduLearn Platform', + 'FinTech Solutions' +); + +-- get the startup owner's user id and create demo companies +WITH startup_user AS ( + SELECT id FROM users WHERE email = 'startup@test.com' LIMIT 1 +) +-- create demo companies +INSERT INTO companies ( + id, + owner_user_id, + name, + description, + is_verified, + created_at, + updated_at +) +SELECT + gen_random_uuid(), + startup_user.id, + name, + description, + is_verified, + created_at, + updated_at +FROM startup_user, (VALUES + ( + 'TechVision AI', + 'An AI company focusing on computer vision solutions for autonomous vehicles', + true, + NOW() - INTERVAL '30 days', + NOW() - INTERVAL '2 days' + ), + ( + 'GreenEnergy Solutions', + 'Developing innovative solar panel technology for residential use', + true, + NOW() - INTERVAL '60 days', + NOW() - INTERVAL '5 days' + ), + ( + 'HealthTech Pro', + 'Healthcare technology focusing on remote patient monitoring', + false, + NOW() - INTERVAL '1 day', + NOW() - INTERVAL '1 day' + ), + ( + 'EduLearn Platform', + 'Online education platform with AI-powered personalized learning', + true, + NOW() - INTERVAL '90 days', + NOW() - INTERVAL '10 days' + ), + ( + 'FinTech Solutions', + 'Blockchain-based payment solutions for cross-border transactions', + false, + NOW() - INTERVAL '2 days', + NOW() - INTERVAL '2 days' + ) +) AS t(name, description, is_verified, created_at, updated_at); + +-- add company financials +WITH companies_to_update AS ( + SELECT id, name FROM companies + WHERE name IN ('TechVision AI', 'GreenEnergy Solutions', 'EduLearn Platform') +) +INSERT INTO company_financials ( + company_id, + financial_year, + revenue, + expenses, + profit, + sales, + amount_raised, + arr, + grants_received +) +SELECT + id, + 2023, + 1000000.00, -- revenue + 800000.00, -- expenses + 200000.00, -- profit + 1200000.00, -- sales + 500000.00, -- amount raised + 960000.00, -- arr + 50000.00 -- grants +FROM companies_to_update; + +-- add employees +WITH companies_to_update AS ( + SELECT id, name FROM companies + WHERE name IN ('TechVision AI', 'GreenEnergy Solutions') +) +INSERT INTO employees ( + company_id, + name, + email, + role, + bio +) +SELECT + c.id, + e.name, + e.email, + e.role, + e.bio +FROM companies_to_update c +CROSS JOIN (VALUES + ( + 'John Smith', + 'john@techvision.ai', + 'CTO', + 'Experienced AI researcher with 10+ years in computer vision' + ), + ( + 'Sarah Johnson', + 'sarah@techvision.ai', + 'Lead Engineer', + 'Senior software engineer specializing in deep learning' + ), + ( + 'Michael Green', + 'michael@greenenergy.com', + 'CEO', + 'Serial entrepreneur with background in renewable energy' + ), + ( + 'Lisa Chen', + 'lisa@greenenergy.com', + 'Head of R&D', + 'PhD in Material Science with focus on solar technology' + ) +) AS e(name, email, role, bio) +WHERE + (c.name = 'TechVision AI' AND e.email LIKE '%techvision%') OR + (c.name = 'GreenEnergy Solutions' AND e.email LIKE '%greenenergy%'); + +-- clean up existing projects +DELETE FROM project_links; +DELETE FROM project_comments; +DELETE FROM project_files; +DELETE FROM projects; + +-- add demo projects +WITH company_data AS ( + SELECT id, name FROM companies +) +INSERT INTO projects ( + company_id, + title, + description, + status, + created_at, + updated_at +) +SELECT + c.id, + p.title, + p.description, + p.status, + NOW() - (p.age || ' days')::INTERVAL, + NOW() - (p.last_update || ' days')::INTERVAL +FROM company_data c +CROSS JOIN (VALUES + ( + 'TechVision AI', + 'Autonomous Parking System', + 'AI-powered system for automated parallel and perpendicular parking', + 'in_progress', + 45, + 2 + ), + ( + 'TechVision AI', + 'Traffic Pattern Analysis', + 'Real-time traffic analysis using computer vision', + 'completed', + 90, + 30 + ), + ( + 'GreenEnergy Solutions', + 'Solar Panel Efficiency Optimizer', + 'AI-driven system to maximize solar panel energy collection', + 'in_progress', + 30, + 5 + ), + ( + 'EduLearn Platform', + 'Adaptive Learning Algorithm', + 'Machine learning system for personalized education paths', + 'in_review', + 15, + 1 + ) +) AS p(company_name, title, description, status, age, last_update) +WHERE c.name = p.company_name; + +-- add project links +WITH project_data AS ( + SELECT p.id, p.title, c.name as company_name + FROM projects p + JOIN companies c ON p.company_id = c.id +) +INSERT INTO project_links ( + project_id, + link_type, + url +) +SELECT + pd.id, + l.link_type, + l.url +FROM project_data pd +CROSS JOIN (VALUES + ( + 'TechVision AI', + 'Autonomous Parking System', + 'github', + 'https://github.com/techvision/parking-ai' + ), + ( + 'TechVision AI', + 'Autonomous Parking System', + 'demo', + 'https://demo.techvision.ai/parking' + ), + ( + 'GreenEnergy Solutions', + 'Solar Panel Efficiency Optimizer', + 'documentation', + 'https://docs.greenenergy.com/solar-optimizer' + ) +) AS l(company_name, project_title, link_type, url) +WHERE pd.company_name = l.company_name AND pd.title = l.project_title; + +-- add project comments +WITH project_data AS ( + SELECT p.id as project_id, + u.id as user_id, + p.title as project_title, + c.name as company_name + FROM projects p + JOIN companies c ON p.company_id = c.id + CROSS JOIN users u +) +INSERT INTO project_comments ( + project_id, + user_id, + comment, + created_at +) +SELECT + pd.project_id, + pd.user_id, + pc.comment, + NOW() - (pc.days_ago || ' days')::INTERVAL +FROM project_data pd +CROSS JOIN (VALUES + ( + 'TechVision AI', + 'Autonomous Parking System', + 'investor@test.com', + 'This looks great!', + 5 + ), + ( + 'TechVision AI', + 'Autonomous Parking System', + 'startup@test.com', + 'YOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO', + 4 + ), + ( + 'GreenEnergy Solutions', + 'Solar Panel Efficiency Optimizer', + 'investor@test.com', + 'This sucks. :(', + 3 + ) +) AS pc(company_name, project_title, user_email, comment, days_ago) +WHERE pd.company_name = pc.company_name + AND pd.project_title = pc.project_title + AND EXISTS (SELECT 1 FROM users u WHERE u.id = pd.user_id AND u.email = pc.user_email); \ No newline at end of file diff --git a/backend/Makefile b/backend/Makefile index a39c8b99..0c87b7bf 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -8,7 +8,7 @@ TEST_DB_HOST_PORT ?= 5432 TEST_DB_URL ?= postgres://$(TEST_DB_USER):$(TEST_DB_PASSWORD)@localhost:$(TEST_DB_HOST_PORT)/$(TEST_DB_NAME)?sslmode=disable POSTGRESQL_VERSION ?= 16 -.PHONY: query +.PHONY: query seed dev: @VERSION=dev APP_ENV=development air @@ -21,6 +21,10 @@ migration: sql: @sqlc generate +seed: + @echo "Running development seed data..." + @cat .sqlc/seeds/development_seed.sql | docker exec -i nokap-postgres psql -U postgres -d postgres + setup: @go install github.com/air-verse/air@v1.61.1 && \ go install github.com/sqlc-dev/sqlc/cmd/sqlc@v1.27.0 && \