func recovery( c martini.Context, req *http.Request, ren render.Render, dec formDecoder, ) { defer func() { if r := recover(); r != nil { switch err := r.(type) { case jsonError: handleJsonError(err, ren) case authError: authenticate(err, dec, ren, req) case userError: ren.HTML(200, "error", m{ "Message": formatMessage(err.Error()), }) case csql.Error: ren.HTML(200, "error", m{ "Message": formatMessage(err.Error()), }) default: panic(r) } } }() c.Next() }
func Auth(session sessions.Session, c martini.Context, r render.Render) { v := session.Get("userid") fmt.Println(v) if v == nil { r.Redirect("/login") } else { c.Next() } }
//Simple auth handler based on a global key. This may have to be rewritten... func authHandler(r *http.Request, ctx martini.Context, ren render.Render) { log.Println(r.Header) if r.Header.Get("Authorization") != APIKey { ren.Text(http.StatusUnauthorized, "Invalid authorization") return } //Call the next handler ctx.Next() }
func gitHubAuthMiddleware(req *http.Request, res http.ResponseWriter, r render.Render, c martini.Context) { // Verify origin is GH template := make(map[string]string) template["contactUrl"] = os.Getenv("CONTACT_URL") template["contactValue"] = os.Getenv("CONTACT_VALUE") template["message"] = "There was an authenticating your account." err := req.ParseForm() if err != nil { log.Println(err) r.HTML(http.StatusBadRequest, "error", template) return } if len(req.Form["code"]) != 1 { r.HTML(http.StatusUnauthorized, "error", template) return } // If legit, attempt to get token payload := make(map[string]string) payload["client_id"] = os.Getenv("GITHUB_CLIENT_ID") payload["client_secret"] = os.Getenv("GITHUB_CLIENT_SECRET") payload["code"] = req.Form["code"][0] body, _ := json.Marshal(payload) ghReq, _ := http.NewRequest("POST", "https://github.com/login/oauth/access_token", bytes.NewReader(body)) ghReq.Header.Add("Content-Type", acceptHeader) ghReq.Header.Add("Accept", acceptHeader) ghReq.Header.Add("User-Agent", userAgent) ghRes, err := http.DefaultClient.Do(ghReq) // check status code if err != nil { log.Println(err) r.HTML(http.StatusServiceUnavailable, "error", template) return } ghPayload, err := ioutil.ReadAll(ghRes.Body) if err != nil { log.Println(err) r.HTML(http.StatusInternalServerError, "error", template) return } var ghJSON map[string]interface{} err = json.Unmarshal(ghPayload, &ghJSON) if err != nil { log.Println(err) r.HTML(http.StatusInternalServerError, "error", template) return } token, ok := ghJSON["access_token"].(string) if !ok { r.HTML(http.StatusOK, "error", template) return } c.Map(token) c.Next() http.Redirect(res, req, "/award", http.StatusFound) }
// Middleware ... func Middleware(ctx martini.Context, r *http.Request, w http.ResponseWriter) { sessionID := ensureCookie(r, w) session := sessionStore.Get(sessionID) ctx.Map(session) ctx.Next() sessionStore.Set(session) }
func (c *ConnectionLimit) Handler(ctx martini.Context, rw http.ResponseWriter) { // {{{ if atomic.AddInt32(&c.numConnections, 1) > c.limit { http.Error(rw, "maximum connections exceeded", http.StatusServiceUnavailable) atomic.AddInt32(&c.numConnections, -1) return } ctx.Next() atomic.AddInt32(&c.numConnections, -1) } // }}}
func Document(c martini.Context, w http.ResponseWriter, r *http.Request) { if !yaag.IsOn() { c.Next() return } apiCall := models.ApiCall{} writer := httptest.NewRecorder() c.MapTo(writer, (*http.ResponseWriter)(nil)) middleware.Before(&apiCall, r) c.Next() middleware.After(&apiCall, writer, w, r) }
func Register(db *gorm.DB, c martini.Context, body *user.Account, rw http.ResponseWriter) { if db == nil { panic("db is not exist") } account := Account{DB: db} res := account.Register(body) if res.Status == http.StatusOK { c.Map(res.Body) c.Next() } Response(res, rw) }
func jsonResp(c martini.Context) { defer func() { if r := recover(); r != nil { if err, ok := r.(error); ok { if _, ok := err.(jsonError); ok { panic(r) } else { panic(jsonError{err}) } } } }() c.Next() }
func ShowBlog(params martini.Params, r render.Render, c martini.Context) { id, err := strconv.ParseInt(params["id"], 0, 64) if err != nil { c.Next() return } post, e := models.GetPost(id) if e != nil { HandleError(404, r) return } r.HTML(200, "blogs/show", post) }
/* Check Authorization token */ func AuthenticationMiddleware(req *http.Request, context martini.Context, r render.Render) { token := req.Header.Get("Authorization") if token == "" { r.Error(401) } uid, err := getUserUidFromToken(token) if err != nil { r.Error(401) } else { context.Map(*uid) context.Next() } }
//If we don't write a response here, the next handler will execute func auth(req *http.Request, rendr render.Render, ctx martini.Context, db *gorm.DB) { tokenStr := req.Header.Get("Authorization") token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) { if token.Method != signingMethod { log.Println("token.Method != signingMethod") return nil, fmt.Errorf("Invalid signingMethod") } return secretKey, nil }) if err != nil { log.Println(err.Error()) log.Println("token was:", tokenStr) rendr.Text(http.StatusUnauthorized, err.Error()) return } if !token.Valid { rendr.Text(http.StatusUnauthorized, "Invalid token") return } userID, ok := token.Claims["id"].(float64) if !ok { rendr.Text(http.StatusInternalServerError, "Bad token") return } acc, err := findAccount(db, &account{ID: int(userID)}) if err != nil { rendr.Text(http.StatusNotFound, "User not found") return } //Attach the current user to the context for other handlers //Pass by value because we don't want to manipulate the object for each request, causes race //conditions. Instead, let's do everything in transactions wher we `select` the account first ctx.Map(acc) ctx.Next() }
func requestLogger(res http.ResponseWriter, req *http.Request, c martini.Context) { if skipLogging[req.URL.Path] { return } start := time.Now() addr := req.Header.Get("X-Real-IP") if addr == "" { addr = req.Header.Get("X-Forwarded-For") if addr == "" { addr = req.RemoteAddr } } logger.Printf("Started %s %s for %s", req.Method, req.URL.Path, addr) rw := res.(martini.ResponseWriter) c.Next() logger.Printf("Completed %v %s in %v\n", rw.Status(), http.StatusText(rw.Status()), time.Since(start)) }
func Middleware(ctx martini.Context, r *http.Request, w http.ResponseWriter) { assets := regexp.MustCompile(`.*assets.*`) if r.URL.Path != "/login" && !assets.MatchString(r.URL.Path) && r.URL.Path != "/" && r.URL.Path != "/socket.io/" { sessionId := EnsureCookie(r, w) session := SessionStorage.Get(sessionId) ctx.Map(session) ctx.Next() SessionStorage.Set(session) } token := jwt.New(jwt.GetSigningMethod("HS256")) token.Claims["Name"] = "token" token.Claims["exp"] = time.Now().Add(time.Minute * 5).Unix() tokenString, err := token.SignedString([]byte(TOKEN_STR)) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("Token Signing error: %v\n", err) fmt.Fprintln(w, "Sorry, error while Signing Token!") } cookie, err := r.Cookie(TOKEN_NAME) if err == nil { if cookie.Value != "" { tokenString = cookie.Value } } session := SessionStorage.Get(tokenString) ctx.Map(session) ctx.Next() SessionStorage.Set(session) }
// PARAMS is a middleware binder for injecting the params into each handler func PARAMS(req *http.Request, c martini.Context) { req.ParseForm() response := req.Form c.Map(response) c.Next() }
func Handler(c martini.Context) { startTime := time.Now() c.Next() agent.HTTPTimer.UpdateSince(startTime) }
// // Middleware called every call that requires user Authentication // It injects the Auth object in handlers that require it to work // Return the user in this context or an anonymous user and an error // Should be used .Logged to identify if it's an anonymous user // and use .GetUser to get this context user or the anonymous user the error object // func AuthMiddleware(c martini.Context, db DB, r render.Render, req *http.Request) { anonymous := &User{ UserId: "anonymous", UserName: "******", PicId: "default", FullName: "Usuario Anonimo", LikeCount: 0, Creation: time.Now(), LastUpdate: time.Now(), Deleted: false, Admin: false, } // Try to get the credentials from Authorization header or credentials cookie credentials := req.Header.Get("Authorization") if credentials == "" { cookie, err := req.Cookie("credentials") if err == nil { credentials = cookie.Value } } if credentials == "" { err := errors.New("Voce nao apresentou credenciais de autorizacao") userAuth := &UserAuth{anonymous, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Handler aborted // If the nex handler aborted, by an empty return // So he can't go on without user, let's alert user AccessDeniedHandler(r, req, err) } return } // Len of our 41 (20:20) char encoded in base64 is 56 // (C++) long base64EncodedSize = 4 * (int)Math.Ceiling(originalSizeInBytes / 3.0); if len(credentials) != 56 { err := errors.New("Credenciais de authorizacao apresentadas sao invalidas.") userAuth := &UserAuth{anonymous, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Handler aborted AccessDeniedHandler(r, req, err) } return } token, err := decodeAuth(credentials) if err != nil { userAuth := &UserAuth{anonymous, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Handler aborted AccessDeniedHandler(r, req, err) } return } obj, err := db.Get(Token{}, token.TokenId, token.UserId) if err != nil { userAuth := &UserAuth{anonymous, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Handler aborted AccessDeniedHandler(r, req, err) } return } if obj == nil { // This tokenid was not found err = errors.New("Credenciais fornecidas nao foram encontradas") userAuth := &UserAuth{anonymous, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Handler aborted AccessDeniedHandler(r, req, err) } return } token = obj.(*Token) obj, err = db.Get(User{}, token.UserId) if err != nil { userAuth := &UserAuth{anonymous, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Handler aborted AccessDeniedHandler(r, req, err) } return } user := obj.(*User) userAuth := &UserAuth{user: user, err: nil} // Here the next handler has got the user c.MapTo(userAuth, (*Auth)(nil)) }
func (s *Shutdown) Handler(c martini.Context) { s.wg.Add(1) c.Next() s.wg.Done() }
func AuthMiddleware(c martini.Context, db DB, r render.Render, req *http.Request) { header := req.Header.Get("Authorization") if header == "" { err := errors.New("Voce nao apresentou credenciais de autorizacao") userAuth := &UserAuth{nil, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // If the nex handler aborted, empty return // So he can't go on without user, let's alert user AccessDeniedHandler(r, req, err) } return } // Len of our 41 (20:20) char encoded in base64 is 56 // (C++) long base64EncodedSize = 4 * (int)Math.Ceiling(originalSizeInBytes / 3.0); if len(header) < 56 { err := errors.New("Credenciais de authorizacao apresentadas sao invalidas.") userAuth := &UserAuth{nil, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Response the user AccessDeniedHandler(r, req, err) } return } auth, err := decodeAuth(header) if err != nil { userAuth := &UserAuth{nil, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Response the user AccessDeniedHandler(r, req, err) } return } i := strings.Index(auth, ":") if i == -1 { err = errors.New("Credenciais de authorizacao estao corrompidas") userAuth := &UserAuth{nil, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Response the user AccessDeniedHandler(r, req, err) } return } tokenid := auth[:i] userid := auth[i+1:] obj, err := db.Get(Token{}, tokenid) if err != nil { userAuth := &UserAuth{nil, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Response the user AccessDeniedHandler(r, req, err) } return } if obj == nil { // This tokenid was not found err = errors.New("Credenciais fornecidas nao foram encontradas") userAuth := &UserAuth{nil, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Response the user AccessDeniedHandler(r, req, err) } return } token := obj.(*Token) if token.UserId != userid { err = errors.New("Usuario nao identificado pelas credenciais fornecidas") userAuth := &UserAuth{nil, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Response the user AccessDeniedHandler(r, req, err) } return } obj, err = db.Get(User{}, userid) if err != nil { userAuth := &UserAuth{nil, err} c.MapTo(userAuth, (*Auth)(nil)) c.Next() // Call the next handler if !c.Written() { // Response the user AccessDeniedHandler(r, req, err) } return } user := obj.(*User) userAuth := &UserAuth{user: user, err: nil} // Here the next handler has got the user c.MapTo(userAuth, (*Auth)(nil)) }
func (g *GracefulShutdown) Handler(c martini.Context) { g.wg.Add(1) c.Next() g.wg.Done() }
func nothing(c martini.Context) { c.Next() }