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 Login API #19

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ require (
)

require (
github.com/MicahParks/keyfunc/v2 v2.1.0 // indirect
github.com/andybalholm/brotli v1.0.6 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gofiber/contrib/jwt v1.0.7 // indirect
github.com/golang-jwt/jwt/v5 v5.0.0 // indirect
github.com/google/uuid v1.4.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
github.com/MicahParks/keyfunc/v2 v2.1.0 h1:6ZXKb9Rp6qp1bDbJefnG7cTH8yMN1IC/4nf+GVjO99k=
github.com/MicahParks/keyfunc/v2 v2.1.0/go.mod h1:rW42fi+xgLJ2FRRXAfNx9ZA8WpD4OeE/yHVMteCkw9k=
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gofiber/contrib/jwt v1.0.7 h1:LZuCnjEq8AjiDTUjBQSd2zg3H5uDWjHxSXjo7nj9iAc=
github.com/gofiber/contrib/jwt v1.0.7/go.mod h1:fA1apg9zQlUhax+Foc0BHATCDzBsemga1Yr9X0KSvrQ=
github.com/gofiber/fiber/v2 v2.50.0 h1:ia0JaB+uw3GpNSCR5nvC5dsaxXjRU5OEu36aytx+zGw=
github.com/gofiber/fiber/v2 v2.50.0/go.mod h1:21eytvay9Is7S6z+OgPi7c7n4++tnClWmhpimVHMimw=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
Expand Down
5 changes: 3 additions & 2 deletions src/auth/jwt.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package auth

import (
"github.com/golang-jwt/jwt/v5"
"github.com/samber/lo"
"onepixel_backend/src/models"
"strconv"
"time"

"github.com/golang-jwt/jwt/v5"
"github.com/samber/lo"
)

// TODO: pick JWT_KEY from config
Expand Down
4 changes: 3 additions & 1 deletion src/auth/middlewares.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package auth

import "github.com/gofiber/fiber/v2"
import (
"github.com/gofiber/fiber/v2"
)

func MandatoryAuthMiddleware(c *fiber.Ctx) error {
authHeader := c.Get("Authorization")
Expand Down
12 changes: 12 additions & 0 deletions src/controllers/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,15 @@ func (c *UsersController) FindUserByEmail(email string) (*models.User, error) {
}
return user, nil
}

// Get user by ID
func (c *UsersController) FindUserById(id uint) (*models.User, error) {
user := &models.User{
ID: id,
}
res := c.db.First(user)
if res.Error != nil {
return nil, res.Error
}
Comment on lines +50 to +53
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
res := c.db.First(user)
if res.Error != nil {
return nil, res.Error
}
if res := c.db.First(user); res.Error!=nil{
return nil, res.Error
}

You can have one liner error return statements. just a suggestion ;) looks neat and cute!

return user, nil
}
5 changes: 5 additions & 0 deletions src/dtos/http_requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,8 @@ type CreateUserRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}

type LoginUserRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
16 changes: 12 additions & 4 deletions src/dtos/http_responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,29 @@ type UserResponse struct {
Email string `json:"email"`
}

type LoginResponse struct {
Token string `json:"token"`
}

type ErrorResponse struct {
Status int `json:"status"`
Message string `json:"message"`
}

