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

feat: golang fiber register endpoint #2 #4

Open
wants to merge 1 commit into
base: develop
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 be-go-fiber/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.env
.idea
cover.out
29 changes: 29 additions & 0 deletions be-go-fiber/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module taskita

go 1.21.0

require (
github.com/go-sql-driver/mysql v1.7.1
github.com/gofiber/fiber/v2 v2.49.1
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/stretchr/testify v1.8.4
golang.org/x/crypto v0.7.0
)

require (
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/google/uuid v1.3.1 // indirect
github.com/klauspost/compress v1.16.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.49.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/sys v0.11.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
51 changes: 51 additions & 0 deletions be-go-fiber/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
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/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/gofiber/fiber/v2 v2.49.1 h1:0W2DRWevSirc8pJl4o8r8QejDR8TV6ZUCawHxwbIdOk=
github.com/gofiber/fiber/v2 v2.49.1/go.mod h1:nPUeEBUeeYGgwbDm59Gp7vS8MDyScL6ezr/Np9A13WU=
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I=
github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.49.0 h1:9FdvCpmxB74LH4dPb7IJ1cOSsluR07XG3I1txXWwJpE=
github.com/valyala/fasthttp v1.49.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
35 changes: 35 additions & 0 deletions be-go-fiber/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"database/sql"
"log"
"os"
"taskita/user"
"time"

_ "github.com/go-sql-driver/mysql"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
)

func main() {
db, err := sql.Open("mysql", os.Getenv("MYSQL_URI"))
if err != nil {
log.Fatalf("database connection error: %v", err)
}

// Set up important parts as was told by the documentation.
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)

app := fiber.New()
app.Use(cors.New())

api := app.Group("/api", logger.New())

user.New(db, api)

app.Listen(":8000")
}
9 changes: 9 additions & 0 deletions be-go-fiber/user/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package user

import "errors"

var ErrRegisterFailedToHashPassword = errors.New("failed to hash your password")

var ErrRegisterAccountAlreadyExists = errors.New("email already registered")

var ErrRegisterFailedToRegisterAccount = errors.New("failed to register your account")
42 changes: 42 additions & 0 deletions be-go-fiber/user/model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package user

import "time"

type User struct {
ID int `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}

type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}

type LoginResponse struct {
ID int `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Email string `json:"email"`
Token string `json:"token"`
TokenExpiredAt time.Time `json:"token_expired_at"`
}

type RegisterRequest struct {
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
}

