-
Notifications
You must be signed in to change notification settings - Fork 0
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 auth #29
Merged
Merged
Add auth #29
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
4821720
Add auth
AmirAgassi ec5990e
Add StatementBegin and StatementEnd
AmirAgassi fcac8c3
Replace Google uuid with pgtype
AmirAgassi fd95bbb
Add db cleanup to auth_test
AmirAgassi a8f59a7
Convert UUID better
AmirAgassi 7dca626
Merge branch 'main' into add-auth
AmirAgassi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
-- +goose Up | ||
-- +goose StatementBegin | ||
CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; | ||
|
||
CREATE TABLE users ( | ||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), | ||
email VARCHAR(255) UNIQUE NOT NULL, | ||
password_hash VARCHAR(255) NOT NULL, | ||
first_name VARCHAR(100), | ||
last_name VARCHAR(100), | ||
role VARCHAR(50) NOT NULL, | ||
wallet_address VARCHAR(100), | ||
created_at TIMESTAMP DEFAULT NOW(), | ||
updated_at TIMESTAMP DEFAULT NOW() | ||
); | ||
-- +goose StatementEnd | ||
|
||
-- +goose Down | ||
-- +goose StatementBegin | ||
DROP TABLE users; | ||
-- +goose StatementEnd |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
-- name: CreateUser :one | ||
INSERT INTO users ( | ||
email, | ||
password_hash, | ||
first_name, | ||
last_name, | ||
role | ||
) VALUES ( | ||
$1, $2, $3, $4, $5 | ||
) RETURNING *; | ||
|
||
-- name: GetUserByEmail :one | ||
SELECT * FROM users | ||
WHERE email = $1 LIMIT 1; | ||
|
||
-- name: GetUserByID :one | ||
SELECT * FROM users | ||
WHERE id = $1 LIMIT 1; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
package server | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
|
||
"github.com/KonferCA/NoKap/db" | ||
"github.com/emicklei/pgtalk/convert" | ||
"github.com/jackc/pgx/v5/pgtype" | ||
"github.com/labstack/echo/v4" | ||
"golang.org/x/crypto/bcrypt" | ||
) | ||
|
||
func (s *Server) setupAuthRoutes() { | ||
auth := s.apiV1.Group("/auth") | ||
auth.POST("/signup", s.handleSignup) | ||
auth.POST("/signin", s.handleSignin) | ||
} | ||
|
||
func (s *Server) handleSignup(c echo.Context) error { | ||
var req SignupRequest | ||
if err := c.Bind(&req); err != nil { | ||
return echo.NewHTTPError(http.StatusBadRequest, "invalid request body") | ||
} | ||
|
||
if err := c.Validate(&req); err != nil { | ||
return err | ||
} | ||
|
||
ctx := context.Background() | ||
existingUser, err := s.queries.GetUserByEmail(ctx, req.Email) | ||
if err == nil && existingUser.ID.Valid { | ||
return echo.NewHTTPError(http.StatusConflict, "email already registered") | ||
} | ||
|
||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) | ||
if err != nil { | ||
return echo.NewHTTPError(http.StatusInternalServerError, "failed to hash password") | ||
} | ||
|
||
user, err := s.queries.CreateUser(ctx, db.CreateUserParams{ | ||
Email: req.Email, | ||
PasswordHash: string(hashedPassword), | ||
FirstName: pgtype.Text{String: req.FirstName, Valid: true}, | ||
LastName: pgtype.Text{String: req.LastName, Valid: true}, | ||
Role: req.Role, | ||
}) | ||
if err != nil { | ||
return echo.NewHTTPError(http.StatusInternalServerError, "failed to create user") | ||
} | ||
|
||
userID := convert.UUIDToString(user.ID) | ||
token, err := generateJWT(userID, user.Role) | ||
if err != nil { | ||
return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate token") | ||
} | ||
|
||
return c.JSON(http.StatusCreated, AuthResponse{ | ||
Token: token, | ||
User: User{ | ||
ID: userID, | ||
Email: user.Email, | ||
FirstName: user.FirstName.String, | ||
LastName: user.LastName.String, | ||
Role: user.Role, | ||
WalletAddress: getStringPtr(user.WalletAddress), | ||
}, | ||
}) | ||
} | ||
|
||
func (s *Server) handleSignin(c echo.Context) error { | ||
var req SigninRequest | ||
if err := c.Bind(&req); err != nil { | ||
return echo.NewHTTPError(http.StatusBadRequest, "invalid request body") | ||
} | ||
|
||
if err := c.Validate(&req); err != nil { | ||
return err | ||
} | ||
|
||
ctx := context.Background() | ||
user, err := s.queries.GetUserByEmail(ctx, req.Email) | ||
if err != nil { | ||
return echo.NewHTTPError(http.StatusUnauthorized, "invalid credentials") | ||
} | ||
|
||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil { | ||
return echo.NewHTTPError(http.StatusUnauthorized, "invalid credentials") | ||
} | ||
|
||
userID := convert.UUIDToString(user.ID) | ||
token, err := generateJWT(userID, user.Role) | ||
if err != nil { | ||
return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate token") | ||
} | ||
|
||
return c.JSON(http.StatusOK, AuthResponse{ | ||
Token: token, | ||
User: User{ | ||
ID: userID, | ||
Email: user.Email, | ||
FirstName: user.FirstName.String, | ||
LastName: user.LastName.String, | ||
Role: user.Role, | ||
WalletAddress: getStringPtr(user.WalletAddress), | ||
}, | ||
}) | ||
} | ||
|
||
// helper function to convert pgtype.Text to *string | ||
func getStringPtr(t pgtype.Text) *string { | ||
if !t.Valid { | ||
return nil | ||
} | ||
return &t.String | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Curious why is this needed?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
func generateJWT(userID string, role string) (string, error)
based on his function definition, he changed the UUID to a string to pass it in
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
^ lol
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
waiiit so like the UUID type is not just an alias to a string? thats dumb