Skip to content

Commit

Permalink
Merge pull request #21 from RobyFerro/ext-request-validation
Browse files Browse the repository at this point in the history
Ext request validation
  • Loading branch information
RobyFerro committed Sep 2, 2021
2 parents a55ab33 + f29775c commit 56edba8
Show file tree
Hide file tree
Showing 8 changed files with 35 additions and 45 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@
All notable changes to the "Go-web" will be documented in this file.

## [Unreleased]

## [v0.7.2-beta] - 2021-09-02
### Changed
- Removed pointers in route middlewares

### Added
- Support for request validation in routing

## [v0.7.1-beta] - 2021-08-30
### Changed
- Moved command service register in "command" module
Expand Down
34 changes: 7 additions & 27 deletions app/http/controller/auth.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package controller

import (
"encoding/json"
"github.com/RobyFerro/go-web/app/auth"
"github.com/labstack/gommon/log"
"github.com/RobyFerro/go-web/app/http/validation"
"net/http"
"time"

"github.com/RobyFerro/go-web-framework/kernel"
"github.com/RobyFerro/go-web-framework/tool"
"github.com/RobyFerro/go-web/database/model"
"github.com/gorilla/sessions"
"github.com/jinzhu/gorm"
Expand All @@ -18,23 +18,13 @@ type AuthController struct {
kernel.BaseController
}

type Credentials struct {
Username string `json:"username" valid:"required"`
Password string `json:"password" valid:"required"`
}

// JWTAuthentication provides user authentication with JWT
func (c *AuthController) JWTAuthentication(db *gorm.DB, conf *kernel.ServerConf) {
var payload Credentials
var payload validation.Credentials
var user *model.User
var jwt auth.JWTAuth

if err := tool.DecodeJsonRequest(c.Request, &payload); err != nil {
log.Error(err)
c.Response.WriteHeader(http.StatusInternalServerError)
}

if valid := tool.ValidateRequest(payload, c.Response); !valid {
if err := json.NewDecoder(c.Request.Body).Decode(&payload); err != nil {
c.Response.WriteHeader(http.StatusUnprocessableEntity)
return
}
Expand All @@ -47,9 +37,7 @@ func (c *AuthController) JWTAuthentication(db *gorm.DB, conf *kernel.ServerConf)
} else {
user = u
}
// End check password

// Generate JWT token
jwt.Name = user.Name
jwt.Surname = user.Surname
jwt.Username = user.Username
Expand All @@ -63,21 +51,13 @@ func (c *AuthController) JWTAuthentication(db *gorm.DB, conf *kernel.ServerConf)
_, _ = c.Response.Write([]byte(`{"token":"` + token + `"}`))
}

// End JWT token generation
return
}

