func LogOne(res http.ResponseWriter, req *http.Request, c martini.Context, logger *log.Logger) { start := time.Now() c.Next() rw := res.(martini.ResponseWriter) status := rw.Status() if status != 200 && status != 304 && req.URL.Path != "/ws" { logThis(start, res, req, logger) return } host, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { host = req.RemoteAddr } logOneLock.Lock() if _, ok := logged[host]; ok { logOneLock.Unlock() return } logged[host] = true logOneLock.Unlock() logger.Printf("%s\tRequested from %s; subsequent successful requests will not be logged\n", time.Now().Format("15:04:05"), host) }
func withApp(context martini.Context, params martini.Params, res http.ResponseWriter) { app := appreg.Get(params["name"]) if app == nil { http.Error(res, "No such application.", 404) } context.Map(app) }
func GET_home(c martini.Context, identity *data.Identity, render render.Render) { if identity == nil { c.Invoke(redirect_to("/login")) } else { c.Invoke(GET_profile) } }
func inner_GET_authorize(c martini.Context, sess sessions.Session, r *http.Request, ar *osin.AuthorizeRequest) bool { var ( identity = ActiveIdentity(c) source = current_url(r) handler martini.Handler ) if identity != nil { ar.UserData = identity sess.Delete("flow") return true } else { sess.Set("flow", FlowState{ Type: AuthorizeFlow, Source: source, StartAt: time.Now(), }) if provider := r.URL.Query().Get("p"); provider == "" { handler = show_provider_chooser() } else { handler = redirect_to_provider(provider) } } c.Invoke(handler) return false }
func create_identity(c martini.Context, tx *sqlx.Tx) { identity := &data.Identity{} err := data.CreateIdentity(tx, identity) if err != nil { panic(err) } c.Map(identity) }
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 SearcherMiddle(c martini.Context, w http.ResponseWriter, r *http.Request) { switch r.URL.Query().Get("type") { case "bing": c.MapTo(BingSearcher{}, (*Searcher)(nil)) w.Header().Set("Content-Type", "application/json") default: c.MapTo(BingSearcher{}, (*Searcher)(nil)) w.Header().Set("Content-Type", "application/json") } }
func ActiveIdentity(c martini.Context) *data.Identity { var ( identity *data.Identity ) c.Invoke(MayAuthenticate()) c.Invoke(func(i *data.Identity) { identity = i }) return identity }
func RequireLogin(rw http.ResponseWriter, req *http.Request, s sessions.Session, db *sql.DB, c martini.Context) { user := &User{} err := db.QueryRow("select name, email from users where id=$1", s.Get("userId")).Scan(&user.Name, &user.Email) if err != nil { http.Redirect(rw, req, "/login", http.StatusFound) return } c.Map(user) }
func ConnectDB(r *http.Request, c martini.Context) string { host := r.FormValue("host") port := r.FormValue("port") client := riakpbc.NewClient([]string{ host + ":" + port, }) c.Map(client) return "connected" }
func must_authenticate(c martini.Context, sess sessions.Session, db *sqlx.DB, r *http.Request) { identity := ActiveIdentity(c) if identity != nil { return } if r.Header.Get("x-interactive") == "true" { sess.Delete("identity_id") c.Invoke(redirect_to("/login")) } else { c.Invoke(forbidden()) } }
func GET_continue(c martini.Context, params martini.Params) { var ( provider = params["provider"] handler martini.Handler ) if provider == "" { handler = show_provider_chooser() } else { handler = redirect_to_provider(provider) } c.Invoke(handler) }
func may_authenticate(c martini.Context, sess sessions.Session, db *sqlx.DB, r *http.Request) { var ( interactive = true token string identity_id int64 identity *data.Identity err error ) // Attempt with Authorization header if v := r.Header.Get("Authorization"); v != "" { parts := strings.SplitN(v, " ", 2) if len(parts) == 2 && strings.ToLower(parts[0]) == "bearer" { interactive = false token = parts[1] } // Attempt with access_token parameter } else if v := r.URL.Query().Get("access_token"); v != "" { interactive = false token = v // Attempt with session.identity_id } else if id, ok := sess.Get("identity_id").(int64); ok { interactive = true identity_id = id } if token != "" { at, err := data.GetAccessTokenWithAccessToken(db, token) if err != nil { panic(err) } identity_id = at.IdentityId } if identity_id > 0 { identity, err = data.GetIdentity(db, identity_id) if err != nil { panic(err) } } if interactive { r.Header.Set("x-interactive", "true") } c.Map(identity) }
func GET_callback_AB(c martini.Context, sess sessions.Session) { flow := sess.Get("flow").(FlowState) c.Invoke(match_session_identity_with_account) c.Invoke(match_session_identity_with_flow) c.Invoke(update_account) c.Invoke(redirect_to(flow.Source)) }
func GET_callback_BC(c martini.Context, sess sessions.Session) { flow := sess.Get("flow").(FlowState) c.Invoke(create_identity) c.Invoke(create_account) c.Invoke(activate_session) c.Invoke(redirect_to(flow.Source)) }
func wsHandshake(context martini.Context, w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } ws, err := websocket.Upgrade(w, r, nil, 1024, 1024) if _, ok := err.(websocket.HandshakeError); ok { http.Error(w, "Not a websocket handshake", 400) return } else if err != nil { http.Error(w, fmt.Sprintf("error: %s", err), 500) log.Println(err) return } context.Map(ws) }
// Performs validation and combines errors from validation // with errors from deserialization, then maps both the // resulting struct and the errors to the context. func validateAndMap(obj reflect.Value, context martini.Context, errors *Errors, ifacePtr ...interface{}) { context.Invoke(Validate(obj.Interface())) errors.combine(getErrors(context)) context.Map(*errors) context.Map(obj.Elem().Interface()) if len(ifacePtr) > 0 { context.MapTo(obj.Elem().Interface(), ifacePtr[0]) } }
func (f *UpdateProfileForm) Validate(errors *binding.Errors, req *http.Request, context martini.Context) { if req.Method == "GET" || errors.Count() == 0 { return } data := context.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData) data["HasError"] = true if len(errors.Overall) > 0 { for _, err := range errors.Overall { log.Error("UpdateProfileForm.Validate: %v", err) } return } validate(errors, data, f) }
func GET_login(c martini.Context, sess sessions.Session, r *http.Request) { var ( identity = ActiveIdentity(c) source = r.Referer() handler martini.Handler ) if identity != nil { sess.Delete("flow") handler = redirect_to(source) } else { sess.Set("flow", FlowState{ Type: LoginFlow, Source: source, StartAt: time.Now(), }) handler = show_provider_chooser() } c.Invoke(handler) }
// MapEncoder intercepts the request's URL, detects the requested format, // and injects the correct encoder dependency for this request. It rewrites // the URL to remove the format extension, so that routes can be defined // without it. func mapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) { // Get the format extension matches := rxExt.FindStringSubmatch(r.URL.Path) ft := ".json" if len(matches) > 1 { // Rewrite the URL without the format extension l := len(r.URL.Path) - len(matches[1]) if strings.HasSuffix(r.URL.Path, "/") { l-- } r.URL.Path = r.URL.Path[:l] ft = matches[1] } // Inject the requested encoder switch ft { // Add cases for other formats default: c.MapTo(jsonEncoder{}, (*encoder)(nil)) w.Header().Set("Content-Type", "application/json") } }
// MapEncoder intercepts the request's URL, detects the requested format, // and injects the correct encoder dependency for this request. It rewrites // the URL to remove the format extension, so that routes can be defined // without it. func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) { // Get the format extension matches := rxExt.FindStringSubmatch(r.URL.Path) ft := ".json" if len(matches) > 1 { // Rewrite the URL without the format extension l := len(r.URL.Path) - len(matches[1]) if strings.HasSuffix(r.URL.Path, "/") { l-- } r.URL.Path = r.URL.Path[:l] ft = matches[1] } // Inject the requested encoder switch ft { case ".xml": c.Map(xmlEncoder) w.Header().Set("Content-Type", "application/xml") case ".text": c.Map(textEncoder) w.Header().Set("Content-Type", "text/plain; charset=utf-8") default: c.Map(jsonEncoder) w.Header().Set("Content-Type", "application/json") } }
func GET_link(c martini.Context, sess sessions.Session, r *http.Request) { var ( identity = ActiveIdentity(c) source = r.Referer() handler martini.Handler ) if identity == nil { sess.Delete("flow") handler = forbidden() } else { sess.Set("flow", FlowState{ Type: LinkFlow, Source: source, IdentityId: identity.Id, StartAt: time.Now(), }) handler = show_provider_chooser() } c.Invoke(handler) }
func (f *AddSSHKeyForm) Validate(errors *binding.Errors, req *http.Request, context martini.Context) { data := context.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData) AssignForm(f, data) if req.Method == "GET" || errors.Count() == 0 { if req.Method == "POST" && (len(f.KeyContent) < 100 || !strings.HasPrefix(f.KeyContent, "ssh-rsa")) { data["HasError"] = true data["ErrorMsg"] = "SSH key content is not valid" } return } data["HasError"] = true if len(errors.Overall) > 0 { for _, err := range errors.Overall { log.Error("AddSSHKeyForm.Validate: %v", err) } return } validate(errors, data, f) }
func GET_callback_B(c martini.Context, sess sessions.Session) { flow := sess.Get("flow").(FlowState) switch flow.Type { case LoginFlow: c.Invoke(GET_callback_BA) case LinkFlow: c.Invoke(GET_callback_BB) case AuthorizeFlow: c.Invoke(GET_callback_BC) default: panic("unknown flow type") } }
func getErrors(context martini.Context) Errors { return context.Get(reflect.TypeOf(Errors{})).Interface().(Errors) }
// Performs validation and combines errors from validation // with errors from deserialization, then maps both the // resulting struct and the errors to the context. func validateAndMap(obj reflect.Value, context martini.Context, errors *Errors) { context.Invoke(Validate(obj.Interface())) errors.combine(getErrors(context)) context.Map(*errors) context.Map(obj.Elem().Interface()) }
func appEngine(c martini.Context, r *http.Request) { c.Map(appengine.NewContext(r)) }
func AdminAuthentication(c martini.Context) { // TODO Need to fix this up c.Next() }
// Martini Middleware to require authentication of anyone logging into // the app // func Authentication(c martini.Context) { // TODO Need to authenticate c.Next() }
func PopulateAppContext(martiniContext martini.Context, w http.ResponseWriter, request *http.Request, renderer render.Render) { dbContext := models.NewDbContext() appContext := &models.AppContext{Request: request, Renderer: renderer, MartiniContext: martiniContext, DbContext: dbContext} martiniContext.Map(appContext) }