type RegisterResponse struct {
ID int `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Email string `json:"email"`
Token string `json:"token"`
TokenExpiredAt time.Time `json:"token_expired_at"`
}
62 changes: 62 additions & 0 deletions be-go-fiber/user/repository.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package user

import (
"context"
"database/sql"
"fmt"
)

type Repository interface {
Register(ctx context.Context, user User) (User, error)
Login(ctx context.Context, username string) (User, error)
User(ctx context.Context, id int) (User, error)
}

type userRepository struct {
database *sql.DB
}

func (r *userRepository) Register(ctx context.Context, user User) (User, error) {
query := "INSERT INTO users (name, username, email, password) VALUES (?, ?, ?, ?)"
result, err := r.database.ExecContext(ctx, query, user.Name, user.Username, user.Email, user.Password)
if err != nil {
return user, fmt.Errorf("repository.register: %v", err)
}

lastInsertedID, err := result.LastInsertId()
if err != nil {
return user, fmt.Errorf("repository.register: %v", err)
}

user.ID = int(lastInsertedID)

return user, nil
}

func (r *userRepository) Login(ctx context.Context, username string) (User, error) {
var user User

query := "SELECT id, name, username, email, password, created_at, updated_at FROM users WHERE username = ? OR email = ?"
if err := r.database.QueryRowContext(ctx, query, username, username).Scan(
&user.ID, &user.Name, &user.Username, &user.Email,
&user.Password, &user.CreatedAt, &user.UpdatedAt,
); err != nil {
return User{}, fmt.Errorf("repository.login: %v", err)
}

return user, nil
}

func (r *userRepository) User(ctx context.Context, id int) (User, error) {
var user User

query := "SELECT id, name, username, email, password, created_at, updated_at FROM users WHERE id = ?"
if err := r.database.QueryRowContext(ctx, query, id).Scan(
&user.ID, &user.Name, &user.Username, &user.Email,
&user.Password, &user.CreatedAt, &user.UpdatedAt,
); err != nil {
return User{}, fmt.Errorf("repository.user: %v", err)
}

return user, nil
}
26 changes: 26 additions & 0 deletions be-go-fiber/user/repository_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package user_test

import (
"context"
"github.com/stretchr/testify/mock"
u "taskita/user"
)

type mockRepository struct {
mock.Mock
}

func (m *mockRepository) Register(ctx context.Context, user u.User) (u.User, error) {
r := m.Called(ctx, user)
return r.Get(0).(u.User), r.Error(1)
}

func (m *mockRepository) Login(ctx context.Context, username string) (u.User, error) {
r := m.Called(ctx, username)
return r.Get(0).(u.User), r.Error(1)
}

func (m *mockRepository) User(ctx context.Context, id int) (u.User, error) {
r := m.Called(ctx, id)
return r.Get(0).(u.User), r.Error(1)
}
40 changes: 40 additions & 0 deletions be-go-fiber/user/route.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package user

import (
"database/sql"

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

func New(db *sql.DB, app fiber.Router) {
r := userRepository{database: db}
s := NewService(&r)

app.Post("/register", registerHandler(s))
}

func registerHandler(s service) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error {
var request RegisterRequest
if err := c.BodyParser(&request); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"success": false,
"message": "you have incomplete registration data",
})
}

result, err := s.Register(c.Context(), request)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"success": false,
"message": err.Error(),
})
}

return c.Status(fiber.StatusOK).JSON(fiber.Map{
"success": true,
"message": "user registered in successfully",
"data": result,
})
}
}
65 changes: 65 additions & 0 deletions be-go-fiber/user/service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package user

import (
"context"
"database/sql"
"errors"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/crypto/bcrypt"
"os"
"time"
)

type service struct{ repository Repository }

func NewService(repository Repository) service {
return service{repository: repository}
}

func (s service) Register(ctx context.Context, request RegisterRequest) (RegisterResponse, error) {
// Hashing password
hashed, err := bcrypt.GenerateFromPassword([]byte(request.Password), 14)
if err != nil {
return RegisterResponse{}, ErrRegisterFailedToHashPassword
}

// Check if user with registered email already exists
_, err = s.repository.Login(ctx, request.Email)
if !errors.Is(err, sql.ErrNoRows) {
return RegisterResponse{}, ErrRegisterAccountAlreadyExists
}

// Register new account
user, err := s.repository.Register(ctx, User{
Name: request.Name,
Username: request.Email,
Email: request.Email,
Password: string(hashed),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
if err != nil {
return RegisterResponse{}, ErrRegisterFailedToRegisterAccount
}

// Set token expired time
expiredAt := time.Now().Add(time.Hour * 24)

// Generate json web token
t := jwt.New(jwt.SigningMethodHS256)
claims := t.Claims.(jwt.MapClaims)
claims["id"] = user.ID
claims["name"] = user.Name
claims["username"] = user.Username
claims["expired"] = expiredAt.Unix()
token, _ := t.SignedString([]byte(os.Getenv("JWT_SECRET")))

return RegisterResponse{
ID: user.ID,
Name: user.Name,
Username: user.Username,
Email: user.Email,
Token: token,
TokenExpiredAt: expiredAt,
}, nil
}
119 changes: 119 additions & 0 deletions be-go-fiber/user/service_test.go

Large diffs are not rendered by default.