func WebThingProgram(w http.ResponseWriter, r *http.Request) { thing := context.Get(r, ContextKeyThing).(*Thing) account := context.Get(r, ContextKeyAccount).(*Account) if !thing.EditableById(account.Character) { http.Error(w, "No access to program", http.StatusForbidden) return } var newProgram *ThingProgram if r.Method == "POST" { program := r.PostFormValue("text") newProgram = NewProgram(program) if newProgram.Error == nil { thing.Program = newProgram World.SaveThing(thing) http.Redirect(w, r, fmt.Sprintf("%sprogram", thing.GetURL()), http.StatusSeeOther) return } } RenderTemplate(w, r, "thing/page/program.html", map[string]interface{}{ "IncludeCodeMirror": true, "Title": fmt.Sprintf("Edit program – %s", thing.Name), "Thing": thing, "Program": newProgram, }) }
// ServeHTTP will store the request details in the analytics store if necessary and proxy the request to it's // final destination, this is invoked by the ProxyHandler or right at the start of a request chain if the URL // Spec states the path is Ignored func (s SuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Make sure we get the correct target URL if s.Spec.APIDefinition.Proxy.StripListenPath { r.URL.Path = strings.Replace(r.URL.Path, s.Spec.Proxy.ListenPath, "", 1) } if config.EnableAnalytics { t := time.Now() // Track the key ID if it exists authHeaderValue := context.Get(r, AuthHeaderValue) keyName := "" if authHeaderValue != nil { keyName = authHeaderValue.(string) } // Track version data version := s.Spec.getVersionFromRequest(r) if version == "" { version = "Non Versioned" } // If OAuth, we need to grab it from the session, which may or may not exist OauthClientID := "" thisSessionState := context.Get(r, SessionData) if thisSessionState != nil { OauthClientID = thisSessionState.(SessionState).OauthClientID } thisRecord := AnalyticsRecord{ r.Method, r.URL.Path, r.ContentLength, r.Header.Get("User-Agent"), t.Day(), t.Month(), t.Year(), t.Hour(), 200, keyName, t, version, s.Spec.APIDefinition.Name, s.Spec.APIDefinition.APIID, s.Spec.APIDefinition.OrgID, OauthClientID} go analytics.RecordHit(thisRecord) } s.Proxy.ServeHTTP(w, r) if doMemoryProfile { pprof.WriteHeapProfile(profileFile) } context.Clear(r) }
// HandleError is the actual error handler and will store the error details in analytics if analytics processing is enabled. func (e ErrorHandler) HandleError(w http.ResponseWriter, r *http.Request, err string, errCode int) { if config.EnableAnalytics { t := time.Now() // Track the key ID if it exists authHeaderValue := context.Get(r, AuthHeaderValue) keyName := "" if authHeaderValue != nil { keyName = authHeaderValue.(string) } version := e.Spec.getVersionFromRequest(r) if version == "" { version = "Non Versioned" } if e.TykMiddleware.Spec.APIDefinition.Proxy.StripListenPath { r.URL.Path = strings.Replace(r.URL.Path, e.TykMiddleware.Spec.Proxy.ListenPath, "", 1) } OauthClientID := "" thisSessionState := context.Get(r, SessionData) if thisSessionState != nil { OauthClientID = thisSessionState.(SessionState).OauthClientID } thisRecord := AnalyticsRecord{ r.Method, r.URL.Path, r.ContentLength, r.Header.Get("User-Agent"), t.Day(), t.Month(), t.Year(), t.Hour(), errCode, keyName, t, version, e.Spec.APIDefinition.Name, e.Spec.APIDefinition.APIID, e.Spec.APIDefinition.OrgID, OauthClientID} go analytics.RecordHit(thisRecord) } w.Header().Add("Content-Type", "application/json") w.Header().Add("X-Generator", "tyk.io") log.Debug("Returning error header") w.WriteHeader(errCode) thisError := APIError{fmt.Sprintf("%s", err)} templates.ExecuteTemplate(w, "error.json", &thisError) if doMemoryProfile { pprof.WriteHeapProfile(profileFile) } // Clean up context.Clear(r) }
func PostAccessTokens(w http.ResponseWriter, r *http.Request) { db := context.Get(r, "db").(*sqlx.DB) cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore) session, _ := cookieStore.Get(r, "resourcedmaster-session") currentUser := session.Values["user"].(*dal.UserRow) clusterID, err := getIdFromPath(w, r) if err != nil { libhttp.HandleErrorJson(w, err) return } level := r.FormValue("Level") _, err = dal.NewAccessToken(db).Create(nil, currentUser.ID, clusterID, level) if err != nil { libhttp.HandleErrorJson(w, err) return } http.Redirect(w, r, "/clusters", 301) }
func PostClustersCurrent(w http.ResponseWriter, r *http.Request) { cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore) session, _ := cookieStore.Get(r, "resourcedmaster-session") redirectPath := "/" recentRequestPathInterface := session.Values["recentRequestPath"] if recentRequestPathInterface != nil { redirectPath = recentRequestPathInterface.(string) } clusterIDString := r.FormValue("ClusterID") clusterID, err := strconv.ParseInt(clusterIDString, 10, 64) if err != nil { http.Redirect(w, r, redirectPath, 301) return } clusterRows := context.Get(r, "clusters").([]*dal.ClusterRow) for _, clusterRow := range clusterRows { if clusterRow.ID == clusterID { session.Values["currentCluster"] = clusterRow err := session.Save(r, w) if err != nil { libhttp.HandleErrorJson(w, err) return } break } } http.Redirect(w, r, redirectPath, 301) }
func PostApiHosts(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") db := context.Get(r, "db").(*sqlx.DB) accessTokenRow := context.Get(r, "accessTokenRow").(*dal.AccessTokenRow) dataJson, err := ioutil.ReadAll(r.Body) if err != nil { libhttp.HandleErrorJson(w, err) return } hostRow, err := dal.NewHost(db).CreateOrUpdate(nil, accessTokenRow, dataJson) if err != nil { libhttp.HandleErrorJson(w, err) return } hostRowJson, err := json.Marshal(hostRow) if err != nil { libhttp.HandleErrorJson(w, err) return } w.Write(hostRowJson) }
// API_SMTP handles requests for the /api/smtp/ endpoint func API_SMTP(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "GET": ss, err := models.GetSMTPs(ctx.Get(r, "user_id").(int64)) if err != nil { Logger.Println(err) } JSONResponse(w, ss, http.StatusOK) //POST: Create a new SMTP and return it as JSON case r.Method == "POST": s := models.SMTP{} // Put the request into a page err := json.NewDecoder(r.Body).Decode(&s) if err != nil { JSONResponse(w, models.Response{Success: false, Message: "Invalid request"}, http.StatusBadRequest) return } // Check to make sure the name is unique _, err = models.GetSMTPByName(s.Name, ctx.Get(r, "user_id").(int64)) if err != gorm.ErrRecordNotFound { JSONResponse(w, models.Response{Success: false, Message: "SMTP name already in use"}, http.StatusConflict) Logger.Println(err) return } s.ModifiedDate = time.Now() s.UserId = ctx.Get(r, "user_id").(int64) err = models.PostSMTP(&s) if err != nil { JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) return } JSONResponse(w, s, http.StatusCreated) } }
func (c *appContext) newReviewHandler(w http.ResponseWriter, r *http.Request) { user, err := userget(r) if err != nil { log.Println(err) } repo := ReviewRepo{c.db.C("reviews")} params := context.Get(r, "params").(httprouter.Params) skillslug := params.ByName("slug") body := context.Get(r, "body").(*ReviewResource) log.Println(skillslug) body.Data.SkillSlug = skillslug body.Data.Username = user.Username err = repo.Create(&body.Data) if err != nil { log.Println(err) } c.newReviewFeed(&body.Data) w.Header().Set("Content-Type", "application/vnd.api+json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(body) }
// New creates a new HttpHandler for the alice middleware package func (k KeyExpired) New() func(http.Handler) http.Handler { aliceHandler := func(h http.Handler) http.Handler { thisHandler := func(w http.ResponseWriter, r *http.Request) { thisSessionState := context.Get(r, SessionData).(SessionState) authHeaderValue := context.Get(r, AuthHeaderValue).(string) keyExpired := authManager.IsKeyExpired(&thisSessionState) if keyExpired { log.WithFields(logrus.Fields{ "path": r.URL.Path, "origin": r.RemoteAddr, "key": authHeaderValue, }).Info("Attempted access from expired key.") handler := ErrorHandler{k.TykMiddleware} handler.HandleError(w, r, "Key has expired, please renew", 403) return } // Request is valid, carry on h.ServeHTTP(w, r) } return http.HandlerFunc(thisHandler) } return aliceHandler }
func RefreshToken(w http.ResponseWriter, r *http.Request) { userID := context.Get(r, "user_id").(uint64) token := context.Get(r, "user_token").(string) var reqBody authorizePutBody if appErr := decode(r, &reqBody); appErr != nil { reply.Err(w, appErr) return } userToken := model.UserToken{UserID: userID, Token: token, RefreshToken: reqBody.RefreshToken} if valid, err := userToken.RefreshTokenValid(); !valid || err != nil { if !valid { reply.Err(w, ae.TokenInvalid("", err, "refresh_token")) } else { reply.Err(w, ae.DB("", err)) } return } if err := userToken.Delete(); err != nil { reply.Err(w, ae.DB("", err)) return } newToken := model.UserToken{UserID: userID} if err := newToken.Add(); err != nil { reply.Err(w, ae.DB("", err)) return } reply.OK(w, newToken) }
func FilterIfOwnerRelations(r *http.Request, filter *usecases.Filter) *usecases.Filter { ownerRelationsCtx := context.Get(r, "ownerRelations") if ownerRelationsCtx != nil { currentSession := context.Get(r, "currentSession").(domain.Session) idKey := "accountId" if context.Get(r, "resource").(string) == "accounts" { idKey = "id" } if filter == nil { filter = &usecases.Filter{ Where: map[string]interface{}{idKey: currentSession.AccountID}, } } else { if filter.Where == nil { filter.Where = map[string]interface{}{idKey: currentSession.AccountID} } else { filter.Where[idKey] = currentSession.AccountID } } } return filter }
// API_Groups returns details about the requested group. If the campaign is not // valid, API_Groups returns null. func API_Groups(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "GET": gs, err := models.GetGroups(ctx.Get(r, "user_id").(int64)) if err != nil { JSONResponse(w, models.Response{Success: false, Message: "No groups found"}, http.StatusNotFound) return } JSONResponse(w, gs, http.StatusOK) //POST: Create a new group and return it as JSON case r.Method == "POST": g := models.Group{} // Put the request into a group err := json.NewDecoder(r.Body).Decode(&g) if err != nil { JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest) return } _, err = models.GetGroupByName(g.Name, ctx.Get(r, "user_id").(int64)) if err != gorm.RecordNotFound { JSONResponse(w, models.Response{Success: false, Message: "Group name already in use"}, http.StatusConflict) return } g.ModifiedDate = time.Now() g.UserId = ctx.Get(r, "user_id").(int64) err = models.PostGroup(&g) if err != nil { JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) return } w.Header().Set("Location", "http://localhost:3333/api/groups/"+string(g.Id)) JSONResponse(w, g, http.StatusCreated) } }
func PostMetadata(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore) session, _ := cookieStore.Get(r, "resourcedmaster-session") currentClusterInterface := session.Values["currentCluster"] if currentClusterInterface == nil { http.Redirect(w, r, "/", 301) return } currentCluster := currentClusterInterface.(*dal.ClusterRow) key := r.FormValue("Key") data := r.FormValue("Data") db := context.Get(r, "db").(*sqlx.DB) _, err := dal.NewMetadata(db).CreateOrUpdate(nil, currentCluster.ID, key, []byte(data)) if err != nil { libhttp.HandleErrorJson(w, err) return } http.Redirect(w, r, "/metadata", 301) }
// PostLogin performs login. func PostLogin(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") db := context.Get(r, "db").(*sqlx.DB) cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore) email := r.FormValue("Email") password := r.FormValue("Password") u := models.NewUser(db) user, err := u.GetUserByEmailAndPassword(nil, email, password) if err != nil { libhttp.HandleErrorJson(w, err) return } session, _ := cookieStore.Get(r, "$GO_BOOTSTRAP_PROJECT_NAME-session") session.Values["user"] = user err = session.Save(r, w) if err != nil { libhttp.HandleErrorJson(w, err) return } http.Redirect(w, r, "/", 302) }
// API_Campaigns returns a list of campaigns if requested via GET. // If requested via POST, API_Campaigns creates a new campaign and returns a reference to it. func API_Campaigns(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "GET": cs, err := models.GetCampaigns(ctx.Get(r, "user_id").(int64)) if err != nil { fmt.Println(err) } JSONResponse(w, cs, http.StatusOK) //POST: Create a new campaign and return it as JSON case r.Method == "POST": c := models.Campaign{} // Put the request into a campaign err := json.NewDecoder(r.Body).Decode(&c) if err != nil { JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest) return } err = models.PostCampaign(&c, ctx.Get(r, "user_id").(int64)) if err != nil { JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) return } Worker.Queue <- &c JSONResponse(w, c, http.StatusCreated) } }
// API_Pages handles requests for the /api/pages/ endpoint func API_Pages(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "GET": ps, err := models.GetPages(ctx.Get(r, "user_id").(int64)) if err != nil { fmt.Println(err) } JSONResponse(w, ps, http.StatusOK) //POST: Create a new page and return it as JSON case r.Method == "POST": p := models.Page{} // Put the request into a page err := json.NewDecoder(r.Body).Decode(&p) if err != nil { JSONResponse(w, models.Response{Success: false, Message: "Invalid request"}, http.StatusBadRequest) return } _, err = models.GetPageByName(p.Name, ctx.Get(r, "user_id").(int64)) if err != gorm.RecordNotFound { JSONResponse(w, models.Response{Success: false, Message: "Page name already in use"}, http.StatusConflict) Logger.Println(err) return } p.ModifiedDate = time.Now() p.UserId = ctx.Get(r, "user_id").(int64) err = models.PostPage(&p) if err != nil { JSONResponse(w, models.Response{Success: false, Message: "Error inserting page"}, http.StatusInternalServerError) return } JSONResponse(w, p, http.StatusCreated) } }
func DeleteSavedQueriesID(w http.ResponseWriter, r *http.Request) { savedQueryID, err := getIdFromPath(w, r) if err != nil { libhttp.HandleErrorJson(w, err) return } db := context.Get(r, "db").(*sqlx.DB) cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore) session, _ := cookieStore.Get(r, "resourcedmaster-session") currentUser := session.Values["user"].(*rm_dal.UserRow) sq := rm_dal.NewSavedQuery(db) savedQueryRow, err := sq.GetByID(nil, savedQueryID) if currentUser.ID != savedQueryRow.UserID { err := errors.New("Modifying other user's saved query is not allowed.") libhttp.HandleErrorJson(w, err) return } err = sq.DeleteByID(nil, savedQueryID) if err != nil { libhttp.HandleErrorJson(w, err) return } http.Redirect(w, r, "/", 301) }
func PostSavedQueries(w http.ResponseWriter, r *http.Request) { db := context.Get(r, "db").(*sqlx.DB) cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore) session, _ := cookieStore.Get(r, "resourcedmaster-session") currentUser := session.Values["user"].(*rm_dal.UserRow) accessTokenRow, err := rm_dal.NewAccessToken(db).GetByUserID(nil, currentUser.ID) if err != nil { libhttp.HandleErrorJson(w, err) return } savedQuery := r.FormValue("SavedQuery") _, err = rm_dal.NewSavedQuery(db).CreateOrUpdate(nil, accessTokenRow, savedQuery) if err != nil { libhttp.HandleErrorJson(w, err) return } http.Redirect(w, r, "/?q="+savedQuery, 301) }
func PostApiMetadataKey(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") db := context.Get(r, "db").(*sqlx.DB) accessTokenRow := context.Get(r, "accessTokenRow").(*dal.AccessTokenRow) dataJson, err := ioutil.ReadAll(r.Body) if err != nil { libhttp.HandleErrorJson(w, err) return } vars := mux.Vars(r) key := vars["key"] metadataRow, err := dal.NewMetadata(db).CreateOrUpdate(nil, accessTokenRow.ClusterID, key, dataJson) if err != nil { libhttp.HandleErrorJson(w, err) return } metadataRowJson, err := json.Marshal(metadataRow) if err != nil { libhttp.HandleErrorJson(w, err) return } w.Write(metadataRowJson) }
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail func (k *KeyExpired) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) { sess, ok := context.GetOk(r, SessionData) if !ok { return errors.New("Session state is missing or unset! Please make sure that auth headers are properly applied"), 403 } thisSessionState := sess.(SessionState) if thisSessionState.IsInactive { authHeaderValue := context.Get(r, AuthHeaderValue).(string) log.WithFields(logrus.Fields{ "path": r.URL.Path, "origin": GetIPFromRequest(r), "key": authHeaderValue, }).Info("Attempted access from inactive key.") // Fire a key expired event go k.TykMiddleware.FireEvent(EVENT_KeyExpired, EVENT_KeyExpiredMeta{ EventMetaDefault: EventMetaDefault{Message: "Attempted access from inactive key.", OriginatingRequest: EncodeRequestToEvent(r)}, Path: r.URL.Path, Origin: GetIPFromRequest(r), Key: authHeaderValue, }) // Report in health check ReportHealthCheckValue(k.Spec.Health, KeyFailure, "-1") return errors.New("Key is inactive, please renew"), 403 } keyExpired := k.Spec.AuthManager.IsKeyExpired(&thisSessionState) if keyExpired { authHeaderValue := context.Get(r, AuthHeaderValue).(string) log.WithFields(logrus.Fields{ "path": r.URL.Path, "origin": GetIPFromRequest(r), "key": authHeaderValue, }).Info("Attempted access from expired key.") // Fire a key expired event go k.TykMiddleware.FireEvent(EVENT_KeyExpired, EVENT_KeyExpiredMeta{ EventMetaDefault: EventMetaDefault{Message: "Attempted access from expired key."}, Path: r.URL.Path, Origin: GetIPFromRequest(r), Key: authHeaderValue, }) // Report in health check ReportHealthCheckValue(k.Spec.Health, KeyFailure, "-1") return errors.New("Key has expired, please renew"), 403 } return nil, 200 }
//DefaultData returns common to all pages template data func DefaultData(r *http.Request) map[string]interface{} { return map[string]interface{}{ "ActiveUser": context.Get(r, "user"), //signed in models.User "Active": "", //active uri shortening for menu item highlight "Title": "", //page title:w "SignupEnabled": context.Get(r, "signup_enabled"), //signup route is enabled (otherwise everyone can signup ;) csrf.TemplateTag: csrf.TemplateField(r), } }
// SetClusters sets clusters data in context based on logged in user ID. func SetClusters(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore) session, _ := cookieStore.Get(r, "resourcedmaster-session") userRowInterface := session.Values["user"] if userRowInterface == nil { http.Redirect(w, r, "/login", 301) return } userRow := userRowInterface.(*dal.UserRow) db := context.Get(r, "db").(*sqlx.DB) clusterRows, err := dal.NewCluster(db).AllClustersByUserID(nil, userRow.ID) if err != nil { libhttp.HandleErrorJson(w, err) return } context.Set(r, "clusters", clusterRows) // Set currentCluster if not previously set. if len(clusterRows) > 0 { currentClusterInterface := session.Values["currentCluster"] if currentClusterInterface == nil { session.Values["currentCluster"] = clusterRows[0] err := session.Save(r, w) if err != nil { libhttp.HandleErrorJson(w, err) return } } } // Set currentClusterJson currentClusterInterface := session.Values["currentCluster"] if currentClusterInterface != nil { currentClusterRow := currentClusterInterface.(*dal.ClusterRow) currentClusterJson, err := json.Marshal(currentClusterRow) if err != nil { libhttp.HandleErrorJson(w, err) return } context.Set(r, "currentClusterJson", currentClusterJson) } else { context.Set(r, "currentClusterJson", []byte("{}")) } next.ServeHTTP(w, r) }) }
func ApiWSAccessToken(w http.ResponseWriter, r *http.Request) { accessToken := mux.Vars(r)["id"] db := context.Get(r, "db").(*sqlx.DB) // Check if access token exists accessTokenRow, err := dal.NewAccessToken(db).GetByAccessToken(nil, accessToken) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if accessTokenRow == nil { err = errors.New("Unrecognized access token") http.Error(w, err.Error(), http.StatusInternalServerError) return } // Upgrade connection to full duplex TCP connection conn, err := upgrader.Upgrade(w, r, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } wsTraffickers := context.Get(r, "wsTraffickers").(*wstrafficker.WSTraffickers) wsTrafficker, err := wsTraffickers.SaveConnection(accessToken, conn) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } ticker := time.NewTicker(pingPeriod) defer func() { ticker.Stop() conn.Close() }() for { select { case message, ok := <-wsTrafficker.Chans.Send: if !ok { wsTrafficker.Write(websocket.CloseMessage, []byte{}) wsTraffickers.DeleteConnection(accessToken, wsTrafficker.Hostname) return } if err := wsTrafficker.Write(websocket.TextMessage, message); err != nil { return } case <-ticker.C: if err := wsTrafficker.Write(websocket.PingMessage, []byte{}); err != nil { return } } } }
func WebThingAccess(w http.ResponseWriter, r *http.Request) { account := context.Get(r, ContextKeyAccount).(*Account) thing := context.Get(r, ContextKeyThing).(*Thing) // Only the owner can edit the access lists. if !thing.OwnedById(account.Character) { http.Error(w, "No access to access lists", http.StatusForbidden) return } if r.Method == "POST" { changed := false if adminsText := r.PostFormValue("admins"); adminsText != "" { var adminIds []ThingId err := json.Unmarshal([]byte(adminsText), &adminIds) if err != nil { // TODO: set a flash http.Redirect(w, r, fmt.Sprintf("%saccess", thing.GetURL()), http.StatusSeeOther) return } thing.AdminList = adminIds changed = true } // TODO: handle allows if deniedText := r.PostFormValue("denied"); deniedText != "" { var deniedIds []ThingId err := json.Unmarshal([]byte(deniedText), &deniedIds) if err != nil { // TODO: set a flash http.Redirect(w, r, fmt.Sprintf("%saccess", thing.GetURL()), http.StatusSeeOther) return } thing.DenyList = deniedIds changed = true } if changed { World.SaveThing(thing) } http.Redirect(w, r, fmt.Sprintf("%saccess", thing.GetURL()), http.StatusSeeOther) return } RenderTemplate(w, r, "thing/page/access.html", map[string]interface{}{ "Title": fmt.Sprintf("Edit access lists – %s", thing.Name), "Thing": thing, }) }
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail func (k *KeyExpired) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) { thisSessionState := context.Get(r, SessionData).(SessionState) authHeaderValue := context.Get(r, AuthHeaderValue).(string) if thisSessionState.IsInactive { log.WithFields(logrus.Fields{ "path": r.URL.Path, "origin": r.RemoteAddr, "key": authHeaderValue, }).Info("Attempted access from inactive key.") // Fire a key expired event authHeaderValue := context.Get(r, AuthHeaderValue) go k.TykMiddleware.FireEvent(EVENT_KeyExpired, EVENT_KeyExpiredMeta{ EventMetaDefault: EventMetaDefault{Message: "Attempted access from inactive key.", OriginatingRequest: EncodeRequestToEvent(r)}, Path: r.URL.Path, Origin: r.RemoteAddr, Key: authHeaderValue.(string), }) // Report in health check ReportHealthCheckValue(k.Spec.Health, KeyFailure, "1") return errors.New("Key is inactive, please renew"), 403 } keyExpired := k.Spec.AuthManager.IsKeyExpired(&thisSessionState) if keyExpired { log.WithFields(logrus.Fields{ "path": r.URL.Path, "origin": r.RemoteAddr, "key": authHeaderValue, }).Info("Attempted access from expired key.") // Fire a key expired event authHeaderValue := context.Get(r, AuthHeaderValue) go k.TykMiddleware.FireEvent(EVENT_KeyExpired, EVENT_KeyExpiredMeta{ EventMetaDefault: EventMetaDefault{Message: "Attempted access from expired key."}, Path: r.URL.Path, Origin: r.RemoteAddr, Key: authHeaderValue.(string), }) // Report in health check ReportHealthCheckValue(k.Spec.Health, KeyFailure, "1") return errors.New("Key has expired, please renew"), 403 } return nil, 200 }
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail func (m *GranularAccessMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) { thisSessionState := context.Get(r, SessionData).(SessionState) authHeaderValue := context.Get(r, AuthHeaderValue).(string) sessionVersionData, foundAPI := thisSessionState.AccessRights[m.Spec.APIID] if foundAPI == false { log.Debug("Version not found") return nil, 200 } if sessionVersionData.AllowedURLs == nil { log.Debug("No allowed URLS") return nil, 200 } if len(sessionVersionData.AllowedURLs) == 0 { log.Debug("No allowed URLS") return nil, 200 } for _, accessSpec := range sessionVersionData.AllowedURLs { log.Debug("Checking: ", r.URL.Path) log.Debug("Against: ", accessSpec.URL) asRegex, regexpErr := regexp.Compile(accessSpec.URL) if regexpErr != nil { log.Error("Regex error: ", regexpErr) return nil, 200 } match := asRegex.MatchString(r.URL.Path) if match { log.Debug("Match!") for _, method := range accessSpec.Methods { if method == r.Method { return nil, 200 } } } } // No paths matched, disallow log.WithFields(logrus.Fields{ "path": r.URL.Path, "origin": GetIPFromRequest(r), "key": authHeaderValue, "api_found": false, }).Info("Attempted access to unauthorised endpoint (Granular).") return errors.New("Access to this resource has been disallowed"), 403 }
// RequireLogin is a simple middleware which checks to see if the user is currently logged in. // If not, the function returns a 302 redirect to the login page. func RequireLogin(handler http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { user := ctx.Get(r, "user") role := ctx.Get(r, "role") if user != nil { log.Println("userId:", user, " userRole:", role) handler.ServeHTTP(w, r) } else { w.WriteHeader(http.StatusForbidden) } } }
func WebThingTable(w http.ResponseWriter, r *http.Request) { thing := context.Get(r, ContextKeyThing).(*Thing) account := context.Get(r, ContextKeyAccount).(*Account) if !thing.EditableById(account.Character) { http.Error(w, "No access to table data", http.StatusForbidden) return } if r.Method == "POST" { updateText := r.PostFormValue("updated_data") var updates map[string]interface{} err := json.Unmarshal([]byte(updateText), &updates) if err != nil { // aw carp // TODO: set a flash? http.Redirect(w, r, fmt.Sprintf("%stable", thing.GetURL()), http.StatusSeeOther) return } deleteText := r.PostFormValue("deleted_data") var deletes map[string]interface{} err = json.Unmarshal([]byte(deleteText), &deletes) if err != nil { // aw carp // TODO: set a flash? http.Redirect(w, r, fmt.Sprintf("%stable", thing.GetURL()), http.StatusSeeOther) return } thing.Table = mergeMapInto(updates, thing.Table) thing.Table = deleteMapFrom(deletes, thing.Table) World.SaveThing(thing) http.Redirect(w, r, fmt.Sprintf("%stable", thing.GetURL()), http.StatusSeeOther) return } RenderTemplate(w, r, "thing/page/table.html", map[string]interface{}{ "Title": fmt.Sprintf("Edit all data – %s", thing.Name), "Thing": thing, "json": func(v interface{}) interface{} { output, err := json.MarshalIndent(v, "", " ") if err != nil { escapedError := template.JSEscapeString(err.Error()) message := fmt.Sprintf("/* error encoding JSON: %s */ {}", escapedError) return template.JS(message) } return template.JS(output) }, }) }
func WebThingEdit(w http.ResponseWriter, r *http.Request) { thing := context.Get(r, ContextKeyThing).(*Thing) account := context.Get(r, ContextKeyAccount).(*Account) if !thing.EditableById(account.Character) { RenderTemplate(w, r, "thing/thing-no-edit.html", map[string]interface{}{ "Title": thing.Name, "Thing": thing, }) return } if r.Method == "POST" { // TODO: player names should be unique? // TODO: account loginnames should match their player names? thing.Name = r.PostFormValue("name") // TODO: validate?? thing.Table["description"] = r.PostFormValue("description") if thing.Type == PlayerThing { thing.Table["glance"] = r.PostFormValue("glance") thing.Table["pronouns"] = r.PostFormValue("pronouns") } parentIdStr := r.PostFormValue("parent") parentId64, err := strconv.ParseInt(parentIdStr, 10, 64) if err != nil { // TODO: set a flash? cause an error? eh } else { parentId := ThingId(parentId64) newParent := World.ThingForId(parentId) // TODO: does the viewer control newParent sufficiently to move the thing there? if newParent == nil { // TODO: set a flash? cause an error? eh } else { thing.Parent = parentId } } World.SaveThing(thing) http.Redirect(w, r, thing.GetURL(), http.StatusSeeOther) return } typeName := thing.Type.String() templateName := fmt.Sprintf("thing/type/%s.html", typeName) RenderTemplate(w, r, templateName, map[string]interface{}{ "Title": thing.Name, "Thing": thing, }) }
func (c *appContext) updatetaskHandler(w http.ResponseWriter, r *http.Request) { params := context.Get(r, "params").(httprouter.Params) body := context.Get(r, "body").(*tasksModel.TaskResource) body.Data.Id = bson.ObjectIdHex(params.ByName("id")) repo := tasksModel.TaskRepo{c.db.C("tasks")} err := repo.Update(&body.Data) if err != nil { panic(err) } w.WriteHeader(204) w.Write([]byte("\n")) }