Skip to content

Commit

Permalink
golint plugins
Browse files Browse the repository at this point in the history
  • Loading branch information
astaxie committed Sep 12, 2015
1 parent 68ec133 commit ea2039c
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 31 deletions.
18 changes: 11 additions & 7 deletions plugins/apiauth/apiauth.go
Expand Up @@ -33,7 +33,7 @@
// // maybe store in configure, maybe in database
// }
//
// beego.InsertFilter("*", beego.BeforeRouter,apiauth.APIAuthWithFunc(getAppSecret, 360))
// beego.InsertFilter("*", beego.BeforeRouter,apiauth.APISecretAuth(getAppSecret, 360))
//
// Infomation:
//
Expand Down Expand Up @@ -68,19 +68,22 @@ import (
"github.com/astaxie/beego/context"
)

type AppIdToAppSecret func(string) string
// AppIDToAppSecret is used to get appsecret throw appid
type AppIDToAppSecret func(string) string

// APIBaiscAuth use the basic appid/appkey as the AppIdToAppSecret
func APIBaiscAuth(appid, appkey string) beego.FilterFunc {
ft := func(aid string) string {
if aid == appid {
return appkey
}
return ""
}
return APIAuthWithFunc(ft, 300)
return APISecretAuth(ft, 300)
}

