Skip to content

Commit

Permalink
api create user, password hash
Browse files Browse the repository at this point in the history
  • Loading branch information
lfcifuentes committed Oct 12, 2023
1 parent ee398e7 commit 6173b95
Show file tree
Hide file tree
Showing 10 changed files with 140 additions and 18 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
APP_SECRET=""

ACCEPTED_DOMAINS="*"

DB_NAME=databasse
DB_USER=test
DB_PORT=1234
Expand Down
31 changes: 31 additions & 0 deletions app/cmd/app_secret.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package cmd

import (
"encoding/base64"
"fmt"
"github.com/spf13/cobra"
"math/rand"
"time"
)

var AppSecret = &cobra.Command{
Use: "make:secret",
Short: "Generate app secret",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("App secret:")
fmt.Println(generateBase64())
},
}

// generateBase64 genera un valor base64 aleatorio
func generateBase64() string {
rand.Seed(time.Now().UnixNano())

// Genera 32 bytes aleatorios
bytes := make([]byte, 32)
rand.Read(bytes)

// Codifica los bytes en base64
base64Value := base64.StdEncoding.EncodeToString(bytes)
return base64Value
}
8 changes: 1 addition & 7 deletions app/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package cmd

import (
"fmt"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/joho/godotenv"
"github.com/lfcifuentes/go-repository-pattern/app/http/router"
"github.com/lfcifuentes/go-repository-pattern/database"
Expand Down Expand Up @@ -34,12 +32,8 @@ func runServer() {
}
defer db.Close()

r := chi.NewRouter()

r.Use(middleware.Logger)

// Configura el enrutador
router := router.NewRouter(r, db)
router := router.NewRouter(db)

fmt.Println(fmt.Sprintf("Server is running in port %v", "8080"))
// Inicia el servidor web
Expand Down
39 changes: 34 additions & 5 deletions app/http/handler/user_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,34 @@ import (
"fmt"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"github.com/go-playground/locales/es"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
es_translations "github.com/go-playground/validator/v10/translations/es"
"github.com/lfcifuentes/go-repository-pattern/app/http/handler/responses"
"github.com/lfcifuentes/go-repository-pattern/app/model"
"github.com/lfcifuentes/go-repository-pattern/app/repository"

"io"
"net/http"
"strconv"
)

var uni *ut.UniversalTranslator
var validate *validator.Validate
var trans ut.Translator

func init() {
esTranslator := es.New()
uni = ut.New(esTranslator, esTranslator)
trans, _ = uni.GetTranslator("es")
validate = validator.New()
err := es_translations.RegisterDefaultTranslations(validate, trans)
if err != nil {
panic(err)
}
}

type UserController struct {
UserRepository repository.UserRepository
}
Expand All @@ -32,20 +53,28 @@ func (uc *UserController) GetAll(w http.ResponseWriter, r *http.Request) {
}

func (uc *UserController) Create(w http.ResponseWriter, r *http.Request) {
newUser := &model.User{
Name: "NombreUsuario",
Email: "[email protected]",

var newUser = model.User{}
reqBody, _ := io.ReadAll(r.Body)
newUser, _ = model.UnmarshalUser(reqBody)

err := validate.Struct(newUser)
if err != nil {
// translate all error at once
errs := err.(validator.ValidationErrors)
responses.ResponseError(w, r, errs.Translate(trans), "Upps, no hemos podido procesar tu solicitud")
return
}

err := uc.UserRepository.Create(newUser)
err = uc.UserRepository.Create(&newUser)

if err != nil {
fmt.Println(err)
http.Error(w, "User not found", http.StatusNotFound)
return
}

response := responses.ResponseOk(nil, "pong")
response := responses.ResponseOk(nil, "usuario creado correctamente!")
render.JSON(w, r, response)
}

Expand Down
24 changes: 23 additions & 1 deletion app/http/router/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,37 @@ package router
import (
"database/sql"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/render"
"github.com/lfcifuentes/go-repository-pattern/app/http/handler"
"github.com/lfcifuentes/go-repository-pattern/app/repository"
"os"
"strings"
"time"
)

func NewRouter(r *chi.Mux, db *sql.DB) *chi.Mux {
func NewRouter(db *sql.DB) *chi.Mux {

userRepository := repository.NewSQLUserRepository(db)
userController := handler.NewUserController(userRepository)

r := chi.NewRouter()

r.Use(middleware.Timeout(10 * time.Second))
r.Use(middleware.Logger)
r.Use(middleware.StripSlashes)
r.Use(render.SetContentType(render.ContentTypeJSON))

r.Use(cors.Handler(cors.Options{
AllowedOrigins: strings.Split(os.Getenv("ACCEPTED_DOMAINS"), ","),
AllowedMethods: []string{"GET", "POST", "PUT", "HEAD", "OPTIONS"},
AllowedHeaders: []string{
"Content-Type",
"Authorization",
},
}))

r.Route("/users", func(r chi.Router) {
r.Get("/", userController.GetAll)
r.Post("/", userController.Create)
Expand Down
13 changes: 10 additions & 3 deletions app/model/user.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package model

import (
"encoding/json"
"fmt"
"github.com/lfcifuentes/go-repository-pattern/app/security"
)
Expand All @@ -11,9 +12,15 @@ type Users struct {

type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password,omitempty"`
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
Password string `json:"password,omitempty" validate:"required"`
}

func UnmarshalUser(data []byte) (User, error) {
var u User
err := json.Unmarshal(data, &u)
return u, err
}

func (u *User) CreatePasswordHash() string {
Expand Down
4 changes: 2 additions & 2 deletions app/repository/user_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ func (r *SQLUserRepository) Create(user *model.User) error {
_, err := r.db.Exec(query, user.Name, user.CreatePasswordHash(), user.Email)

if err != nil {
fmt.Println(err)
return err
}

return errors.New("ERROR")
return nil
}

func (r *SQLUserRepository) ChangePassword(user *model.User) error {
Expand Down
9 changes: 9 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ go 1.19

require (
github.com/go-chi/chi/v5 v5.0.10
github.com/go-chi/cors v1.2.1
github.com/go-chi/render v1.0.3
github.com/go-playground/locales v0.14.1
github.com/go-playground/universal-translator v0.18.1
github.com/go-playground/validator/v10 v10.15.5
github.com/go-sql-driver/mysql v1.7.1
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.10.9
Expand All @@ -16,8 +20,13 @@ require (
require (
github.com/ajg/form v1.5.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
27 changes: 27 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,18 +1,32 @@
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
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/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.15.5 h1:LEBecTWb/1j5TNY1YYG2RcOUN3R7NLylN+x8TTueE24=
github.com/go-playground/validator/v10 v10.15.5/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
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/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand All @@ -22,11 +36,24 @@ github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
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/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.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
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=
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ func main() {
rootCmd.AddCommand(
cmd2.Run,
cmd2.Migrate,
cmd2.AppSecret,
)

if err := rootCmd.Execute(); err != nil {
Expand Down

0 comments on commit 6173b95

Please sign in to comment.