Beispiel #1
0
func TestTokenLength(t *testing.T) {
	c := newConfig()
	home, _ := os.Getwd()
	c.Home = home

	var err error

	c.Token, err = randutil.AlphaString(32)
	assert.NoError(t, err)
	assert.NoError(t, c.Validate())

	c.Token, err = randutil.AlphaString(10)
	assert.NoError(t, err)
	assert.Error(t, c.Validate())

}
Beispiel #2
0
func home(w http.ResponseWriter, r *http.Request) {
	var id string

	//Create unique RandomUser
	id, _ = randutil.AlphaString(20)

	tmpl, err := template.ParseFiles("./html/index.html")
	if err != nil {
		panic(err)
	}
	var socketProto = "ws"
	if strings.Contains(r.Proto, "HTTPS") {
		socketProto = "wss"
	}
	var first bool
	if 0 == len(serverConnections) {
		first = true
	} else {
		first = false
	}
	values := struct {
		WSocketURL string
		Id         string
		First      bool
	}{
		WSocketURL: socketProto + "://" + r.Host + "/ws/" + id,
		Id:         id,
		First:      first,
	}
	tmpl.Execute(w, values)
}
Beispiel #3
0
func appName(t *testing.T) string {
	rnd, err := randutil.AlphaString(25)
	if err != nil {
		t.Fatal(err)
	}
	rnd = strings.ToLower(rnd)
	return "test-" + rnd
}
Beispiel #4
0
// Initialize a randomly-named testing database
func InitMongo(t *testing.T) *mgo.Database {
	randStr, err := randutil.AlphaString(32)
	if err != nil {
		t.Fatal(err)
	}
	dbName := "testing_" + randStr
	conn, err := mgo.Dial("localhost")
	if err != nil {
		t.Fatal(err)
	}
	return conn.DB(dbName)
}
Beispiel #5
0
func gameHome(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	game := vars["game"]
	var id string
	if *debug {
		id = "123456"
	} else {
		id, _ = randutil.AlphaString(20)
	}
	//Redirect the server to a new instance
	http.Redirect(w, r, "/"+game+"/server/"+id, http.StatusFound)
}
Beispiel #6
0
func TestRoundTrip(t *testing.T) {
	//
	// Initialize mongoStore instance
	//
	db := InitMongo(t)
	defer db.DropDatabase()
	data, err := randutil.AlphaString(512)
	if err != nil {
		t.Fatal(err)
	}
	ms := mongoStore{gfs: db.GridFS("")}
	//
	// Create
	//
	b := bytes.NewBufferString(data)
	fi := FileInfo{
		Type: "text/plain",
	}
	err = ms.Create(&fi, b)
	if err != nil {
		t.Fatal(err)
	}
	key := fi.Key
	t.Log("key:", key)
	//
	// Get
	//
	fi, r, err := ms.Get(key)
	if err != nil {
		t.Error(err)
	}
	rbuf := new(bytes.Buffer)
	io.Copy(rbuf, r)
	retr := rbuf.String()
	if retr != data {
		msg := "Different data retrieved than was saved!\n"
		msg += "data: " + data + "\n"
		msg += "retr: " + retr + "\n"
		t.Error(msg)
	}
	//
	// Delete
	//
	t.Log(key)
	err = ms.Delete(key)
	if err != nil {
		t.Fatal(err)
	}
}
Beispiel #7
0
func createAccountTemplate(t *testing.T) Account {
	rnd, err := randutil.AlphaString(8)
	if err != nil {
		t.Error(err)
	}
	email := "jason.mcvetta+" + rnd + "@gmail.com"
	password := rnd + "Xy123" // Ensure we meet password requirements
	tmpl := Account{
		Username:   rnd,
		Email:      email,
		Password:   password,
		GivenName:  "James",
		MiddleName: "T",
		Surname:    "Kirk",
	}
	return tmpl
}
Beispiel #8
0
func clientRedirect(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]
	game := vars["game"]
	var subid string
	if *debug {
		subid = "7890"
	} else {
		subid, _ = randutil.AlphaString(20)
		//We should ensure that we didn't already random this string for another client for this session...
	}

	proto := getProto(r, false)

	url := proto + "://" + r.Host + "/" + game + "/client/" + id + "/" + subid
	tools.LOG_DEBUG.Println("Redirecting to " + url)
	http.Redirect(w, r, url, http.StatusFound)
}
Beispiel #9
0
func TestRequest(t *testing.T) {
	// NOTE:  Do we really need to test different combinations for different
	// HTTP methods?
	pairs := []pair{}
	for _, test := range reqTests {
		baseReq := Request{
			Method: test.method,
		}
		allReq := baseReq // allRR has all supported attribues for this verb
		var allHF hfunc   // allHF is combination of all relevant handlers
		//
		// Generate a random key/value pair
		//
		key, err := randutil.AlphaString(8)
		if err != nil {
			t.Error(err)
		}
		value, err := randutil.AlphaString(8)
		if err != nil {
			t.Error(err)
		}
		//
		// Method
		//
		r := baseReq
		f := methodHandler(t, test.method, nil)
		allHF = methodHandler(t, test.method, allHF)
		pairs = append(pairs, pair{r, f})
		//
		// Header
		//
		h := http.Header{}
		h.Add(key, value)
		r = baseReq
		r.Header = &h
		allReq.Header = &h
		f = headerHandler(t, h, nil)
		allHF = headerHandler(t, h, allHF)
		pairs = append(pairs, pair{r, f})
		//
		// Params
		//
		if test.params {
			p := Params{key: value}.AsUrlValues()
			f := paramHandler(t, p, nil)
			allHF = paramHandler(t, p, allHF)
			r = baseReq
			r.Params = &p
			allReq.Params = &p
			pairs = append(pairs, pair{r, f})
		}
		//
		// Payload
		//
		if test.payload {
			p := payload{value}
			f = payloadHandler(t, p, nil)
			allHF = payloadHandler(t, p, allHF)
			r = baseReq
			r.Payload = p
			allReq.Payload = p
			pairs = append(pairs, pair{r, f})
		}
		//
		// All
		//
		pairs = append(pairs, pair{allReq, allHF})
	}
	for _, p := range pairs {
		srv := httptest.NewServer(http.HandlerFunc(p.hf))
		defer srv.Close()
		//
		// Good request
		//
		p.r.Url = "http://" + srv.Listener.Addr().String()
		_, err := Send(&p.r)
		if err != nil {
			t.Error(err)
		}
	}
}
Beispiel #10
0
func main() {
	conf, err := config.New("./config.json")
	if err != nil {
		log.Fatalf("Error parsing confuration file: %s", err.Error())
	}
	if conf.JWTKey == "" {
		log.Fatalf("jwt_secret in config.json is not set, please set this to a random value")
	}

	db, err := boltons.Open(conf.BoltDBFile, 0600, nil)
	if err != nil {
		log.Fatalf("Error opening db: %s", err.Error())
	}
	defer db.Close()

	keys, err := db.Keys(models.User{})
	if err != nil {
		log.Fatalf("Error getting keys from db: %s", err.Error())
	}
	if len(keys) == 0 {
		log.Println("No users found creating admin@localhost user with random password")
		random, err := randutil.AlphaString(10)
		if err != nil {
			log.Fatalf("Error generating password: %s", err.Error())
		}
		firstUser, err := models.NewUser("admin@localhost", []byte(random))
		if err != nil {
		}
		if err := db.Save(firstUser); err != nil {
			log.Fatalf("Error saving first user to db: %s", err.Error())
		}
		log.Printf("admin@localhost password set to %s", random)
	}

	serverApp := &app.App{
		DB:        db,
		JWTSecret: []byte(conf.JWTKey),
		Render:    render.New(),
		Config:    conf,
	}

	if conf.Proxy.SSL.Enabled {
		sslMux := http.NewServeMux()
		sslMux.HandleFunc("/", handlers.Proxy(serverApp, true))
		sslRecovery := negroni.NewRecovery()
		sslRecovery.PrintStack = false
		sslProxy := negroni.New(sslRecovery)
		sslProxy.UseHandler(sslMux)
		go func() {
			log.Fatal(http.ListenAndServeTLS(conf.Proxy.SSL.Listener, conf.Proxy.SSL.Cert, conf.Proxy.SSL.Key, sslProxy))
		}()
	}

	if conf.Proxy.HTTP.Enabled {
		httpMux := http.NewServeMux()
		httpMux.HandleFunc("/", handlers.Proxy(serverApp, false))
		httpRecovery := negroni.NewRecovery()
		httpRecovery.PrintStack = false
		httpProxy := negroni.New(httpRecovery)
		httpProxy.UseHandler(httpMux)
		go func() {
			log.Fatal(http.ListenAndServe(conf.Proxy.HTTP.Listener, httpProxy))
		}()
	}

	if conf.Proxy.DNS.Enabled {
		tcpDNServer := &dns.Server{Addr: conf.Proxy.DNS.Listener, Net: "udp"}
		udpDNServer := &dns.Server{Addr: conf.Proxy.DNS.Listener, Net: "tcp"}

		dns.HandleFunc(".", handlers.ProxyDNS(serverApp))

		go func() {
			log.Fatal(tcpDNServer.ListenAndServe())
		}()

		go func() {
			log.Fatal(udpDNServer.ListenAndServe())
		}()
	}

	r := mux.NewRouter()
	api := mux.NewRouter()
	r.HandleFunc("/api/token", handlers.UserToken(serverApp)).Methods("POST")

	api.HandleFunc("/api/users", handlers.CreateUser(serverApp)).Methods("POST")
	api.HandleFunc("/api/users", handlers.IndexUser(serverApp)).Methods("GET")
	api.HandleFunc("/api/users/{id}", handlers.ShowUser(serverApp)).Methods("GET")
	api.HandleFunc("/api/users/{id}", handlers.DeleteUser(serverApp)).Methods("DELETE")
	api.HandleFunc("/api/users/{id}", handlers.UpdateUser(serverApp)).Methods("PUT")
	api.HandleFunc("/api/records", handlers.CreateRecord(serverApp)).Methods("POST")
	api.HandleFunc("/api/records", handlers.IndexRecord(serverApp)).Methods("GET")
	api.HandleFunc("/api/records/{id}", handlers.ShowRecord(serverApp)).Methods("GET")
	api.HandleFunc("/api/records/{id}", handlers.DeleteRecord(serverApp)).Methods("DELETE")
	api.HandleFunc("/api/records/{id}", handlers.UpdateRecord(serverApp)).Methods("PUT")
	api.HandleFunc("/api/info", handlers.Info(serverApp, version)).Methods("GET")

	r.PathPrefix("/api").Handler(negroni.New(
		negroni.HandlerFunc(middleware.JWTAuth(serverApp)),
		negroni.HandlerFunc(middleware.SetUserContext(serverApp)),
		negroni.Wrap(api),
	))

	server := negroni.New(
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("static")),
		negroni.NewRecovery(),
	)

	server.UseHandler(r)
	log.Fatal(http.ListenAndServeTLS(conf.Admin.Listener, conf.Admin.Cert, conf.Admin.Key, server))

}
Beispiel #11
0
func getBar(request *restful.Request, response *restful.Response) {
	var b Bar
	b.Rand, _ = randutil.AlphaString(8)
	response.WriteEntity(&b)
}