// BasicAuthentication perform basic authentication method
func (c *AuthController) BasicAuthentication(db *gorm.DB, session *sessions.CookieStore) {
var payload Credentials

if err := tool.DecodeJsonRequest(c.Request, &payload); err != nil {
log.Error(err)
c.Response.WriteHeader(http.StatusInternalServerError)
return
}

if valid := tool.ValidateRequest(payload, c.Response); !valid {
var payload validation.Credentials
if err := json.NewDecoder(c.Request.Body).Decode(&payload); err != nil {
c.Response.WriteHeader(http.StatusUnprocessableEntity)
return
}
Expand Down Expand Up @@ -114,7 +94,7 @@ func createAuthSession(s *sessions.CookieStore, user *model.User, r *http.Reques
}

// Attempt login
func attemptLogin(db *gorm.DB, cred *Credentials) (*model.User, bool) {
func attemptLogin(db *gorm.DB, cred *validation.Credentials) (*model.User, bool) {
var user model.User
if err := db.Where("username = ?", cred.Username).Find(&user); err != nil && err.RecordNotFound() {
return nil, false
Expand Down
17 changes: 2 additions & 15 deletions app/http/controller/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/RobyFerro/go-web-framework/kernel"
"github.com/RobyFerro/go-web-framework/tool"
jwt "github.com/RobyFerro/go-web/app/auth"
"github.com/RobyFerro/go-web/app/http/validation"
"github.com/RobyFerro/go-web/database/model"
"github.com/jinzhu/gorm"
"golang.org/x/crypto/bcrypt"
Expand All @@ -17,25 +18,11 @@ type UserController struct {

// Insert this method will be used to insert a new user in main DB (SQL)
func (c *UserController) Insert(db *gorm.DB) {

type NewUser struct {
Name string `json:"name" valid:"required,alpha"`
Surname string `json:"surname" valid:"required,alpha"`
Username string `json:"username" valid:"required,alpha"`
Password string `json:"password" valid:"required,alpha"`
RepeatPassword string `json:"repeat-password" valid:"required,alpha"`
}

var data NewUser
var data validation.NewUser
if err := tool.DecodeJsonRequest(c.Request, &data); err != nil {
log.Fatal(err)
}

// Validation
if valid := tool.ValidateRequest(data, c.Response); valid == false {
return
}

if data.Password != data.RepeatPassword {
c.Response.WriteHeader(422)
_, _ = c.Response.Write([]byte(`{"Name":"Password","Err":{},"CustomErrorMessageExists":"false"`))
Expand Down
6 changes: 6 additions & 0 deletions app/http/validation/login.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package validation

type Credentials struct {
Username string `json:"username" valid:"required"`
Password string `json:"password" valid:"required"`
}
9 changes: 9 additions & 0 deletions app/http/validation/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package validation

type NewUser struct {
Name string `json:"name" valid:"required,alpha"`
Surname string `json:"surname" valid:"required,alpha"`
Username string `json:"username" valid:"required,alpha"`
Password string `json:"password" valid:"required,alpha"`
RepeatPassword string `json:"repeat-password" valid:"required,alpha"`
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ go 1.16
//replace github.com/RobyFerro/go-web-framework => custom path

require (
github.com/RobyFerro/go-web-framework v0.7.0-beta
github.com/RobyFerro/go-web-framework v0.7.1-beta
github.com/auth0/go-jwt-middleware v0.0.0-20200810150920-a32d7af194d1
github.com/brianvoe/gofakeit/v4 v4.3.0
github.com/denisenkom/go-mssqldb v0.10.0 // indirect
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
github.com/RobyFerro/dig v1.12.1-0.20210820090948-eef4b5ae40c2 h1:RaMKVl0nfJD/neflcaPmWJYyzt43HfX5kmN3gdWGjRw=
github.com/RobyFerro/dig v1.12.1-0.20210820090948-eef4b5ae40c2/go.mod h1:jfL50cNXPp4gqLYHPyZMyUS9D05UTUJCdkxNU6gftXc=
github.com/RobyFerro/go-web-framework v0.7.0-beta h1:D/vZAWAa/E/KxMFKMv8lFX3Hfk4FlNkgb98+UWUBxO4=
github.com/RobyFerro/go-web-framework v0.7.0-beta/go.mod h1:wB/7eaLLMAq+y4rGnKxvrRlw+c3RoO6i825jBCd44gU=
github.com/RobyFerro/go-web-framework v0.7.1-beta h1:yGp2GDx1WH5exWT7qdHZ1BauKSSA+xZxcmWVgIEJBRU=
github.com/RobyFerro/go-web-framework v0.7.1-beta/go.mod h1:wB/7eaLLMAq+y4rGnKxvrRlw+c3RoO6i825jBCd44gU=
github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
github.com/auth0/go-jwt-middleware v0.0.0-20200810150920-a32d7af194d1 h1:lnVadil6o8krZE47ms2PCxhXcki/UwoqiB0axOIV3mk=
github.com/auth0/go-jwt-middleware v0.0.0-20200810150920-a32d7af194d1/go.mod h1:mF0ip7kTEFtnhBJbd/gJe62US3jykNN+dcZoZakJCCA=
Expand Down
3 changes: 3 additions & 0 deletions router/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package router
import (
"github.com/RobyFerro/go-web-framework/kernel"
"github.com/RobyFerro/go-web/app/http/middleware"
"github.com/RobyFerro/go-web/app/http/validation"
)

var AuthRouter = kernel.HTTRouter{
Expand All @@ -12,6 +13,7 @@ var AuthRouter = kernel.HTTRouter{
Path: "/login",
Action: "AuthController@JWTAuthentication",
Method: "POST",
Validation: &validation.Credentials{},
Description: "Perform login",
Middleware: []kernel.Middleware{
middleware.LoggingMiddleware{},
Expand All @@ -22,6 +24,7 @@ var AuthRouter = kernel.HTTRouter{
Path: "/basic-auth",
Action: "AuthController@BasicAuthentication",
Method: "POST",
Validation: &validation.Credentials{},
Description: "Basic authentication",
Middleware: []kernel.Middleware{
middleware.LoggingMiddleware{},
Expand Down

0 comments on commit 56edba8

Please sign in to comment.