func APIAuthWithFunc(f AppIdToAppSecret, timeout int) beego.FilterFunc {
// APISecretAuth use AppIdToAppSecret verify and
func APISecretAuth(f AppIDToAppSecret, timeout int) beego.FilterFunc {
return func(ctx *context.Context) {
if ctx.Input.Query("appid") == "" {
ctx.ResponseWriter.WriteHeader(403)
Expand Down Expand Up @@ -116,13 +119,14 @@ func APIAuthWithFunc(f AppIdToAppSecret, timeout int) beego.FilterFunc {
return
}
if ctx.Input.Query("signature") !=
Signature(appsecret, ctx.Input.Method(), ctx.Request.Form, ctx.Input.Uri()) {
Signature(appsecret, ctx.Input.Method(), ctx.Request.Form, ctx.Input.URI()) {
ctx.ResponseWriter.WriteHeader(403)
ctx.WriteString("auth failed")
}
}
}

// Signature used to generate signature with the appsecret/method/params/RequestURI
func Signature(appsecret, method string, params url.Values, RequestURI string) (result string) {
var query string
pa := make(map[string]string)
Expand All @@ -139,11 +143,11 @@ func Signature(appsecret, method string, params url.Values, RequestURI string) (
query = fmt.Sprintf("%v%v%v", query, vs.Keys[i], vs.Vals[i])
}
}
string_to_sign := fmt.Sprintf("%v\n%v\n%v\n", method, query, RequestURI)
stringToSign := fmt.Sprintf("%v\n%v\n%v\n", method, query, RequestURI)

sha256 := sha256.New
hash := hmac.New(sha256, []byte(appsecret))
hash.Write([]byte(string_to_sign))
hash.Write([]byte(stringToSign))
return base64.StdEncoding.EncodeToString(hash.Sum(nil))
}

Expand Down
16 changes: 10 additions & 6 deletions plugins/auth/basic.go
Expand Up @@ -46,13 +46,15 @@ import (

var defaultRealm = "Authorization Required"

// Basic is the http basic auth
func Basic(username string, password string) beego.FilterFunc {
secrets := func(user, pass string) bool {
return user == username && pass == password
}
return NewBasicAuthenticator(secrets, defaultRealm)
}

// NewBasicAuthenticator return the BasicAuth
func NewBasicAuthenticator(secrets SecretProvider, Realm string) beego.FilterFunc {
return func(ctx *context.Context) {
a := &BasicAuth{Secrets: secrets, Realm: Realm}
Expand All @@ -62,17 +64,19 @@ func NewBasicAuthenticator(secrets SecretProvider, Realm string) beego.FilterFun
}
}

// SecretProvider is the SecretProvider function
type SecretProvider func(user, pass string) bool

// BasicAuth store the SecretProvider and Realm
type BasicAuth struct {
Secrets SecretProvider
Realm string
}

//Checks the username/password combination from the request. Returns
//either an empty string (authentication failed) or the name of the
//authenticated user.
//Supports MD5 and SHA1 password entries
// CheckAuth Checks the username/password combination from the request. Returns
// either an empty string (authentication failed) or the name of the
// authenticated user.
// Supports MD5 and SHA1 password entries
func (a *BasicAuth) CheckAuth(r *http.Request) string {
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 || s[0] != "Basic" {
Expand All @@ -94,8 +98,8 @@ func (a *BasicAuth) CheckAuth(r *http.Request) string {
return ""
}

//http.Handler for BasicAuth which initiates the authentication process
//(or requires reauthentication).
// RequireAuth http.Handler for BasicAuth which initiates the authentication process
// (or requires reauthentication).
func (a *BasicAuth) RequireAuth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="`+a.Realm+`"`)
w.WriteHeader(401)
Expand Down
15 changes: 8 additions & 7 deletions plugins/cors/cors_test.go
Expand Up @@ -25,31 +25,32 @@ import (
"github.com/astaxie/beego/context"
)

type HttpHeaderGuardRecorder struct {
// HTTPHeaderGuardRecorder is httptest.ResponseRecorder with own http.Header
type HTTPHeaderGuardRecorder struct {
*httptest.ResponseRecorder
savedHeaderMap http.Header
}

func NewRecorder() *HttpHeaderGuardRecorder {
return &HttpHeaderGuardRecorder{httptest.NewRecorder(), nil}
// NewRecorder return HttpHeaderGuardRecorder
func NewRecorder() *HTTPHeaderGuardRecorder {
return &HTTPHeaderGuardRecorder{httptest.NewRecorder(), nil}
}

func (gr *HttpHeaderGuardRecorder) WriteHeader(code int) {
func (gr *HTTPHeaderGuardRecorder) WriteHeader(code int) {
gr.ResponseRecorder.WriteHeader(code)
gr.savedHeaderMap = gr.ResponseRecorder.Header()
}

func (gr *HttpHeaderGuardRecorder) Header() http.Header {
func (gr *HTTPHeaderGuardRecorder) Header() http.Header {
if gr.savedHeaderMap != nil {
// headers were written. clone so we don't get updates
clone := make(http.Header)
for k, v := range gr.savedHeaderMap {
clone[k] = v
}
return clone
} else {
return gr.ResponseRecorder.Header()
}
return gr.ResponseRecorder.Header()
}

func Test_AllowAll(t *testing.T) {
Expand Down
27 changes: 16 additions & 11 deletions plugins/jwt/jwt.go
Expand Up @@ -50,17 +50,17 @@
// beego.AddNamespace(ns)
// }
//

package jwt

import (
"io/ioutil"
"net/http"
"time"

"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
goJwt "github.com/dgrijalva/jwt-go"
"io/ioutil"
"net/http"
"time"
)

// Options for the JWT Auth
Expand All @@ -70,11 +70,13 @@ type Options struct {
WhiteList []string
}

// RSAKeys store PrivateKey and PublicKey
var RSAKeys struct {
PrivateKey []byte
PublicKey []byte
}

// AuthRequest retunn FilterFunc
func AuthRequest(o *Options) beego.FilterFunc {
RSAKeys.PrivateKey, _ = ioutil.ReadFile(o.PrivateKeyPath)
RSAKeys.PublicKey, _ = ioutil.ReadFile(o.PublicKeyPath)
Expand All @@ -101,26 +103,29 @@ func AuthRequest(o *Options) beego.FilterFunc {
}
}

// oprations for Jwt
type JwtController struct {
// Controller oprations for Jwt
type Controller struct {
beego.Controller
}

func (this *JwtController) URLMapping() {
this.Mapping("IssueToken", this.IssueToken)
// URLMapping is used to mapping the string to method
func (c *Controller) URLMapping() {
c.Mapping("IssueToken", c.IssueToken)
}

// IssueToken function
// @Title IssueToken
// @Description Issue a Json Web Token
// @Success 200 string
// @Failure 403 no privilege to access
// @Failure 500 server inner error
// @router /issue-token [get]
func (this *JwtController) IssueToken() {
this.Data["json"] = CreateToken()
this.ServeJson()
func (c *Controller) IssueToken() {
c.Data["json"] = CreateToken()
c.ServeJSON()
}

// CreateToken return the token
func CreateToken() map[string]string {
log := logs.NewLogger(10000)
log.SetLogger("console", "")
Expand Down

0 comments on commit ea2039c

Please sign in to comment.