Skip to content

Commit

Permalink
Merge pull request #76 from yoyofx/dev
Browse files Browse the repository at this point in the history
v1.5.1.2
  • Loading branch information
yoyofx authored Aug 20, 2020
2 parents 3c16459 + a06cd91 commit 024b856
Show file tree
Hide file tree
Showing 36 changed files with 1,339 additions and 81 deletions.
2 changes: 1 addition & 1 deletion Abstractions/HostBuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ func (host *HostBuilder) Build() IServiceHost {
host.Context.ApplicationServicesDef = services
applicationBuilder.SetHostBuildContext(host.Context)
host.Context.HostServices = services.Build() //serviceProvider
host.Context.RequestDelegate = applicationBuilder.Build() // ServeHTTP(w http.ResponseWriter, r *http.Request)
host.Context.RequestDelegate = applicationBuilder.Build() // ServeHTTP(w http.IResponseWriter, r *http.Request)
host.Context.ApplicationServices = services.Build() //serviceProvider

if host.lifeConfigure != nil {
Expand Down
12 changes: 5 additions & 7 deletions Abstractions/xlog/XLogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,7 @@ func GetXLogger(class string) ILogger {
func (log *XLogger) log(level LogLevel, format string, a ...interface{}) {
hostName, _ := os.Hostname()
message := format
if len(a[0].([]interface{})) > 0 {
message = fmt.Sprintf(format, a...)
}
message = fmt.Sprintf(format, a...)

start := time.Now()
info := LogInfo{
Expand All @@ -85,17 +83,17 @@ func (log *XLogger) log(level LogLevel, format string, a ...interface{}) {
}

func (log *XLogger) Debug(format string, a ...interface{}) {
log.log(DEBUG, format, a)
log.log(DEBUG, format, a...)
}

func (log *XLogger) Info(format string, a ...interface{}) {
log.log(INFO, format, a)
log.log(INFO, format, a...)
}

func (log *XLogger) Warning(format string, a ...interface{}) {
log.log(WARNING, format, a)
log.log(WARNING, format, a...)
}

func (log *XLogger) Error(format string, a ...interface{}) {
log.log(ERROR, format, a)
log.log(ERROR, format, a...)
}
11 changes: 11 additions & 0 deletions Examples/SimpleWeb/config_dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,14 @@ application:
static:
patten: "/"
webroot: "./Static"
jwt:
header: "Authorization"
secret: "12391JdeOW^%$#@"
prefix: "Bearer"
expires: 3
enable: true
skip_path: [
"/info",
"/v1/user/GetInfo"
]

6 changes: 6 additions & 0 deletions Examples/SimpleWeb/config_prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,9 @@ application:
static:
patten: "/"
webroot: "./Static"
jwt:
header: "Authorization"
secret: "12391JdeOW^%$#@"
prefix: "Bearer"
expires: 3
enable: true
7 changes: 5 additions & 2 deletions Examples/SimpleWeb/contollers/usercontroller.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,12 @@ func (controller UserController) GetUserName(ctx *Context.HttpContext, request *
return ActionResult.Json{Data: result}
}

func (controller UserController) PostUserInfo(request *RegisterRequest) ActionResult.IActionResult {
func (controller UserController) PostUserInfo(ctx *Context.HttpContext, request *RegisterRequest) ActionResult.IActionResult {

return ActionResult.Json{Data: Mvc.ApiResult{Success: true, Message: "ok", Data: request}}
return ActionResult.Json{Data: Mvc.ApiResult{Success: true, Message: "ok", Data: Context.H{
"user": ctx.GetUser(),
"request": request,
}}}
}

func (controller UserController) GetHtmlHello() ActionResult.IActionResult {
Expand Down
13 changes: 8 additions & 5 deletions Examples/SimpleWeb/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/yoyofx/yoyogo/WebFramework"
"github.com/yoyofx/yoyogo/WebFramework/Context"
"github.com/yoyofx/yoyogo/WebFramework/Endpoints"
"github.com/yoyofx/yoyogo/WebFramework/Middleware"
"github.com/yoyofx/yoyogo/WebFramework/Mvc"
"github.com/yoyofx/yoyogo/WebFramework/Router"
)
Expand All @@ -19,7 +20,7 @@ func SimpleDemo() {
Endpoints.UsePrometheus(router)

router.GET("/info", func(ctx *Context.HttpContext) {
ctx.JSON(200, Context.M{"info": "ok"})
ctx.JSON(200, Context.H{"info": "ok"})
})
}).Build().Run()
}
Expand All @@ -37,6 +38,7 @@ func CreateCustomBuilder() *Abstractions.HostBuilder {
return YoyoGo.NewWebHostBuilder().
UseConfiguration(configuration).
Configure(func(app *YoyoGo.WebApplicationBuilder) {
app.UseMiddleware(Middleware.NewRequestID())
app.UseStaticAssets()
app.UseEndpoints(registerEndpointRouterConfig)
app.UseMvc(func(builder *Mvc.ControllerBuilder) {
Expand All @@ -58,7 +60,8 @@ func registerEndpointRouterConfig(router Router.IRouterBuilder) {
Endpoints.UseHealth(router)
Endpoints.UseViz(router)
Endpoints.UsePrometheus(router)
//Endpoints.UsePprof(router)
Endpoints.UsePprof(router)
Endpoints.UseJwt(router)

router.GET("/error", func(ctx *Context.HttpContext) {
panic("http get error")
Expand Down Expand Up @@ -87,13 +90,13 @@ type UserInfo struct {
//HttpGet request: /info or /v1/api/info
//bind UserInfo for id,q1,username
func GetInfo(ctx *Context.HttpContext) {
ctx.JSON(200, Context.M{"info": "ok"})
ctx.JSON(200, Context.H{"info": "ok"})
}

func GetInfoByIOC(ctx *Context.HttpContext) {
var userAction models.IUserAction
_ = ctx.RequiredServices.GetService(&userAction)
ctx.JSON(200, Context.M{"info": "ok " + userAction.Login("zhang")})
ctx.JSON(200, Context.H{"info": "ok " + userAction.Login("zhang")})
}

//HttpPost request: /info/:id ?q1=abc&username=123
Expand All @@ -106,7 +109,7 @@ func PostInfo(ctx *Context.HttpContext) {

strResult := fmt.Sprintf("Name:%s , Q1:%s , bind: %s , routeData id:%s", pd_name, qs_q1, userInfo, id)

ctx.JSON(200, Context.M{"info": "hello world", "result": strResult})
ctx.JSON(200, Context.H{"info": "hello world", "result": strResult})
}

func getApplicationLifeEvent(life *Abstractions.ApplicationLife) {
Expand Down
26 changes: 26 additions & 0 deletions Test/jwt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package Test

import (
"fmt"
"github.com/stretchr/testify/assert"
"github.com/yoyofx/yoyogo/Utils/jwt"
"testing"
"time"
)

func TestCreateToken(t *testing.T) {
SecretKey := []byte("12391JdeOW^%$#@")
token, _ := jwt.CreateToken(SecretKey, "YDQ", 2222, int64(time.Now().Add(time.Hour*72).Unix()))
fmt.Println(token)

claims, err := jwt.ParseToken(token, SecretKey)
if nil != err {
fmt.Println(" err :", err)
}
fmt.Println("claims:", claims)
fmt.Println("claims uid:", claims.(jwt.MapClaims)["uid"])

assert.Equal(t, err, nil)
assert.Equal(t, int(claims.(jwt.MapClaims)["uid"].(float64)), 2222)
assert.Equal(t, claims.(jwt.MapClaims)["iss"], "YDQ")
}
22 changes: 21 additions & 1 deletion Utils/StringHelper.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package Utils

import "unicode"
import (
"reflect"
"unicode"
)

func PadLeft(s string, pad string, plength int) string {
for i := len(s); i < plength; i++ {
Expand All @@ -22,3 +25,20 @@ func LowercaseFirst(str string) string {
}
return ""
}

func Contains(obj interface{}, target interface{}) bool {
targetValue := reflect.ValueOf(target)
switch reflect.TypeOf(target).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < targetValue.Len(); i++ {
if targetValue.Index(i).Interface() == obj {
return true
}
}
case reflect.Map:
if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
return true
}
}
return false
}
134 changes: 134 additions & 0 deletions Utils/jwt/claims.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package jwt

import (
"crypto/subtle"
"fmt"
"time"
)

// For a type to be a Claims object, it must just have a Valid method that determines
// if the token is invalid for any supported reason
type Claims interface {
Valid() error
}

// Structured version of Claims Section, as referenced at
// https://tools.ietf.org/html/rfc7519#section-4.1
// See examples for how to use this with your own claim types
type StandardClaims struct {
Audience string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
Id string `json:"jti,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
Issuer string `json:"iss,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Subject string `json:"sub,omitempty"`
}

// Validates time based claims "exp, iat, nbf".
// There is no accounting for clock skew.
// As well, if any of the above claims are not in the token, it will still
// be considered a valid claim.
func (c StandardClaims) Valid() error {
vErr := new(ValidationError)
now := TimeFunc().Unix()

// The claims below are optional, by default, so if they are set to the
// default value in Go, let's not fail the verification for them.
if c.VerifyExpiresAt(now, false) == false {
delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0))
vErr.Inner = fmt.Errorf("token is expired by %v", delta)
vErr.Errors |= ValidationErrorExpired
}

if c.VerifyIssuedAt(now, false) == false {
vErr.Inner = fmt.Errorf("Token used before issued")
vErr.Errors |= ValidationErrorIssuedAt
}

if c.VerifyNotBefore(now, false) == false {
vErr.Inner = fmt.Errorf("token is not valid yet")
vErr.Errors |= ValidationErrorNotValidYet
}

if vErr.valid() {
return nil
}

return vErr
}

// Compares the aud claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool {
return verifyAud(c.Audience, cmp, req)
}

// Compares the exp claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool {
return verifyExp(c.ExpiresAt, cmp, req)
}

// Compares the iat claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool {
return verifyIat(c.IssuedAt, cmp, req)
}

// Compares the iss claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool {
return verifyIss(c.Issuer, cmp, req)
}

// Compares the nbf claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool {
return verifyNbf(c.NotBefore, cmp, req)
}

// ----- helpers

func verifyAud(aud string, cmp string, required bool) bool {
if aud == "" {
return !required
}
if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 {
return true
} else {
return false
}
}

func verifyExp(exp int64, now int64, required bool) bool {
if exp == 0 {
return !required
}
return now <= exp
}

func verifyIat(iat int64, now int64, required bool) bool {
if iat == 0 {
return !required
}
return now >= iat
}

func verifyIss(iss string, cmp string, required bool) bool {
if iss == "" {
return !required
}
if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 {
return true
} else {
return false
}
}

func verifyNbf(nbf int64, now int64, required bool) bool {
if nbf == 0 {
return !required
}
return now >= nbf
}
Loading

0 comments on commit 024b856

Please sign in to comment.