func CreateUserResponseFromUser(user *models.User) UserResponse {
func UserResponseFromUser(user *models.User) UserResponse {
return UserResponse{
ID: user.ID,
Email: user.Email,
}
}

func CreateErrorResponse(status int, message string) ErrorResponse {
func LoginResponseFromUser(token string) LoginResponse {
return LoginResponse{
Token: token,
}
}

func ErrorResponseFromServer(message string) ErrorResponse {
return ErrorResponse{
Status: status,
Message: message,
}
}
3 changes: 2 additions & 1 deletion src/main.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package main

import (
"github.com/samber/lo"
"log"
"onepixel_backend/src/db"
"onepixel_backend/src/server"

"github.com/samber/lo"
)

func main() {
Expand Down
13 changes: 12 additions & 1 deletion src/routes/api/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@ var usersController *controllers.UsersController
func UsersRoute(db *gorm.DB) func(router fiber.Router) {
usersController = controllers.NewUsersController(db)
return func(router fiber.Router) {
// Public Routes
router.Post("/", registerUser)
router.Post("/login", loginUser)

// Private Routes
router.Get("/:id", auth.MandatoryAuthMiddleware, getUserInfo)
router.Patch("/:id", auth.MandatoryAuthMiddleware, updateUserInfo)
}
Expand Down Expand Up @@ -51,7 +54,15 @@ func registerUser(ctx *fiber.Ctx) error {
}

func loginUser(ctx *fiber.Ctx) error {
return ctx.SendString("LoginUser")
var u = new(dtos.CreateUserRequest)
lo.Must0(ctx.BodyParser(u))
savedUser := lo.Must(usersController.FindUserByEmail(u.Email))

if u.Password != savedUser.Password {
return ctx.Status(fiber.StatusUnauthorized).JSON(dtos.ErrorResponseFromServer("Incorrect credentials"))
}
token := auth.CreateJWTFromUser(savedUser)
return ctx.Status(fiber.StatusOK).JSON(dtos.LoginResponseFromUser(token))
}

func getUserInfo(ctx *fiber.Ctx) error {
Expand Down
5 changes: 4 additions & 1 deletion src/server/server.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package server

import (
"onepixel_backend/src/routes/api"

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/recover"
"gorm.io/gorm"
"onepixel_backend/src/routes/api"
)

func CreateApp(db *gorm.DB) *fiber.App {
app := fiber.New()
app.Use(recover.New())

app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World 👋!")
Expand Down
28 changes: 26 additions & 2 deletions tests/routes/api/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http/httptest"
"onepixel_backend/src/auth"
Expand All @@ -17,9 +18,11 @@ import (
)

var app = server.CreateApp(lo.Must(db.InitDBTest()))
var USER_EMAIL = "[email protected]"
var USER_PASSWORD = "test1234"

func TestUsersRoute_RegisterUser(t *testing.T) {
reqBody := []byte(`{"email": "[email protected]", "password": "123456"}`)
reqBody := []byte(fmt.Sprintf(`{"email": "%s", "password": "%s"}`, USER_EMAIL, USER_PASSWORD))

req := httptest.NewRequest("POST", "/api/v1/users", bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
Expand All @@ -29,8 +32,29 @@ func TestUsersRoute_RegisterUser(t *testing.T) {
assert.Equal(t, 201, resp.StatusCode)
}

func TestUsersRoute_LoginUser(t *testing.T) {
var responseStruct dtos.LoginResponse
reqBody := []byte(fmt.Sprintf(`{"email": "%s", "password": "%s"}`, USER_EMAIL, USER_PASSWORD))
req := httptest.NewRequest("POST", "/api/v1/users/login", bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
resp := lo.Must(app.Test(req))

assert.Equal(t, 200, resp.StatusCode)

body, err := io.ReadAll(resp.Body)
assert.Equal(t, err, nil)

err = json.Unmarshal(body, &responseStruct)
assert.Equal(t, err, nil)
assert.NotEqual(t, responseStruct.Token, "")

user, err := auth.ValidateJWT(responseStruct.Token)
assert.Equal(t, err, nil)
assert.Equal(t, user.ID, uint(1))
}

func TestUsersRoute_RegisterUserDuplicateFail(t *testing.T) {
reqBody := []byte(`{"email": "[email protected]", "password": "123456"}`)
reqBody := []byte(fmt.Sprintf(`{"email": "%s", "password": "%s"}`, USER_EMAIL, USER_PASSWORD))
req := httptest.NewRequest("POST", "/api/v1/users", bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
resp := lo.Must(app.Test(req))
Expand Down