Skip to content

Commit

Permalink
Bump Fiber 1.4 to 2.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
sujit-baniya committed Oct 20, 2020
1 parent f02d6d7 commit c2d5ab1
Show file tree
Hide file tree
Showing 28 changed files with 319 additions and 328 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -26,7 +26,7 @@ The features include:

Thanks to following libraries:

* [Fiber](https://github.com/gofiber/fiber)
* [Fiber](https://github.com/gofiber/fiber/v2)
* [Xopen](https://github.com/brentp/xopen)
* [Gorm](https://github.com/go-gorm/gorm)
* [Zerolog](https://github.com/edersohe/zflogger)
Expand Down
6 changes: 3 additions & 3 deletions app/app.go
Expand Up @@ -5,11 +5,11 @@ import (
"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v2"
"github.com/go-redis/redis"
"github.com/gofiber/fiber"
"github.com/gofiber/session"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/session/v2"
"github.com/gofiber/template/html"
"github.com/itsursujit/flash"
"github.com/itsursujit/fiber-boilerplate/mail"
"github.com/itsursujit/flash"
"github.com/jinzhu/gorm"
"github.com/plutov/paypal/v3"
"github.com/rs/zerolog"
Expand Down
11 changes: 5 additions & 6 deletions auth/user.go
Expand Up @@ -3,7 +3,7 @@ package auth
import (
"errors"
"fmt"
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/v2"
. "github.com/itsursujit/fiber-boilerplate/app"
"github.com/itsursujit/fiber-boilerplate/config"
"github.com/itsursujit/fiber-boilerplate/models"
Expand Down Expand Up @@ -55,19 +55,18 @@ func Login(c *fiber.Ctx, userID uint, secret string) (config.Token, error) {
return token, err
}

func Logout(c *fiber.Ctx) {
func Logout(c *fiber.Ctx) error {
store := Session.Get(c)
store.Delete("user_id")
err := store.Save()
if err != nil {
panic(err)
}
c.ClearCookie()
c.Send("You are now logged out.")
return
return c.SendString("You are now logged out.")
}

func AuthCookie(c *fiber.Ctx) {
func AuthCookie(c *fiber.Ctx) error {
IsLoggedIn(c)
c.Next()
return c.Next()
}
25 changes: 13 additions & 12 deletions config/app.go
Expand Up @@ -3,9 +3,10 @@ package config
import (
"crypto/rand"
"fmt"
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/middleware"
"github.com/gofiber/pprof"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/pprof"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/template/html"
. "github.com/itsursujit/fiber-boilerplate/app"
"github.com/itsursujit/flash"
Expand Down Expand Up @@ -62,7 +63,7 @@ func GenerateAppKey(length int) {
func BootApp() {
LoadAppConfig()
TemplateEngine = html.NewFileSystem(pkger.Dir("/resources/views"), ".html")
App = fiber.New(&fiber.Settings{
App = fiber.New(fiber.Config{
ErrorHandler: CustomErrorHandler,
ServerHeader: "fiber-boilerplate",
Prefork: true,
Expand All @@ -73,9 +74,11 @@ func BootApp() {

App.Use(pprof.New())
App.Use(LoadHeaders)
App.Use(middleware.Favicon())
App.Use(middleware.Recover())
App.Use(middleware.Compress(middleware.CompressLevelBestSpeed))
App.Use(recover.New())
App.Use(compress.New(compress.Config{
Next: nil,
Level: compress.LevelBestSpeed,
}))
/*App.Use(csrf.New(csrf.Config{
CookieSecure: true,
}))*/
Expand All @@ -97,19 +100,17 @@ func BootApp() {
}
}

func CustomErrorHandler(c *fiber.Ctx, err error) {
func CustomErrorHandler(c *fiber.Ctx, err error) error {
// StatusCode defaults to 500
code := fiber.StatusInternalServerError
//nolint:misspell // Retrieve the custom statuscode if it's an fiber.*Error
if e, ok := err.(*fiber.Error); ok {
code = e.Code
} //nolint:gofmt,wsl
if c.Is("json") {
c.SendStatus(code)
_ = c.JSON(err)
return c.Status(code).JSON(err)
} else {
c.SendStatus(code)
_ = c.Render(fmt.Sprintf("errors/%d", code), fiber.Map{ //nolint:nolintlint,errcheck
return c.Status(code).Render(fmt.Sprintf("errors/%d", code), fiber.Map{ //nolint:nolintlint,errcheck
"error": err,
})
}
Expand Down
17 changes: 9 additions & 8 deletions config/auth.go
Expand Up @@ -7,7 +7,7 @@ import (
gormadapter "github.com/casbin/gorm-adapter/v2"
"github.com/dgrijalva/jwt-go"
_ "github.com/go-sql-driver/mysql"
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/v2"
. "github.com/itsursujit/fiber-boilerplate/app"
"time"
)
Expand Down Expand Up @@ -54,15 +54,15 @@ func SetupPermission() { //nolint:whitespace
Lookup: func(ctx *fiber.Ctx) string {
return "sujit"
},
Unauthorized: func(c *fiber.Ctx) {
Unauthorized: func(c *fiber.Ctx) error {
var err fiber.Error
err.Code = fiber.StatusUnauthorized
CustomErrorHandler(c, &err)
return CustomErrorHandler(c, &err)
},
Forbidden: func(c *fiber.Ctx) {
Forbidden: func(c *fiber.Ctx) error {
var err fiber.Error
err.Code = fiber.StatusForbidden
CustomErrorHandler(c, &err)
return CustomErrorHandler(c, &err)
},
}
}
Expand Down Expand Up @@ -127,12 +127,13 @@ func DeleteToken(c *fiber.Ctx) {
}

//RefreshToken refreshes the token
func RefreshToken(c *fiber.Ctx, secret string) {
func RefreshToken(c *fiber.Ctx, secret string) (Token, error) {
var t Token
u, err := ParseToken(c, secret)

if err != nil {
return
return t, err
}

CreateToken(c, u, secret)
return CreateToken(c, u, secret)
}
10 changes: 5 additions & 5 deletions config/headers.go
@@ -1,21 +1,21 @@
package config

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

func LoadHeaders(c *fiber.Ctx) {
func LoadHeaders(c *fiber.Ctx) error {
// Set some security headers:
c.Set("X-XSS-Protection", "1; mode=block")
c.Set("X-Content-Type-Options", "nosniff")
c.Set("X-Download-Options", "noopen")
c.Set("Strict-Transport-Security", "max-age=5184000")
c.Set("X-Frame-Options", "SAMEORIGIN")
c.Next()
return c.Next()
}

func LoadCacheHeaders(c *fiber.Ctx) {
func LoadCacheHeaders(c *fiber.Ctx) error {
c.Set("X-DNS-Prefetch-Control", "off")
c.Set("Pragma", "no-cache")
c.Set("Expires", "Fri, 01 Jan 1990 00:00:00 GMT")
c.Set("Cache-Control", "no-cache, must-revalidate, no-store, max-age=0, private")
c.Next()
return c.Next()
}
2 changes: 1 addition & 1 deletion config/mail.go
@@ -1,7 +1,7 @@
package config

import (
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/v2"
. "github.com/itsursujit/fiber-boilerplate/app"
"github.com/itsursujit/fiber-boilerplate/mail"
"github.com/valyala/bytebufferpool"
Expand Down
94 changes: 45 additions & 49 deletions config/role.go
Expand Up @@ -5,7 +5,7 @@ import (

"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v2"
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/v2"
)

// Config holds the configuration for the middleware
Expand All @@ -25,11 +25,11 @@ type PermissionMiddleware struct {

// Unauthorized defines the response body for unauthorized responses.
// Optional. Default: func(c *fiber.Ctx) string { c.SendStatus(401) }
Unauthorized func(*fiber.Ctx)
Unauthorized func(*fiber.Ctx) error

// Forbidden defines the response body for forbidden responses.
// Optional. Default: func(c *fiber.Ctx) string { c.SendStatus(403) }
Forbidden func(*fiber.Ctx)
Forbidden func(*fiber.Ctx) error
}

type validationRule int
Expand Down Expand Up @@ -77,7 +77,7 @@ type Options struct {

// RequiresPermissions tries to find the current subject and determine if the
// subject has the required permissions according to predefined Casbin policies.
func (cm *PermissionMiddleware) RequiresPermissions(permissions []string, opts ...func(o *Options)) func(*fiber.Ctx) {
func (cm *PermissionMiddleware) RequiresPermissions(permissions []string, opts ...func(o *Options)) func(*fiber.Ctx) error {

options := &Options{
ValidationRule: matchAll,
Expand All @@ -88,76 +88,73 @@ func (cm *PermissionMiddleware) RequiresPermissions(permissions []string, opts .
o(options)
}

return func(c *fiber.Ctx) {
return func(c *fiber.Ctx) error {
if len(permissions) == 0 {
c.Next()
return
return c.Next()
}

sub := cm.Lookup(c)
if len(sub) == 0 {
cm.Unauthorized(c)
return
return cm.Unauthorized(c)
}

if options.ValidationRule == matchAll {
for _, permission := range permissions {
vals := append([]string{sub}, options.PermissionParser(permission)...)
if ok, err := cm.Enforcer.Enforce(convertToInterface(vals)...); err != nil {
c.SendStatus(fiber.StatusInternalServerError)
return
return c.SendStatus(fiber.StatusInternalServerError)
} else if !ok {
cm.Forbidden(c)
return
return cm.Forbidden(c)

}
}
c.Next()
return
return c.Next()

} else if options.ValidationRule == atLeastOne {
for _, permission := range permissions {
vals := append([]string{sub}, options.PermissionParser(permission)...)
if ok, err := cm.Enforcer.Enforce(convertToInterface(vals)...); err != nil {
c.SendStatus(fiber.StatusInternalServerError)
return
return c.SendStatus(fiber.StatusInternalServerError)

} else if ok {
c.Next()
return
return c.Next()

}
}
cm.Forbidden(c)
return
return cm.Forbidden(c)

}

c.Next()
return c.Next()
}
}

// RoutePermission tries to find the current subject and determine if the
// subject has the required permissions according to predefined Casbin policies.
// This method uses http Path and Method as object and action.
func (cm *PermissionMiddleware) RoutePermission() func(*fiber.Ctx) {
return func(c *fiber.Ctx) {
func (cm *PermissionMiddleware) RoutePermission() func(*fiber.Ctx) error {
return func(c *fiber.Ctx) error {
sub := cm.Lookup(c)
if len(sub) == 0 {
cm.Unauthorized(c)
return
return cm.Unauthorized(c)

}
if ok, err := cm.Enforcer.Enforce(sub, c.Path(), c.Method()); err != nil {
c.SendStatus(fiber.StatusInternalServerError)
return
return c.SendStatus(fiber.StatusInternalServerError)

} else if !ok {
cm.Forbidden(c)
return
return cm.Forbidden(c)

}

c.Next()
return
return c.Next()

}
}

// RequiresRoles tries to find the current subject and determine if the
// subject has the required roles according to predefined Casbin policies.
func (cm *PermissionMiddleware) RequiresRoles(roles []string, opts ...func(o *Options)) func(*fiber.Ctx) {
func (cm *PermissionMiddleware) RequiresRoles(roles []string, opts ...func(o *Options)) func(*fiber.Ctx) error {
options := &Options{
ValidationRule: matchAll,
PermissionParser: permissionParserWithSeperator(":"),
Expand All @@ -166,45 +163,44 @@ func (cm *PermissionMiddleware) RequiresRoles(roles []string, opts ...func(o *Op
for _, o := range opts {
o(options)
}
return func(c *fiber.Ctx) { //nolint:wsl
return func(c *fiber.Ctx) error { //nolint:wsl
if len(roles) == 0 {
c.Next()
return
return c.Next()
}

sub := cm.Lookup(c)
if len(sub) == 0 {
cm.Unauthorized(c)
return
return cm.Unauthorized(c)

}

userRoles, err := cm.Enforcer.GetRolesForUser(sub)
if err != nil {
c.SendStatus(fiber.StatusInternalServerError)
return
return c.SendStatus(fiber.StatusInternalServerError)

}

if options.ValidationRule == matchAll {
for _, role := range roles {
if !contains(userRoles, role) {
cm.Forbidden(c)
return
return cm.Forbidden(c)

}
}
c.Next() //nolint:wsl
return
return c.Next() //nolint:wsl

} else if options.ValidationRule == atLeastOne {
for _, role := range roles {
if contains(userRoles, role) {
c.Next()
return
return c.Next()

}
}
cm.Forbidden(c)
return
return cm.Forbidden(c)

}

c.Next()
return c.Next()
}
}

Expand Down

0 comments on commit c2d5ab1

Please sign in to comment.