Commit ea2039c1 authored by astaxie's avatar astaxie

golint plugins

parent 68ec133a
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
// // maybe store in configure, maybe in database // // maybe store in configure, maybe in database
// } // }
// //
// beego.InsertFilter("*", beego.BeforeRouter,apiauth.APIAuthWithFunc(getAppSecret, 360)) // beego.InsertFilter("*", beego.BeforeRouter,apiauth.APISecretAuth(getAppSecret, 360))
// //
// Infomation: // Infomation:
// //
...@@ -68,8 +68,10 @@ import ( ...@@ -68,8 +68,10 @@ import (
"github.com/astaxie/beego/context" "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 { func APIBaiscAuth(appid, appkey string) beego.FilterFunc {
ft := func(aid string) string { ft := func(aid string) string {
if aid == appid { if aid == appid {
...@@ -77,10 +79,11 @@ func APIBaiscAuth(appid, appkey string) beego.FilterFunc { ...@@ -77,10 +79,11 @@ func APIBaiscAuth(appid, appkey string) beego.FilterFunc {
} }
return "" 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) { return func(ctx *context.Context) {
if ctx.Input.Query("appid") == "" { if ctx.Input.Query("appid") == "" {
ctx.ResponseWriter.WriteHeader(403) ctx.ResponseWriter.WriteHeader(403)
...@@ -116,13 +119,14 @@ func APIAuthWithFunc(f AppIdToAppSecret, timeout int) beego.FilterFunc { ...@@ -116,13 +119,14 @@ func APIAuthWithFunc(f AppIdToAppSecret, timeout int) beego.FilterFunc {
return return
} }
if ctx.Input.Query("signature") != 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.ResponseWriter.WriteHeader(403)
ctx.WriteString("auth failed") 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) { func Signature(appsecret, method string, params url.Values, RequestURI string) (result string) {
var query string var query string
pa := make(map[string]string) pa := make(map[string]string)
...@@ -139,11 +143,11 @@ func Signature(appsecret, method string, params url.Values, RequestURI string) ( ...@@ -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]) 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 sha256 := sha256.New
hash := hmac.New(sha256, []byte(appsecret)) hash := hmac.New(sha256, []byte(appsecret))
hash.Write([]byte(string_to_sign)) hash.Write([]byte(stringToSign))
return base64.StdEncoding.EncodeToString(hash.Sum(nil)) return base64.StdEncoding.EncodeToString(hash.Sum(nil))
} }
......
...@@ -46,6 +46,7 @@ import ( ...@@ -46,6 +46,7 @@ import (
var defaultRealm = "Authorization Required" var defaultRealm = "Authorization Required"
// Basic is the http basic auth
func Basic(username string, password string) beego.FilterFunc { func Basic(username string, password string) beego.FilterFunc {
secrets := func(user, pass string) bool { secrets := func(user, pass string) bool {
return user == username && pass == password return user == username && pass == password
...@@ -53,6 +54,7 @@ func Basic(username string, password string) beego.FilterFunc { ...@@ -53,6 +54,7 @@ func Basic(username string, password string) beego.FilterFunc {
return NewBasicAuthenticator(secrets, defaultRealm) return NewBasicAuthenticator(secrets, defaultRealm)
} }
// NewBasicAuthenticator return the BasicAuth
func NewBasicAuthenticator(secrets SecretProvider, Realm string) beego.FilterFunc { func NewBasicAuthenticator(secrets SecretProvider, Realm string) beego.FilterFunc {
return func(ctx *context.Context) { return func(ctx *context.Context) {
a := &BasicAuth{Secrets: secrets, Realm: Realm} a := &BasicAuth{Secrets: secrets, Realm: Realm}
...@@ -62,17 +64,19 @@ func NewBasicAuthenticator(secrets SecretProvider, Realm string) beego.FilterFun ...@@ -62,17 +64,19 @@ func NewBasicAuthenticator(secrets SecretProvider, Realm string) beego.FilterFun
} }
} }
// SecretProvider is the SecretProvider function
type SecretProvider func(user, pass string) bool type SecretProvider func(user, pass string) bool
// BasicAuth store the SecretProvider and Realm
type BasicAuth struct { type BasicAuth struct {
Secrets SecretProvider Secrets SecretProvider
Realm string Realm string
} }
//Checks the username/password combination from the request. Returns // CheckAuth Checks the username/password combination from the request. Returns
//either an empty string (authentication failed) or the name of the // either an empty string (authentication failed) or the name of the
//authenticated user. // authenticated user.
//Supports MD5 and SHA1 password entries // Supports MD5 and SHA1 password entries
func (a *BasicAuth) CheckAuth(r *http.Request) string { func (a *BasicAuth) CheckAuth(r *http.Request) string {
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 || s[0] != "Basic" { if len(s) != 2 || s[0] != "Basic" {
...@@ -94,8 +98,8 @@ func (a *BasicAuth) CheckAuth(r *http.Request) string { ...@@ -94,8 +98,8 @@ func (a *BasicAuth) CheckAuth(r *http.Request) string {
return "" return ""
} }
//http.Handler for BasicAuth which initiates the authentication process // RequireAuth http.Handler for BasicAuth which initiates the authentication process
//(or requires reauthentication). // (or requires reauthentication).
func (a *BasicAuth) RequireAuth(w http.ResponseWriter, r *http.Request) { func (a *BasicAuth) RequireAuth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="`+a.Realm+`"`) w.Header().Set("WWW-Authenticate", `Basic realm="`+a.Realm+`"`)
w.WriteHeader(401) w.WriteHeader(401)
......
...@@ -25,21 +25,23 @@ import ( ...@@ -25,21 +25,23 @@ import (
"github.com/astaxie/beego/context" "github.com/astaxie/beego/context"
) )
type HttpHeaderGuardRecorder struct { // HTTPHeaderGuardRecorder is httptest.ResponseRecorder with own http.Header
type HTTPHeaderGuardRecorder struct {
*httptest.ResponseRecorder *httptest.ResponseRecorder
savedHeaderMap http.Header savedHeaderMap http.Header
} }
func NewRecorder() *HttpHeaderGuardRecorder { // NewRecorder return HttpHeaderGuardRecorder
return &HttpHeaderGuardRecorder{httptest.NewRecorder(), nil} 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.ResponseRecorder.WriteHeader(code)
gr.savedHeaderMap = gr.ResponseRecorder.Header() gr.savedHeaderMap = gr.ResponseRecorder.Header()
} }
func (gr *HttpHeaderGuardRecorder) Header() http.Header { func (gr *HTTPHeaderGuardRecorder) Header() http.Header {
if gr.savedHeaderMap != nil { if gr.savedHeaderMap != nil {
// headers were written. clone so we don't get updates // headers were written. clone so we don't get updates
clone := make(http.Header) clone := make(http.Header)
...@@ -47,9 +49,8 @@ func (gr *HttpHeaderGuardRecorder) Header() http.Header { ...@@ -47,9 +49,8 @@ func (gr *HttpHeaderGuardRecorder) Header() http.Header {
clone[k] = v clone[k] = v
} }
return clone return clone
} else {
return gr.ResponseRecorder.Header()
} }
return gr.ResponseRecorder.Header()
} }
func Test_AllowAll(t *testing.T) { func Test_AllowAll(t *testing.T) {
......
...@@ -50,17 +50,17 @@ ...@@ -50,17 +50,17 @@
// beego.AddNamespace(ns) // beego.AddNamespace(ns)
// } // }
// //
package jwt package jwt
import ( import (
"io/ioutil"
"net/http"
"time"
"github.com/astaxie/beego" "github.com/astaxie/beego"
"github.com/astaxie/beego/context" "github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs" "github.com/astaxie/beego/logs"
goJwt "github.com/dgrijalva/jwt-go" goJwt "github.com/dgrijalva/jwt-go"
"io/ioutil"
"net/http"
"time"
) )
// Options for the JWT Auth // Options for the JWT Auth
...@@ -70,11 +70,13 @@ type Options struct { ...@@ -70,11 +70,13 @@ type Options struct {
WhiteList []string WhiteList []string
} }
// RSAKeys store PrivateKey and PublicKey
var RSAKeys struct { var RSAKeys struct {
PrivateKey []byte PrivateKey []byte
PublicKey []byte PublicKey []byte
} }
// AuthRequest retunn FilterFunc
func AuthRequest(o *Options) beego.FilterFunc { func AuthRequest(o *Options) beego.FilterFunc {
RSAKeys.PrivateKey, _ = ioutil.ReadFile(o.PrivateKeyPath) RSAKeys.PrivateKey, _ = ioutil.ReadFile(o.PrivateKeyPath)
RSAKeys.PublicKey, _ = ioutil.ReadFile(o.PublicKeyPath) RSAKeys.PublicKey, _ = ioutil.ReadFile(o.PublicKeyPath)
...@@ -101,26 +103,29 @@ func AuthRequest(o *Options) beego.FilterFunc { ...@@ -101,26 +103,29 @@ func AuthRequest(o *Options) beego.FilterFunc {
} }
} }
// oprations for Jwt // Controller oprations for Jwt
type JwtController struct { type Controller struct {
beego.Controller beego.Controller
} }
func (this *JwtController) URLMapping() { // URLMapping is used to mapping the string to method
this.Mapping("IssueToken", this.IssueToken) func (c *Controller) URLMapping() {
c.Mapping("IssueToken", c.IssueToken)
} }
// IssueToken function
// @Title IssueToken // @Title IssueToken
// @Description Issue a Json Web Token // @Description Issue a Json Web Token
// @Success 200 string // @Success 200 string
// @Failure 403 no privilege to access // @Failure 403 no privilege to access
// @Failure 500 server inner error // @Failure 500 server inner error
// @router /issue-token [get] // @router /issue-token [get]
func (this *JwtController) IssueToken() { func (c *Controller) IssueToken() {
this.Data["json"] = CreateToken() c.Data["json"] = CreateToken()
this.ServeJson() c.ServeJSON()
} }
// CreateToken return the token
func CreateToken() map[string]string { func CreateToken() map[string]string {
log := logs.NewLogger(10000) log := logs.NewLogger(10000)
log.SetLogger("console", "") log.SetLogger("console", "")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment