Пример #1
0
func RegisterHandler(w http.ResponseWriter, r *http.Request) {

	r.ParseForm()
	fmt.Println(r.Form())
	fmt.Println(r.FormValue("data"))

	data := r.Header.Get("data")
	bytes := []byte(data)
	var user types.User
	json.Unmarshal(bytes, &user)
	// userData := f.(map[string]interface{})
	// fmt.Println("data: ", userData)

	err := parsing.AddUser(user.FacebookID, user.PublicKey)

	var errorResponse types.ErrorResponse
	if err != nil {
		fmt.Printf("Error adding user: %v\n", err)
		errorResponse = types.ErrorResponse{true, err.Error()}
	} else {
		fmt.Printf("Added user: %v\n", user.FacebookID)
		errorResponse = types.ErrorResponse{false, ""}
	}

	//write json to return here
	b, err := json.Marshal(errorResponse)
	fmt.Fprintf(w, "%s", b)
}
Пример #2
0
func indexHandler(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	if len(req.Form["name"]) > 0 {
		fmt.Fprint(rw, "hello,", req.Form("name")[0])
	} else {
		fmt.Fprint(rw, "hello,world")
	}
}
Пример #3
0
/**
 *	测试session manager的Free()
 *	测试时间20秒,需要耐心等待
 */
func TestSessionManagerFree(t *testing.T) {
	runtime.GOMAXPROCS(runtime.NumCPU())
	sm := NewSessionManagerAtGCTime(1, true)

	sm.testing = true

	fmt.Println("sm free() testing...:", time.Now(), "\n")

	go func() {

		//	添加http session
		for i := 1; i <= 10; i++ {
			rw := TestImplResponse{}
			req := http.Request{}
			req.RemoteAddr = "128.0.0.1:8212"
			req.Header = make(http.Header, 1)
			req.Form = make(url.Values)
			sm.tempSessMaxlifeTime = int32(i)
			_, err := sm.GetSession(rw, &req, int32(i), false)
			if nil != err {
				fmt.Println("get session error:", err)
			}
		}

		<-time.After(time.Duration(6) * time.Second)
		fmt.Println("session manager start free()...:", time.Now())
		sm.Free()
	}()

	time.Sleep(time.Duration(20) * time.Second)
}
Пример #4
0
func slashws(w http.ResponseWriter, req *http.Request) {
	// Upgrader.Upgrade() has Origin check if .CheckOrigin is nil
	upgrader := gorillawebsocket.Upgrader{}
	wsconn, err := upgrader.Upgrade(w, req, nil)
	if err != nil { // Upgrade() does http.Error() to the client
		return
	}

	// req.Method == "GET" asserted by the mux
	req.Form = nil // reset reused later .Form
	c := &conn{
		Conn:          wsconn,
		requestOrigin: req,
		receive:       make(chan *received, 2),
		push:          make(chan *pageUpdate, 2),
		full:          defaultClient(),
	}
	register <- c
	defer func() {
		unregister <- c
		c.Conn.Close()
	}()
	stop := make(chan struct{}, 1)
	go c.receiveLoop(stop) // read from the client
	c.updateLoop(stop)     // write to the client
}
Пример #5
0
func (req *stockHttp) Request(ret interface{}) error {
	var hdl *http.Request
	var resp *http.Response
	var err error

	if hdl, err = http.NewRequest("GET", req.url+"?"+req.params.Encode(), nil); err != nil {
		return err
	}

	hdl.Form = req.params
	if err = hdl.ParseForm(); err != nil {
		return err
	}

	for k, v := range req.headers {
		hdl.Header.Add(k, v)
	}

	if resp, err = http.DefaultClient.Do(hdl); err != nil {
		return err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	if err = json.Unmarshal(body, ret); err != nil {
		return err
	}

	return nil
}
Пример #6
0
func (handler *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
	log := handler.logger.Session("index")

	client := handler.clientFactory.Build(r)

	pipelines, err := client.ListPipelines()
	if err != nil {
		log.Error("failed-to-list-pipelines", err)
		return err
	}

	if len(pipelines) == 0 {
		err := handler.noBuildsTemplate.Execute(w, TemplateData{})
		if err != nil {
			log.Fatal("failed-to-build-template", err, lager.Data{})
			return err
		}

		return nil
	}

	if r.Form == nil {
		r.Form = url.Values{}
	}

	r.Form[":pipeline"] = []string{pipelines[0].Name}

	return handler.pipelineHandler.ServeHTTP(w, r)
}
Пример #7
0
func run_test_request(t *testing.T, server *plate.Server, method, url_str string, payload url.Values) (*httptest.ResponseRecorder, http.Request) {

	url_obj, err := url.Parse(url_str)
	if err != nil {
		t.Fatal(err)
	}

	r := http.Request{
		Method: method,
		URL:    url_obj,
	}

	if payload != nil {
		r.URL.RawQuery = payload.Encode()
	}

	if strings.ToUpper(method) == "POST" {
		r.Form = payload
	}

	recorder := httptest.NewRecorder()

	server.ServeHTTP(recorder, &r)

	return recorder, r
}
Пример #8
0
func (me *Request) encodeBody(method string) (*http.Request, error) {
	var req *http.Request
	var err error

	//given body is a param collection
	if params, ok := me.body.(map[string]interface{}); ok {
		paramValues := url.Values{}
		for key, val := range params {
			strVal := ToString(val, "")
			if len(strVal) > 0 {
				paramValues.Add(key, strVal)
			}
		}
		req, err = http.NewRequest(method, me.url, nil)
		req.Form = paramValues
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	} else { //given a raw body object
		bodyBytes, err := json.Marshal(me.body)
		if err != nil {
			return nil, errors.New("Invalid JSON in the query")
		}
		reader := bytes.NewReader(bodyBytes)
		req, err = http.NewRequest(method, me.url, reader)
		req.Header.Set("Content-Length", strconv.Itoa(len(string(bodyBytes))))
		req.Header.Set("Content-Type", "application/json; charset=utf-8")
	}

	return req, err
}
Пример #9
0
Файл: ws.go Проект: vadv/ostent
func IndexWS(access *Access, errlog *log.Logger, minperiod flags.Period, w http.ResponseWriter, req *http.Request) {
	// Upgrader.Upgrade() has Origin check if .CheckOrigin is nil
	upgrader := gorillawebsocket.Upgrader{
		HandshakeTimeout: 5 * time.Second,
	}
	wsconn, err := upgrader.Upgrade(w, req, nil)
	if err != nil { // Upgrade() does http.Error() to the client
		return
	}

	// req.Method == "GET" asserted by the mux
	req.Form = nil // reset reused later .Form
	c := &conn{
		Conn: wsconn,

		requestOrigin: req,

		receive: make(chan *received, 2),
		pushch:  make(chan *IndexUpdate, 2),
		para:    params.NewParams(minperiod),
		access:  access,
	}
	Register <- c
	defer func() {
		unregister <- c
		c.Conn.Close()
	}()
	stop := make(chan struct{}, 1)
	go c.receiveLoop(stop)     // read from the client
	c.updateLoop(errlog, stop) // write to the client
}
Пример #10
0
func (mr *ManuelRequest) encodeForm(req *http.Request) {
	if mr.Body != nil {
		req.Form = url.Values{}

		for k, v := range mr.Body {
			req.Form.Add(k, v)
		}
	}
}
Пример #11
0
func benchRequest(b *testing.B, router http.Handler, r *http.Request) {
	w := mockResponseWriter{}
	u := r.URL
	r.RequestURI = u.RequestURI()

	b.ReportAllocs()
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		router.ServeHTTP(&w, r)

		// clear caches
		r.Form = nil
		r.PostForm = nil
		r.MultipartForm = nil
	}
}
Пример #12
0
func TestFilter_Request(t *testing.T) {
	print("Filter_Request\n")
	c := gsc(t)
	gl, err := c.Games()
	assert.Nil(t, err, "c.Games()")
	r := http.Request{}
	uv := url.Values{}
	uv.Add("dummy", "dummy")
	r.Form = uv
	assert.Equal(t, len(Filter(gl).Request(&r)), 801, "FilterRequest()")
	uv.Add("has", "true")
	assert.Equal(t, len(Filter(gl).Request(&r)), 1, "FilterRequest(has=true)")
	uv.Del("has")
	uv.Add("manual", "true")
	assert.Equal(t, len(Filter(gl).Request(&r)), 1, "FilterRequest(manual=true)")
	uv.Del("manual")
	uv.Add("box", "true")
	assert.Equal(t, len(Filter(gl).Request(&r)), 1, "FilterRequest(box=true)")
}
Пример #13
0
// findHandler ...
func (router *Router) findHandler(req *http.Request) http.HandlerFunc {
	if methodes, ok := router.routes[req.Method]; ok {
		if handler, ok := methodes[req.URL.Path]; ok {
			return handler
		}
	}
	if methods, ok := router.regexps[req.Method]; ok {
		for exp, handler := range methods {
			if exp.MatchString(req.URL.Path) {
				matched := exp.FindAllStringSubmatch(req.URL.Path, -1)
				if req.Form == nil {
					req.Form = url.Values{}
				}
				for i, name := range exp.SubexpNames() {
					req.Form.Add(name, matched[0][i])
				}
				return handler
			}
		}
	}
	return nil
}
Пример #14
0
func (s *ChatServer) ServeHTTP(rep http.ResponseWriter, req *http.Request) {
	//短连接要调用一下这个,否则go不会主动断开连接
	//req.ParseForm();
	req.Form = make(url.Values)

	body, e := ioutil.ReadAll(req.Body)
	if e != nil {
		fmt.Printf("read request error\n")
	} else {
		sessionid := req.Header.Get("SESSIONID")
		event := req.Header.Get("EVENT")
		fmt.Printf("sid=%s, event=%s\n", sessionid, event)
		switch event {
		case "1": //新连接
			//TODO
		case "2": //连接关闭
			s.logout(sessionid)
		default: //消息处理
			if len(body) > 0 {
				js, err := simplejson.NewJson(body)
				if err != nil {
					fmt.Printf("parse JSON error, data=")
					fmt.Println(body)
				} else {
					r := s.handle(sessionid, js)
					if len(r) > 0 {
						rep.Header().Add("Content-Length", strconv.Itoa(len(r)))
						rep.Write(r)
					} else {
						fmt.Println("no message response")
					}
				}
			}
		}
	}

	//rep.Write([]byte("<h1>Hello World</h1>"))
}
Пример #15
0
func appendTokenToForm(r *http.Request, t *jwt.Token, prefix string) error {

	if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" {
		if err := r.ParseForm(); err != nil {
			return err
		}
	}

	if r.Form == nil {
		r.Form = make(url.Values)
	}

	for k, v := range t.Claims {
		vs, err := cast.ToStringE(v)
		if err == nil {
			r.Form.Add(prefix+k, vs)
		} else {
			return errgo.Newf("appendTokenToForm: failed to assert to type string: key %s => value %v : %s", k, v, err.Error())
		}
	}

	return nil
}
Пример #16
0
// Handler returns the handler to use for the given request, consulting r.Method
// and r.URL.Path. It always returns a non-nil handler. If there is no registered handler
// that applies to the request, Handler returns a “page not found” handler and empty pattern.
// If there is a registered handler but requested method is not allowed,
// "method not allowed" and a pattern are returned.
func (t *Router) Handler(r *http.Request) (handler http.Handler, pattern string) {
	// Make sure we have a handler for this request.
	obj, params, found := t.data.Lookup(r.URL.Path)
	if !found {
		return http.HandlerFunc(NotFound), ""
	}

	// Check whether requested method is allowed.
	route := obj.(*Route)
	handler, i := route.Handlers.Get(r.Method)
	if i == -1 {
		return http.HandlerFunc(MethodNotAllowed), route.Pattern
	}

	// Add parameters of request to request.Form and return a handler.
	if len(params) > 0 {
		r.Form = make(url.Values, len(params))
		for i := range params {
			r.Form[params[i].Name] = []string{params[i].Value}
		}
	}
	return handler, route.Pattern
}
Пример #17
0
func (server *SecureServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	params := mux.Vars(req)

	data := params["data"]
	signature := params["signature"]
	check := ComputeHmac256(data, server.secret)

	if check != signature {
		http.Error(rw, "Invalid cryptographic signature", http.StatusBadRequest)
		return
	}

	decoded, err := decodeData(data)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusBadRequest)
		return
	}

	query := url.Values{}
	query.Set("g", decoded.G)

	if decoded.Gr || decoded.Grey {
		query.Set("greyscale", "1")
	}

	if decoded.F != "" && decoded.Shop_id != 0 {
		//"/#{opts['shop_id']}/original/#{opts['f']}"
		path := fmt.Sprintf("/%d/original/%s", decoded.Shop_id, decoded.F)
		query.Set("src", path)
	} else {
		query.Set("src", decoded.Src)
	}

	req.Form = query
	server.app.ServeHTTP(rw, req)
}
Пример #18
0
func requestDataToUrlValues(r *http.Request, data map[string]interface{}) (err error) {
	var (
		form        = make(url.Values)
		postform    = make(url.Values)
		queryValues url.Values
	)

	makeRequestData("", data, postform)

	for k, v := range postform {
		form[k] = append(form[k], v...)
	}

	if queryValues, err = url.ParseQuery(r.URL.RawQuery); err == nil {
		for k, v := range queryValues {
			form[k] = append(form[k], v...)
		}
	}

	r.PostForm = postform
	r.Form = form

	return
}
Пример #19
0
		Context("with an authorization header", func() {
			BeforeEach(func() {
				request.Header.Set("Authorization", authorization)
			})

			It("fails with no guid", func() {
				Expect(response.Code).To(Equal(http.StatusBadRequest))
			})
		})
	})

	Describe("retrieve container metrics", func() {
		BeforeEach(func() {
			request.Header.Set("Authorization", authorization)
			request.Form = url.Values{}
			request.Form.Add(":guid", guid)

			noaaClient.ContainerMetricsReturns([]*events.ContainerMetric{
				{
					ApplicationId: proto.String("appId"),
					InstanceIndex: proto.Int32(5),
					CpuPercentage: proto.Float64(4),
					MemoryBytes:   proto.Uint64(1024),
					DiskBytes:     proto.Uint64(2048),
				},
			}, nil)

			bbsClient.DesiredLRPByProcessGuidReturns(&models.DesiredLRP{
				LogGuid:     logGuid,
				ProcessGuid: guid,
Пример #20
0
		request          *http.Request
		responseRecorder *httptest.ResponseRecorder
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")
		fakeBBS = new(fake_bbs.FakeClient)

		responseRecorder = httptest.NewRecorder()

		var err error
		request, err = http.NewRequest("DELETE", "", nil)
		Expect(err).NotTo(HaveOccurred())
		request.Form = url.Values{
			":process_guid": []string{"process-guid"},
		}
	})

	JustBeforeEach(func() {
		stopAppHandler := handlers.NewStopAppHandler(logger, fakeBBS)
		stopAppHandler.StopApp(responseRecorder, request)
	})

	It("invokes the bbs to delete the app", func() {
		Expect(fakeBBS.RemoveDesiredLRPCallCount()).To(Equal(1))
		Expect(fakeBBS.RemoveDesiredLRPArgsForCall(0)).To(Equal("process-guid"))
	})

	It("responds with 202 Accepted", func() {
		Expect(responseRecorder.Code).To(Equal(http.StatusAccepted))
Пример #21
0
				Expect(receptorError).To(Equal(receptor.Error{
					Type:    receptor.UnknownError,
					Message: "Something went wrong",
				}))

			})
		})
	})

	Describe("GetAllByProcessGuid", func() {
		var req *http.Request

		BeforeEach(func() {
			req = newTestRequest("")
			req.Form = url.Values{":process_guid": []string{"process-guid-0"}}
		})

		JustBeforeEach(func() {
			handler.GetAllByProcessGuid(responseRecorder, req)
		})

		Context("when reading LRPs from BBS succeeds", func() {
			BeforeEach(func() {
				fakeLegacyBBS.ActualLRPGroupsByProcessGuidReturns(oldmodels.ActualLRPGroupsByIndex{
					1: {Instance: &oldActualLRP1, Evacuating: nil},
				}, nil)
			})

			It("calls the BBS to retrieve the actual LRPs", func() {
				Expect(fakeLegacyBBS.ActualLRPGroupsByProcessGuidCallCount()).To(Equal(1))
Пример #22
0
		request          *http.Request
		responseRecorder *httptest.ResponseRecorder
	)

	BeforeEach(func() {
		var err error

		logger = lagertest.NewTestLogger("test")
		fakeBBSClient = new(fake_bbs.FakeClient)

		responseRecorder = httptest.NewRecorder()

		request, err = http.NewRequest("DELETE", "", nil)
		Expect(err).NotTo(HaveOccurred())
		request.Form = url.Values{
			":task_guid": []string{"some-guid"},
		}
	})

	JustBeforeEach(func() {
		handler := handlers.NewCancelTaskHandler(logger, fakeBBSClient)
		handler.CancelTask(responseRecorder, request)
	})

	It("logs the incoming and outgoing request", func() {
		Eventually(logger.TestSink.Buffer).Should(gbytes.Say("serving"))
		Eventually(logger.TestSink.Buffer).Should(gbytes.Say("canceling-task"))
	})

	Context("when the task does not exist", func() {
		BeforeEach(func() {
				err := json.Unmarshal(garbageRequest, &receptor.DesiredLRPCreateRequest{})
				expectedBody, _ := json.Marshal(receptor.Error{
					Type:    receptor.InvalidJSON,
					Message: err.Error(),
				})
				Expect(responseRecorder.Body.String()).To(Equal(string(expectedBody)))
			})
		})
	})

	Describe("Get", func() {
		var req *http.Request

		BeforeEach(func() {
			req = newTestRequest("")
			req.Form = url.Values{":process_guid": []string{"process-guid-0"}}
		})

		JustBeforeEach(func() {
			handler.Get(responseRecorder, req)
		})

		Context("when reading tasks from BBS succeeds", func() {
			BeforeEach(func() {
				fakeBBS.DesiredLRPByProcessGuidReturns(&models.DesiredLRP{
					ProcessGuid: "process-guid-0",
					Domain:      "domain-1",
					Action: models.WrapAction(&models.RunAction{
						User: "******",
						Path: "the-path",
					}),
Пример #24
0
Файл: net.go Проект: shaban/gwf
func multiplexer(w http.ResponseWriter, req *http.Request) {
	// inline function for redirecting the root of a route to an alias
	// e.g /posts/ ==> /posts/index
	// so that the 301 takes care of duplicate content issues
	// google will index it in a fashion where the content of
	// /posts/index will be attributed to /posts/
	checkAlias := func(p, a string, w http.ResponseWriter) bool {
		if a == "" {
			return false
		}
		alias := strings.Split(a, "=")
		if p == alias[0] {
			http.Redirect(w, req, alias[1], http.StatusMovedPermanently)
			return true
		}
		return false
	}
	// some crappy way to intercept that call.
	if req.URL.Path == "/favicon.ico" {
		http.NotFound(w, req)
		return
	}
	// the basic multiplex loop
	for _, rt := range rtr.controllers {
		// if methods GET,PUT etc. different this route can't be correct
		if req.Method != rt.method {
			continue
		}
		// split path components
		dir, f := path.Split(req.URL.Path)
		// extract file extensions
		ext := path.Ext(req.URL.Path)
		// extract parameters from full route
		// e.g in /posts/general/post-name get general/post-name into rel
		rel, err := filepath.Rel(rt.urlPath, req.URL.Path)
		if err != nil {
			log.Println(err.Error())
		}
		// if the path can be described as just navigating up
		// the hierarchy it's not parameters of a dynamic route
		if strings.HasPrefix(rel, ".") {
			rel = ""
		}
		// now comes decision tree
		switch {
		// if there is no file component and no file extension
		// it must be some sort of dynamic route
		// because of this if type of route is file or static move on
		case f != "" && ext == "":
			switch rt.kind {
			case file, static:
				continue
			case dynamic:
				if rel == "" {
					continue
				}
				// is dynamic
				// if number of parameters is different
				// it must be different dynamic route
				// to differentiate beween e.g. /{page} and /{page/subpage}}
				if len(rt.vars)-1 != strings.Count(rel, "/") {
					continue
				}
				// it's same rooted path and same parameter count
				// so go to handling of dynamic route
				goto isdynamic
			}
			// if file component is empty it's either
			// a static route or an alias for a dynamic route
		case f == "":
			switch rt.kind {
			case file:
				continue
			case dynamic:
				//= of it's an alias do the appropriate
				// redirect in above inline function
				if checkAlias(dir, rt.as, w) {
					return
				}
				continue
			case static:
				// of it's a direct hit on a static route go for it
				if req.URL.Path != rt.urlPath {
					continue
				}
				// is static
				goto isstatic
			}
		case ext != "":
			// if route is of type file and starts with the rooted path go for it
			if rt.kind != file {
				continue
			}
			// is file
			if strings.HasPrefix(req.URL.Path, rt.urlPath) {
				goto isfile
			}
			continue
		}
		// must be bogus return with 404
		http.NotFound(w, req)
		return
		// the cool thing it's all fallthrough so
		// dynamic goes through all three code parts
	isdynamic:
		// append the parameters to the raw query and
		// make sure to not mess up existing GET params
		if req.URL.RawQuery != "" {
			req.URL.RawQuery += "&;"
		}
		// get the param keys from route definitions
		// and assign appropriate values from route
		for vark, varv := range strings.Split(rel, "/") {
			req.URL.RawQuery += fmt.Sprintf("%s=%s&;", rt.vars[vark], varv)
		}
		req.URL.RawQuery = req.URL.RawQuery[0 : len(req.URL.RawQuery)-2]
		req.Form = nil
	isstatic:
		// get the standard session for to4go micro framework
		rt.session, err = store.Get(req, "to4go")
		if err != nil {
			log.Printf("store.get:%s", err.Error())
		}
		// parse forms
		req.ParseForm()
		req.ParseMultipartForm(2000000)
	isfile:
		// take care of caching specified in routes
		if rt.cache != 0 {
			w.Header().Set("Cache-Control",
				fmt.Sprintf("max-age=%v,public", rt.cache.Seconds()))
		}
		// call the registered handler of the controller
		rt.handleFunc(w, req)
		// when in dev mode parse Template Sets again
		if tool.Dev {
			parseTpl()
		}
		return
	}
}
Пример #25
0
// Tests the ability to create GitHub repositories.
func Test_GitHubCreate(t *testing.T) {
	// seed the database with values
	SetupFixtures()
	defer TeardownFixtures()

	// mock request
	req := http.Request{}
	req.Form = url.Values{}

	// get user that will add repositories
	user, _ := database.GetUser(1)
	settings := database.SettingsMust()

	Convey("Given request to setup github repo", t, func() {

		Convey("When repository is public", func() {
			req.Form.Set("owner", "example")
			req.Form.Set("name", "public")
			req.Form.Set("team", "")
			res := httptest.NewRecorder()
			err := handler.RepoCreateGithub(res, &req, user)
			repo, _ := database.GetRepoSlug(settings.GitHubDomain + "/example/public")

			Convey("The repository is created", func() {
				So(err, ShouldBeNil)
				So(repo, ShouldNotBeNil)
				So(repo.ID, ShouldNotEqual, 0)
				So(repo.Owner, ShouldEqual, "example")
				So(repo.Name, ShouldEqual, "public")
				So(repo.Host, ShouldEqual, settings.GitHubDomain)
				So(repo.TeamID, ShouldEqual, 0)
				So(repo.UserID, ShouldEqual, user.ID)
				So(repo.Private, ShouldEqual, false)
				So(repo.SCM, ShouldEqual, "git")
			})
			Convey("The repository is public", func() {
				So(repo.Private, ShouldEqual, false)
			})
		})

		Convey("When repository is private", func() {
			req.Form.Set("owner", "example")
			req.Form.Set("name", "private")
			req.Form.Set("team", "")
			res := httptest.NewRecorder()
			err := handler.RepoCreateGithub(res, &req, user)
			repo, _ := database.GetRepoSlug(settings.GitHubDomain + "/example/private")

			Convey("The repository is created", func() {
				So(err, ShouldBeNil)
				So(repo, ShouldNotBeNil)
				So(repo.ID, ShouldNotEqual, 0)
			})
			Convey("The repository is private", func() {
				So(repo.Private, ShouldEqual, true)
			})
		})

		Convey("When repository is not found", func() {
			req.Form.Set("owner", "example")
			req.Form.Set("name", "notfound")
			req.Form.Set("team", "")
			res := httptest.NewRecorder()
			err := handler.RepoCreateGithub(res, &req, user)

			Convey("The result is an error", func() {
				So(err, ShouldNotBeNil)
				So(err.Error(), ShouldEqual, "Unable to find GitHub repository example/notfound.")
			})

			Convey("The repository is not created", func() {
				_, err := database.GetRepoSlug("example/notfound")
				So(err, ShouldNotBeNil)
				So(err, ShouldEqual, sql.ErrNoRows)
			})
		})

		Convey("When repository hook is not writable", func() {
			req.Form.Set("owner", "example")
			req.Form.Set("name", "hookerr")
			req.Form.Set("team", "")
			res := httptest.NewRecorder()
			err := handler.RepoCreateGithub(res, &req, user)

			Convey("The result is an error", func() {
				So(err, ShouldNotBeNil)
				So(err.Error(), ShouldEqual, "Unable to add Hook to your GitHub repository.")
			})

			Convey("The repository is not created", func() {
				_, err := database.GetRepoSlug("example/hookerr")
				So(err, ShouldNotBeNil)
				So(err, ShouldEqual, sql.ErrNoRows)
			})
		})

		Convey("When repository ssh key is not writable", func() {
			req.Form.Set("owner", "example")
			req.Form.Set("name", "keyerr")
			req.Form.Set("team", "")
			res := httptest.NewRecorder()
			err := handler.RepoCreateGithub(res, &req, user)

			Convey("The result is an error", func() {
				So(err, ShouldNotBeNil)
				So(err.Error(), ShouldEqual, "Unable to add Public Key to your GitHub repository.")
			})

			Convey("The repository is not created", func() {
				_, err := database.GetRepoSlug("example/keyerr")
				So(err, ShouldNotBeNil)
				So(err, ShouldEqual, sql.ErrNoRows)
			})
		})

		Convey("When a team is provided", func() {
			req.Form.Set("owner", "example")
			req.Form.Set("name", "team")
			req.Form.Set("team", "drone")
			res := httptest.NewRecorder()

			// invoke handler
			err := handler.RepoCreateGithub(res, &req, user)
			team, _ := database.GetTeamSlug("drone")
			repo, _ := database.GetRepoSlug(settings.GitHubDomain + "/example/team")

			Convey("The repository is created", func() {
				So(err, ShouldBeNil)
				So(repo, ShouldNotBeNil)
				So(repo.ID, ShouldNotEqual, 0)
			})

			Convey("The team should be set", func() {
				So(repo.TeamID, ShouldEqual, team.ID)
			})
		})

		Convey("When a team is not found", func() {
			req.Form.Set("owner", "example")
			req.Form.Set("name", "public")
			req.Form.Set("team", "faketeam")
			res := httptest.NewRecorder()
			err := handler.RepoCreateGithub(res, &req, user)

			Convey("The result is an error", func() {
				So(err, ShouldNotBeNil)
				So(err.Error(), ShouldEqual, "Unable to find Team faketeam.")
			})
		})

		Convey("When a team is forbidden", func() {
			req.Form.Set("owner", "example")
			req.Form.Set("name", "public")
			req.Form.Set("team", "golang")
			res := httptest.NewRecorder()
			err := handler.RepoCreateGithub(res, &req, user)

			Convey("The result is an error", func() {
				So(err, ShouldNotBeNil)
				So(err.Error(), ShouldEqual, "Invalid permission to access Team golang.")
			})
		})
	})
}
Пример #26
0
func (h *Handler) AuthorizeHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	resp := h.server.NewResponse()
	defer resp.Close()

	code := r.Form.Get("code")
	state := r.Form.Get("state")
	if code != "" {
		stateData, err := h.States.GetStateData(state)
		if err != nil {
			// Something else went wrong
			http.Error(w, fmt.Sprintf("Could not fetch state: %s", err), http.StatusBadRequest)
			return
		}
		if stateData.IsExpired() {
			http.Error(w, fmt.Sprintf("This session expired %v.", err), http.StatusBadRequest)
		}
		r.Form = stateData.ToURLValues()
	}

	if ar := h.server.HandleAuthorizeRequest(resp, r); ar != nil {
		// For now, a provider must be given.
		// TODO there should be a fallback provider which is a redirect to the login endpoint. This should be configurable by env var.
		// Let's see if this is a valid provider. If not, return an error.
		providerName := r.Form.Get("provider")
		if r.Form.Get("provider") == "" && h.SignInLocation != "" {
			providerName = "login"
		}

		provider, err := h.Providers.Find(providerName)
		if err != nil {
			http.Error(w, fmt.Sprintf(`Unknown provider "%s".`, providerName), http.StatusBadRequest)
			return
		}

		if code == "" {
			stateData := new(storage.StateData)
			if err := stateData.FromAuthorizeRequest(ar, provider.GetID()); err != nil {
				// Something else went wrong
				http.Error(w, fmt.Sprintf("Could not hydrate state data: %s", err), http.StatusInternalServerError)
				return
			}
			stateData.ExpireInOneHour()
			if err := h.States.SaveStateData(stateData); err != nil {
				// Something else went wrong
				http.Error(w, fmt.Sprintf("Could not persist state data: %s", err), http.StatusInternalServerError)
				return
			}

			// If no code was given we have to initiate the provider's authorization workflow
			url := provider.GetAuthenticationURL(stateData.ID)
			http.Redirect(w, r, url, http.StatusFound)
			return
		}

		// Create a session by exchanging the code for the auth code
		session, err := provider.FetchSession(code)
		if err != nil {
			http.Error(w, fmt.Sprintf("Could not exchange access code: %s", err), http.StatusUnauthorized)
			return
		}

		var conn connection.Connection
		var acc account.Account
		if session.GetForcedLocalSubject() != "" {
			acc, err = h.Accounts.Get(session.GetForcedLocalSubject())
		} else {
			conn, err = h.Connections.FindByRemoteSubject(provider.GetID(), session.GetRemoteSubject())
		}

		if err == pkg.ErrNotFound {
			// The subject is not linked to any account.

			if h.SignUpLocation == "" {
				http.Error(w, "No sign up location is set. Please contact your admin.", http.StatusInternalServerError)
				return
			}

			redirect, err := url.Parse(h.SignUpLocation)
			if err != nil {
				http.Error(w, fmt.Sprintf("Could not parse redirect URL: %s", err), http.StatusInternalServerError)
				return
			}

			claims := map[string]interface{}{
				"iss":                h.Issuer,
				"aud":                redirect.String(),
				"exp":                time.Now().Add(time.Hour),
				"iat":                time.Now(),
				"state":              ar.State,
				"connector_id":       provider.GetID(),
				"connector_response": session.GetExtra(),
				"connector_subject":  session.GetRemoteSubject(),
				"redirect_uri":       pkg.JoinURL(h.HostURL, "oauth2/authorize"),
			}
			authToken, err := h.JWT.SignToken(claims, map[string]interface{}{})
			if err != nil {
				http.Error(w, fmt.Sprintf("Could not generate token: %s", err), http.StatusInternalServerError)
				return
			}

			query := redirect.Query()
			query.Add("auth_token", authToken)
			redirect.RawQuery = query.Encode()

			log.WithFields(log.Fields{
				"provider": provider.GetID(),
				"subject":  session.GetRemoteSubject(),
				"redirect": h.SignUpLocation,
			}).Warnf(`Remote subject is not linked to any local subject. Redirecting to sign up page.`)
			http.Redirect(w, r, redirect.String(), http.StatusFound)
			return
		} else if err != nil {
			// Something else went wrong
			http.Error(w, fmt.Sprintf("Could not assert subject claim: %s", err), http.StatusInternalServerError)
			return
		}

		var localSubject string
		if conn != nil {
			localSubject = conn.GetLocalSubject()
		} else if acc != nil {
			localSubject = acc.GetID()
		}

		ar.UserData = jwt.NewClaimsCarrier(uuid.New(), h.Issuer, localSubject, ar.Client.GetId(), time.Now().Add(time.Duration(ar.Expiration)*time.Second), time.Now(), time.Now())
		ar.Authorized = true
		h.server.FinishAuthorizeRequest(resp, r, ar)
	}

	if resp.IsError {
		resp.StatusCode = http.StatusUnauthorized
	}

	osin.OutputJSON(resp, w, r)
}
		request          *http.Request
		responseRecorder *httptest.ResponseRecorder
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")
		fakeBBS = new(fake_bbs.FakeClient)

		responseRecorder = httptest.NewRecorder()

		var err error
		request, err = http.NewRequest("POST", "", nil)
		Expect(err).NotTo(HaveOccurred())
		request.Form = url.Values{
			":process_guid": []string{"process-guid-0"},
			":index":        []string{"1"},
		}

		fakeBBS.ActualLRPGroupByProcessGuidAndIndexStub = func(processGuid string, index int) (*models.ActualLRPGroup, error) {
			return &models.ActualLRPGroup{
				Instance: model_helpers.NewValidActualLRP(processGuid, int32(index)),
			}, nil
		}
	})

	JustBeforeEach(func() {
		killHandler := handlers.NewKillIndexHandler(logger, fakeBBS)
		killHandler.KillIndex(responseRecorder, request)
	})

	It("invokes the bbs to retire", func() {
Пример #28
0
func TestUserProfilePage(t *testing.T) {
	// seed the database with values
	Setup()
	defer Teardown()

	// dummy request
	req := http.Request{}
	req.Form = url.Values{}

	Convey("User Profile", t, func() {
		SkipConvey("View Profile Information", func() {
			user, _ := database.GetUser(1)
			res := httptest.NewRecorder()
			handler.UserUpdate(res, &req, user)

			Convey("Email Address is correct", func() {

			})
			Convey("User Name is correct", func() {

			})
		})
		Convey("Update Email Address", func() {
			Convey("With a Valid Email Address", func() {
				user, _ := database.GetUser(1)
				req.Form.Set("name", "John Smith")
				req.Form.Set("email", "*****@*****.**")
				res := httptest.NewRecorder()
				handler.UserUpdate(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusOK)
			})
			Convey("With an Invalid Email Address", func() {
				user, _ := database.GetUser(1)
				req.Form.Set("name", "John Smith")
				req.Form.Set("email", "John.Smith")
				res := httptest.NewRecorder()
				handler.UserUpdate(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusBadRequest)
				So(res.Body.String(), ShouldContainSubstring, ErrInvalidEmail.Error())
			})
			Convey("With an Empty Email Address", func() {
				user, _ := database.GetUser(1)
				req.Form.Set("name", "John Smith")
				req.Form.Set("email", "")
				res := httptest.NewRecorder()
				handler.UserUpdate(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusBadRequest)
				So(res.Body.String(), ShouldContainSubstring, ErrInvalidEmail.Error())
			})
			Convey("With a Duplicate Email Address", func() {
				user, _ := database.GetUser(1)
				req.Form.Set("name", "John Smith")
				req.Form.Set("email", "*****@*****.**")
				res := httptest.NewRecorder()
				handler.UserUpdate(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusBadRequest)
			})
		})

		Convey("Update User Name", func() {
			Convey("With a Valid Name", func() {
				user, _ := database.GetUser(1)
				req.Form.Set("name", "John Smith")
				req.Form.Set("email", "*****@*****.**")
				res := httptest.NewRecorder()
				handler.UserUpdate(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusOK)
			})
			Convey("With an Empty Name", func() {
				user, _ := database.GetUser(1)
				req.Form.Set("name", "")
				req.Form.Set("email", "*****@*****.**")
				res := httptest.NewRecorder()
				handler.UserUpdate(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusBadRequest)
				So(res.Body.String(), ShouldContainSubstring, ErrInvalidUserName.Error())
			})
		})

		Convey("Change Password", func() {
			Convey("To a Valid Password", func() {
				user, _ := database.GetUser(1)
				req.Form.Set("password", "password123")
				res := httptest.NewRecorder()
				handler.UserPassUpdate(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusOK)
				So(user.ComparePassword("password123"), ShouldBeNil)
			})
			Convey("To an Invalid Password, too short", func() {
				user, _ := database.GetUser(1)
				req.Form.Set("password", "123")
				res := httptest.NewRecorder()
				handler.UserPassUpdate(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusBadRequest)
			})
		})
		Convey("Delete the Account", func() {
			Convey("Providing an Invalid Password", func() {
				user, _ := database.GetUser(1)
				req.Form.Set("password", "password111")
				res := httptest.NewRecorder()
				handler.UserDelete(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusBadRequest)
			})
			SkipConvey("Providing a Valid Password", func() {
				// TODO Skipping because there are no teampltes
				// loaded which will cause a panic
				user, _ := database.GetUser(2)
				req.Form.Set("password", "password")
				res := httptest.NewRecorder()
				handler.UserDelete(res, &req, user)

				So(res.Code, ShouldEqual, http.StatusOK)
			})
		})
	})
}
Пример #29
0
/**
 *	测试GetSession的并发情况
 */
func TestRquestGetSession(t *testing.T) {

	runtime.GOMAXPROCS(runtime.NumCPU())
	sm := NewSessionManagerAtGCTime(1, true)
	sm.tempSessMaxlifeTime = 5
	sm.testing = true

	// 统计记录
	errorNum := 0                         //	创建错误session统计
	delSessCount := 0                     //	删除session统计
	sessCreateMap := make(map[string]int) //	创建session统计
	getSessNum := 0                       //	获取session的次数
	isResetToken := true                  //	每次请求重置session token
	// sameReqMap := make(map[string]int)    //	相同请求的计算

	//	并发数量别乱调,小心系统崩溃
	var maxlifeTime int32 = 10 //	session最大有效时间
	forNum := 1000             //	进行多少次并发
	goNum := 100               //	每次并发多少
	wgNum := goNum * forNum
	wg := sync.WaitGroup{}
	wg.Add(wgNum)
	var rwm sync.RWMutex

	sm.AddSessionWillInvalidateHandlerFunc(func(session HttpSession) {
		if nil == session {
			fmt.Println("InvalidateHandlerFunc session nil....")
		}
		rwm.Lock()
		delSessCount++
		rwm.Unlock()
		time.Sleep(time.Duration(1) * time.Second)
	})

	//	request rw num
	reqCount := wgNum / 5
	rws := make([]TestImplResponse, reqCount)
	reqs := make([]*http.Request, reqCount)
	for i := 0; i < reqCount; i++ {
		rws[i] = TestImplResponse{}

		req := http.Request{}
		req.RemoteAddr = "128.0.0.1:8212"
		req.Header = make(http.Header, 1)
		req.Form = make(url.Values)
		reqs[i] = &req
	}

	for i := 0; i < forNum; i++ {
		for j := 0; j < goNum; j++ {
			// fmt.Println(i*forNum + j)
			forIndex := i*goNum + j
			go func() {
				rw := TestImplResponse{}
				req := &http.Request{}
				req.RemoteAddr = "128.0.0.1:8212"
				req.Header = make(http.Header, 1)
				req.Form = make(url.Values)

				sameCookieV := ""
				if forIndex%5 == 0 {
					//	随机获取相同的请求
					rint := SFRandUtil.RandBetweenInt(0, int64(reqCount)-1)
					rw = rws[rint]
					req = reqs[rint]

					//	相同请求计算起来特别累,不知道怎么计算,而且好像计算也没用,这个是客户端的问题,只要服务端session能够正常GC就好。
					// ce, _ := req.Cookie(SESSION_COOKIE_NAME)
					// if nil != ce && "" != ce.Value {
					// 	rwm.Lock()
					// 	if count, ok := sameReqMap[ce.Value]; ok {
					// 		sameReqMap[ce.Value] = count + 1
					// 	} else {
					// 		sameReqMap[ce.Value] = 1
					// 	}
					// 	sameCookieV = ce.Value
					// 	rwm.Unlock()
					// }
				}

				session, err := sm.GetSession(rw, req, maxlifeTime, isResetToken)

				rwm.Lock()
				getSessNum++
				rwm.Unlock()

				if nil != err {
					rwm.Lock()
					errorNum++
					rwm.Unlock()
				} else {
					rwm.Lock()
					if count, ok := sessCreateMap[session.UID()]; ok {
						sessCreateMap[session.UID()] = count + 1
					} else {
						sessCreateMap[session.UID()] = 1
					}
					if "" != sameCookieV {
						//	可以观察session id 与 cookie是否是相同的,看cookie前几位就知道了,前几位是UUID的存储
						//	如果出现不相同可能要检查下cookie token的验证,可能导致了创建了一个新的session
						// fmt.Println(sameCookieV)
						// fmt.Println(session.UID())
					}

					rwm.Unlock()

					if forIndex%15 == 0 {
						session.Invalidate()
					}
				}

				wg.Done()
			}()
		}
	}

	wg.Wait()
	time.Sleep(time.Duration(30) * time.Second)

	//	等待GC最后一次的执行
	if sm.IsGC() {
		for {
			if !sm.IsGC() {
				break
			}
		}
	}

	//	测试要求的结果,只要运行起来不出现系统级别或代码错误(panic)就根据以下判断的结果进行比较就可以了。
	//	创建session数量与GetSession不相同可能是相同的请求照成的,不要紧的。

	//	计算SessionManager存储的session是否正确
	mapSessNum := len(sm.mapSessions)
	listRankSessNum := 0
	for _, v := range sm.listRank {
		listRankSessNum += v.Len()
	}
	fmt.Println("mapSessions num:", mapSessNum)
	fmt.Println("listRankSession num:", listRankSessNum)
	if mapSessNum != listRankSessNum {
		//	如果出现两个不相等就表示存储出逻辑问题,需要调查session的存储情况
		t.Fatalf("mapSessNum != listRankSessNum")
		return
	}

	//	计算相同的请求
	//	相同请求计算起来特别累,不知道怎么计算,而且好像计算也没用,这个是客户端的问题,只要服务端session能够正常GC就好。
	// sameReqNum := 0
	// for _, v := range sameReqMap {
	// 	sameReqNum = sameReqNum + v
	// }
	// fmt.Println("same request num:", sameReqNum)

	//	进行了多少次GetSession
	fmt.Println("GetSession(...) num:", getSessNum)
	fmt.Println("GetSession(...) Error num:", errorNum)

	//	计算创建的session,创建数量与删除数是一致的,如果出现不一致则需要进一步测试,不一致肯定是有错误的。
	sessionCreateNum := len(sessCreateMap)
	fmt.Println("create session num:", sessionCreateNum)
	fmt.Println("delete session num:", delSessCount)

	fmt.Println("not delete session num:", mapSessNum)
	if delSessCount+mapSessNum != sessionCreateNum {
		//	如果这里出现错误表示GC删除的结果与创建session的结果不一致,这里需要调查GC删除是否有错误没有计算到
		t.Fatal("delSessCount+mapSessNum != sessionCreateNum")
		return
	}
	// for k, v := range sessCreateMap {

	// }

}