Example #1
0
func main() {
	var addr = flag.String("addr", ":8080", "The addr of the application.")
	// set up gomniauth
	gomniauth.SetSecurityKey("lfq618")
	gomniauth.WithProviders(
		facebook.New("608517422619964", "ff3966474a0e0925419a57cd79776bdd", "http://localhost:8080/auth/callback/facebook"),
		github.New("6f6ab375ab58c83ce223", "20e565a7e13d235c60ede23a26d33bd8a735e03a", "http://localhost:8080/auth/callback/github"),
		google.New("507301202565-k1drgkq7v6u5b42fk849k90pm33b3van.apps.googleusercontent.com", "EmPZvBUVc1-Tc5fWQ4gjSh78", "http://localhost:8080/auth/callback/google"),
	)

	r := newRoom()
	//r.tracer = trace.New(os.Stdout)

	//root
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)

	//get the room goint
	go r.run()

	//start the web server
	log.Println("Starting web server on", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #2
0
func main() {
	var addr = flag.String("addr", ":18080", "アプリケーションのアドレス")
	flag.Parse() // フラグを解釈します

	// Gomniauth のセットアップ
	gomniauth.SetSecurityKey("RESIDENCE101")
	gomniauth.WithProviders(
		facebook.New("957653387645069", "bd4b9984868d78cb2012b4554a6c61a8", "http://localhost:18080/auth/callback/facebook"),
		github.New("60c22ff289a776f58746", "cd1581d547e80cfc01586bdfd343317a8b9e3f65", "http://localhost:18080/auth/callback/github"),
		google.New("940801949020-9b6d4r5emh1k6ds9mmmiq1esdt669mrs.apps.googleusercontent.com", "jd3H38hVee1Ragcx0UzStHoW", "http://localhost:18080/auth/callback/google"),
	)

	r := newRoom()
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)

	// チャットルームを開始します
	go r.run()

	// Web サーバーを開始します
	log.Println("Web サーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #3
0
func main() {
	var addr = flag.String("addr", ":8080", "アプリケーションのアドレス")
	flag.Parse() // フラグを解釈します
	// Gomniauthのセットアップ
	gomniauth.SetSecurityKey("セキュリティキー")
	gomniauth.WithProviders(
		facebook.New("クライアントID", "秘密の値", "http://localhost:8080/auth/callback/facebook"),
		github.New("クライアントID", "秘密の値", "http://localhost:8080/auth/callback/github"),
		google.New("クライアントID", "秘密の値", "http://localhost:8080/auth/callback/google"),
	)

	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)
	// チャットルームを開始します
	go r.run()
	// Webサーバーを起動します
	log.Println("Webサーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
func main() {
	var addr = flag.String("addr", ":8080", "The addr of the application.")
	flag.Parse() // parse the flags
	gomniauth.SetSecurityKey("some long key")
	gomniauth.WithProviders(
		facebook.New("key", "secret", "http://localhost:8080/auth/callback/facebook"),
		github.New("key", "secret", "http://localhost:8080/auth/callback/github"),
		google.New("key", "secret", "http://localhost:8080/auth/callback/google"),
	)
	r := newRoom()
	r.tracer = trace.New(os.Stdout)

	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)

	// get the room going
	go r.run()

	// start the web server
	log.Println("Starting web server on", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}

}
Example #5
0
func main() {
	var addr = flag.String("addr", ":8080", "The addr of the application")
	flag.Parse()

	gomniauth.SetSecurityKey("wetre94541gd616fd1g6fd")
	gomniauth.WithProviders(
		facebook.New("1578364069092723", "3be3e79ef1c5a14a8d556d45ab28bc23",
			"http://localhost:8080/auth/callback/facebook"),
		google.New("773345955621-aj0hpvne7depi9er2cp72t2mrknb3l26.apps.googleusercontent.com", "zT2_36o-f18VxmmvdltT_9vX",
			"http://localhost:8080/auth/callback/google"),
	)

	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHander)
	http.Handle("/room", r)

	//start the room in the background
	go r.run()

	//start the web server
	log.Println("Starting web server on", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #6
0
func main() {

	flag.Parse() // parse the flags

	// setup gomniauth
	gomniauth.SetSecurityKey("98dfbg7iu2nb4uywevihjw4tuiyub34noilk")
	gomniauth.WithProviders(
		github.New("3d1e6ba69036e0624b61", "7e8938928d802e7582908a5eadaaaf22d64babf1", "http://localhost:8080/auth/callback/github"),
		google.New("44166123467-o6brs9o43tgaek9q12lef07bk48m3jmf.apps.googleusercontent.com", "rpXpakthfjPVoFGvcf9CVCu7", "http://localhost:8080/auth/callback/google"),
		facebook.New("537611606322077", "f9f4d77b3d3f4f5775369f5c9f88f65e", "http://localhost:8080/auth/callback/facebook"),
	)

	r := newRoom()
	r.tracer = trace.New(os.Stdout)

	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)

	// get the room going
	go r.run()

	// start the web server
	log.Println("Starting web server on", *host)
	if err := http.ListenAndServe(*host, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}

}
Example #7
0
func main() {
	// The de nition for the addr variable sets up our flag
	// as a string that defaults to :8080
	addr := flag.String("addr", ":8080", "The addr of the application.")
	// must call flag. Parse() that parses the arguments
	// and extracts the appropriate information.
	// Then, we can reference the value of the host  ag by using *addr.
	flag.Parse() // parse the flags

	// set up gomniauth
	gomniauth.SetSecurityKey("some long key")
	gomniauth.WithProviders(
		facebook.New("key", "secret", ""),
		github.New("key", "secret", ""),
		google.New("151570833065-i9p63mogjm7adt0h0490or9bvqua0r2l.apps.googleusercontent.com",
			"jzEEORYarixD30S6qyosGrWe",
			"http://localhost:3000/auth/callback/google"),
	)

	//	r := newRoom(UseAuthAvatar)
	//	r := newRoom(UseGravatar)
	r := newRoom(UseFileSystemAvatar)
	r.tracer = trace.New(os.Stdout)

	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploaderHandler)
	http.Handle("/avatars/",
		http.StripPrefix("chapter2/chat/avatars/",
			http.FileServer(http.Dir("./avatars"))))

	// get the room going
	// running the room in a separate Go routine
	// so that the chatting operations occur in the background,
	// allowing our main thread to run the web server.
	go r.run()
	// start the web server
	log.Println("Starting web server on", *addr)
	// start the web server
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #8
0
func main() {
	var addr = flag.String("addr", ":8080", "The addr of the application.")
	flag.Parse() // parse the flags

	// set up gomniauth
	gomniauth.SetSecurityKey("amazing2050")
	gomniauth.WithProviders(
		facebook.New("key", "secret", "http://localhost:8080/auth/callback/facebook"),
		github.New("key", "secret", "http://localhost:8080/auth/callback/github"),
		google.New("638547583987-2l7p38d7iq7kpp2rvvms4ambvg1qaq5b.apps.googleusercontent.com", "whS4UlWsA0YXRdD7nVQScrcK", "http://localhost:8080/auth/callback/google"),
	)

	r := newRoom()
	r.tracer = trace.New(os.Stdout)

	// handlers
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHander)
	http.Handle("/room", r)
	http.Handle("/upload", MustAuth(&templateHandler{filename: "upload.html"}))
	http.HandleFunc("/uploader", uploaderHandler)
	// both http.StripPrefix and http.FileServer return Handler and they
	// use the decorator pattern
	// The StripPrefix function takes Handler in, modifies the path by removing
	// the specified prefix, and passes functionality onto an inner handler.
	// The FileServer handler simply serve static files, and generating the
	// 404 Not Fount error if it cannot find the file.
	http.Handle("/avatars/",
		http.StripPrefix("/avatars/",
			http.FileServer(http.Dir("./avatars"))))
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})

	// get the room going
	go r.run()
	// start the web server
	log.Println("Starting web server on", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #9
0
func main() {
	addr := flag.String("addr", ":8080", "An address of application")
	flag.Parse()

	config := loadConfig()

	gomniauth.SetSecurityKey("セキュリティキー")
	gomniauth.WithProviders(
		facebook.New(
			config.Facebook.ClientID,
			config.Facebook.ClientSecret,
			"http://localhost:8080/auth/callback/facebook",
		),
		github.New(
			config.Github.ClientID,
			config.Github.ClientSecret,
			"http://localhost:8080/auth/callback/github",
		),
		google.New(
			config.Google.ClientID,
			config.Google.ClientSecret,
			"http://localhost:8080/auth/callback/google",
		),
	)
	r := newRoom(UseGravatar)
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploadHandler)

	go r.run()
	log.Println("start web server. port: ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #10
0
func main() {
	var addr = flag.String("addr", ":8080", "アプリケーションのアドレス")
	flag.Parse()

	c, err := redis.Dial("tcp", ":6379")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer c.Close()
	log.Println("Redisにせつぞくしました。")

	gomniauth.SetSecurityKey(os.Getenv("FUNNYCHAT_SECURITY_KEY"))
	gomniauth.WithProviders(
		facebook.New(os.Getenv("FB_CLIENT_ID"), os.Getenv("FB_SECRET_KEY"), "http://localhost:8080/auth/callback/facebook"),
		google.New(os.Getenv("GOOGLE_CLIENT_ID"), os.Getenv("GOOGLE_SECRET_KEY"), "http://localhost:8080/auth/callback/google"),
		github.New(os.Getenv("GITHUB_CLIENT_ID"), os.Getenv("GITHUB_SECRET_KEY"), "http://localhost:8080/auth/callback/github"),
	)

	r := newRoom(c)
	r.subscribe("room01")
	r.tracer = trace.New(os.Stdout)

	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.Handle("/room", r)
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploadHandler)
	http.Handle("/avatars/", http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars"))))
	http.Handle("/assets/", http.StripPrefix("/assets", http.FileServer(http.Dir("assets"))))
	go r.run()
	go r.receive()
	log.Println("Webサーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #11
0
func main() {
	var addr = flag.String("addr", ":8080", "The addr of the application.")
	flag.Parse() // parse the flags
	//	set up gomniauth
	gomniauth.SetSecurityKey("this is my own crazy phrase not")
	gomniauth.WithProviders(
		facebook.New("key", "secret", "http://localhost:8080/auth/callback/facebook"),
		github.New("key", "secret", "http://localhost:8080/auth/callback/github"),
		google.New("AIzaSyAHdC_P8iM2SU3D5BEh5747tGb4Sr5xxj8", "3aoJeQ8Ub3l2Gfvz-wNIOXUo", "http://localhost:8080/auth/callback/google"),
	)
	r := newRoom()
	//	output to the os.Stdout standard output pipe (prints output to the terminal)
	//r.tracer = trace.New(os.Stdout)
	// root
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)

	//	Directory used to store css and js files.
	//http.Handle("/assets/",
	//	http.StripPrefix("/assets",
	//		http.FileServer(http.Dir("/path/to/assets/"))))

	//	get the room going
	go r.run()

	//	Writes out the hardcoded HTML when a request is made
	/*http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`
			<html>
				<head>
					<title>Chat</title>
				</head>
				<body>
					Let's chat!
				</body>
			</html>
		`))
	})*/
	// 	Starts web server using ListenAndServe
	log.Println("Starting web server on", *addr)
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #12
0
func main() {

	flag.Parse() // parse the flags

	// setup gomniauth
	gomniauth.SetSecurityKey("98dfbg7iu2nb4uywevihjw4tuiyub34noilk")
	gomniauth.WithProviders(
		github.New("3d1e6ba69036e0624b61", "7e8938928d802e7582908a5eadaaaf22d64babf1", "http://localhost:8080/auth/callback/github"),
		google.New("44166123467-o6brs9o43tgaek9q12lef07bk48m3jmf.apps.googleusercontent.com", "rpXpakthfjPVoFGvcf9CVCu7", "http://localhost:8080/auth/callback/google"),
		facebook.New("537611606322077", "f9f4d77b3d3f4f5775369f5c9f88f65e", "http://localhost:8080/auth/callback/facebook"),
	)

	r := newRoom()
	r.tracer = trace.New(os.Stdout)

	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header().Set("Location", "/chat")
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploaderHandler)

	http.Handle("/avatars/",
		http.StripPrefix("/avatars/",
			http.FileServer(http.Dir("./avatars"))))

	// get the room going
	go r.run()

	// start the web server
	log.Println("Starting web server on", *host)
	if err := http.ListenAndServe(*host, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}

}
Example #13
0
func main() {
	var addr = flag.String("addr", ":3000", "The addr of the application")
	flag.Parse()

	// set up gomniauth
	gomniauth.SetSecurityKey("some long key")
	gomniauth.WithProviders(
		facebook.New("key", "secret",
			"http://localhost:3000/auth/callback/facebook"),
		github.New("key", "secret",
			"http://localhost:3000/auth/callback/github"),
		google.New("89198476902-sp9n6ukjk37ccc2vuh11chkga865sidq.apps.googleusercontent.com", "GeQA1wriK2DdN_tTg8Sv1x9r",
			"http://localhost:3000/auth/callback/google"),
	)

	r := newRoom(UseAuthAvatar)
	http.HandleFunc("/room", r.serveHTTP)

	mainTemplate := &templateHandler{filename: "chat.html", messages: r.Messages}
	loginTemplate := &templateHandler{filename: "login.html"}

	http.HandleFunc("/auth/", LoginHandler)
	http.HandleFunc("/chat", MustAuth(mainTemplate).ServeHTTP)
	http.HandleFunc("/login", loginTemplate.ServeHTTP)

	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})

	go r.run()

	log.Println("Server starting on ", *addr)
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Example #14
0
func main() {
	var addr = flag.String("addr", ":8080", "The addr of the application")
	flag.Parse()

	gomniauth.SetSecurityKey("wetre94541gd616fd1g6fd")
	gomniauth.WithProviders(
		facebook.New("1578364069092723", "3be3e79ef1c5a14a8d556d45ab28bc23",
			"http://localhost:8080/auth/callback/facebook"),
		google.New("773345955621-aj0hpvne7depi9er2cp72t2mrknb3l26.apps.googleusercontent.com", "zT2_36o-f18VxmmvdltT_9vX",
			"http://localhost:8080/auth/callback/google"),
	)

	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHander)
	http.Handle("/room", r)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploadHandler)
	http.Handle("/avatars/",
		http.StripPrefix("/avatars",
			http.FileServer(http.Dir("./avatars"))))

	//start the room in the background
	go r.run()

	//start the web server
	log.Println("Starting web server on", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #15
0
func main() {

	// setup the providers
	gomniauth.SetSecurityKey("yLiCQYG7CAflDavqGH461IO0MHp7TEbpg6TwHBWdJzNwYod1i5ZTbrIF5bEoO3oP") // NOTE: DO NOT COPY THIS - MAKE YOR OWN!
	gomniauth.WithProviders(
		github.New("3d1e6ba69036e0624b61", "7e8938928d802e7582908a5eadaaaf22d64babf1", "http://localhost:8080/auth/github/callback"),
		google.New("1051709296778.apps.googleusercontent.com", "7oZxBGwpCI3UgFMgCq80Kx94", "http://localhost:8080/auth/google/callback"),
		facebook.New("537611606322077", "f9f4d77b3d3f4f5775369f5c9f88f65e", "http://localhost:8080/auth/facebook/callback"),
	)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		template := `
			<!DOCTYPE html>
			<html>
				<body>
				<h2>Log in with...</h2>
				<ul>
					<li>
					<a href="auth/github/login">GitHub</a>
					</li>
					<li>
					<a href="auth/google/login">Google</a>
					</li>
					<li>
					<a href="auth/facebook/login">Facebook</a>
					</li>
				</ul>
				</body>
			</html>
			`
		io.WriteString(w, template)
	})

	providers := []string{"google", "github", "facebook"}
	for _, provider := range providers {
		http.HandleFunc(fmt.Sprintf("/auth/%s/login", provider), loginHandler(provider))
		http.HandleFunc(fmt.Sprintf("/auth/%s/callback", provider), callbackHandler(provider))
	}

	http.ListenAndServe(Address, nil)

}
Example #16
0
func main() {
	var addr = flag.String("addr", ":8080", "アプリケーションのアドレス")
	flag.Parse() // フラグを解釈します
	// Gomniauthのセットアップ
	gomniauth.SetSecurityKey("セキュリティキー")
	gomniauth.WithProviders(
		facebook.New("クライアントID", "秘密の値", "http://localhost:8080/auth/callback/facebook"),
		github.New("クライアントID", "秘密の値", "http://localhost:8080/auth/callback/github"),
		google.New("クライアントID", "秘密の値", "http://localhost:8080/auth/callback/google"),
	)

	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploaderHandler)
	http.Handle("/avatars/",
		http.StripPrefix("/avatars/",
			http.FileServer(http.Dir("./avatars"))))

	http.Handle("/room", r)
	// チャットルームを開始します
	go r.run()
	// Webサーバーを起動します
	log.Println("Webサーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #17
0
func main() {
	var addr = flag.String("addr", ":8080", "The addr of the application.")
	// set up gomniauth
	gomniauth.SetSecurityKey("lfq618")
	gomniauth.WithProviders(
		facebook.New("608517422619964", "ff3966474a0e0925419a57cd79776bdd", "http://localhost:8080/auth/callback/facebook"),
		github.New("6f6ab375ab58c83ce223", "20e565a7e13d235c60ede23a26d33bd8a735e03a", "http://localhost:8080/auth/callback/github"),
		google.New("507301202565-k1drgkq7v6u5b42fk849k90pm33b3van.apps.googleusercontent.com", "EmPZvBUVc1-Tc5fWQ4gjSh78", "http://localhost:8080/auth/callback/google"),
	)

	r := newRoom()
	//r.tracer = trace.New(os.Stdout)

	//root
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploaderHandler)
	http.HandleFunc("/auth/", loginHandler)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.Handle("/room", r)
	http.Handle("/avatars/", http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars"))))

	//get the room goint
	go r.run()

	//start the web server
	log.Println("Starting web server on", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #18
0
func main() {
	var host = flag.String("host", ":8080", "The host of the application.")
	flag.Parse()

	key, secret := ReadCredentials("keys/chat-keys-google.json")
	// Set up gomniauth.
	gomniauth.SetSecurityKey("Q/AnKc03rI1ZzMuOBDL0ZCJiWbmO1dMUk3PiH6e/Gi83pqljwt9kV9eEZl7a5s0H")
	gomniauth.WithProviders(
		facebook.New("key", "secret", "http://localhost:8080/auth/callback/facebook"),
		github.New("key", "secret", "http://localhost:8080/auth/callback/github"),
		google.New(key, secret, "http://localhost:8080/auth/callback/google"),
	)

	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/avatars/", http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars"))))
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploadHandler)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})

	r := newRoom()
	// r.tracer = trace.New(os.Stdout)
	http.Handle("/room", r)
	go r.run()

	// Start the web server.
	log.Println("Starting web server on", *host)
	if err := http.ListenAndServe(*host, nil); err != nil {
		log.Fatal("ListenAndServer:", err)
	}
}
Example #19
0
func main() {

	var addr = flag.String("addr", ":8080", "Address of application.")
	flag.Parse()

	// set up gomniauth
	// callback URLs that will receive auth token comes as 3rd argument for each provider
	gomniauth.SetSecurityKey("some key here")
	gomniauth.WithProviders(
		facebook.New("key", "secret",
			"http://localhost:8080/auth/callback/facebook"),
		github.New("key", "secret",
			"http://localhost:8080/auth/callback/github"),
		google.New("key", "secret",
			"http://localhost:8080/auth/callback/google"),
	)

	r := newRoom()
	// r.tracer = trace.New(os.Stdout)

	// http.Handle('routeToURL' 'Handler')
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))

	// No need for MustAuth wrapper otherwise it goes to an infinite redirection loop
	http.Handle("/login", &templateHandler{filename: "login.html"})

	// Since we don't need to maintain any state (object) we can use HandleFunc and pass a function to it
	http.HandleFunc("/auth/", loginHandler)

	http.Handle("/room", r)

	// get the room going (initialize that infinite loop in threads [goroutine])
	go r.run()

	// Log web server startup
	log.Println("Starting web server on...", *addr)

	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Example #20
0
func main() {
	var addr = flag.String("addr", ":18080", "アプリケーションのアドレス")
	flag.Parse() // フラグを解釈します

	// Gomniauth のセットアップ
	gomniauth.SetSecurityKey("RESIDENCE101")
	gomniauth.WithProviders(
		facebook.New("957653387645069", "bd4b9984868d78cb2012b4554a6c61a8", "http://localhost:18080/auth/callback/facebook"),
		github.New("60c22ff289a776f58746", "cd1581d547e80cfc01586bdfd343317a8b9e3f65", "http://localhost:18080/auth/callback/github"),
		google.New("940801949020-9b6d4r5emh1k6ds9mmmiq1esdt669mrs.apps.googleusercontent.com", "jd3H38hVee1Ragcx0UzStHoW", "http://localhost:18080/auth/callback/google"),
	)

	r := newRoom()
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploaderHandler)
	http.Handle("/avatars/", http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars"))))

	// チャットルームを開始します
	go r.run()

	// Web サーバーを開始します
	log.Println("Web サーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #21
0
func main() {
	var addr = flag.String("addr", ":8080", "アプリケーションのアドレス")
	flag.Parse()

	// Gomniauthのセットアップ
	gomniauth.SetSecurityKey("98dfbg7iu2nb4uywevihjw4tuiyub34noilk")
	gomniauth.WithProviders(
		github.New("e87fd3d4443a41a869eb", "f9efbb46a454cdfbea1e713c9c4bf1df90ceb5f8", "http://localhost:8080/auth/callback/github"),
		facebook.New("866458566797843", "c265d1fe8f5bf6eb28066e20a7f25281", "http://localhost:8080/auth/callback/facebook"),
	)

	r := newRoom(UseFileSystemAvatar)

	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.Handle("/avatars/", http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars"))))
	http.HandleFunc("/auth/", loginHandler)
	http.HandleFunc("/uploader", uploaderHandler)
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})

	http.Handle("/room", r)
	// チャット開始
	go r.run()
	// Webサーバを開始
	log.Println("Webサーバー開始。ポート:", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #22
0
func main() {

	var addr = flag.String("addr", ":8080", "The addr of the application.")
	flag.Parse() // parse the flag

	JsonConfigInit()

	// set up gomniauth
	gomniauth.SetSecurityKey("some long key")
	gomniauth.WithProviders(
		facebook.New("", "",
			"http://localhost:8080/auth/callback/facebook"),
		github.New("key", "secret",
			"http://localhost:8080/auth/callback/github"),
		google.New(jsonConfig.GoogleAuth.Key, jsonConfig.GoogleAuth.Secret,
			"http://localhost:8080/auth/callback/google"),
	)

	http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))

	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.Handle("/room", r)

	muxr := mux.NewRouter()
	muxr.HandleFunc("/auth/{action}/{provider}", loginHandler)
	http.Handle("/auth/", muxr)

	// get the room going
	go r.run()

	// start the web server
	log.Println("Starting web server on", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #23
0
func main() {
	addr := flag.String("addr", ":8080", "the addr of the app")
	flag.Parse()

	// setup gomniauth
	// it's a lot effort to setup gomniauth package to work
	gomniauth.SetSecurityKey("some long key")
	gomniauth.WithProviders(
		google.New(
			"158657564022-mt9rk82d9iqjpcjr184ckhhsg6f8idkg.apps.googleusercontent.com", // client Id
			"ljQvpTZZBrh7KY9vN4NyYh8R",                                                 // client secret
			"http://localhost:8080/auth/callback/google"),
		github.New(
			"ea3a81ad4933259c2632",
			"456fce8185c579590a1a35b48a72d0b1abdcf4a0",
			"http://localhost:8080/auth/callback/github"),
		facebook.New("key", "secret", "http://localhost:8080/auth/callback/facebook"),
	)

	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploaderHandler)
	http.HandleFunc("/auth/", loginHandler)
	http.HandleFunc("/logout", logoutHandler)

	// static resources
	pattern := "/js/"
	http.Handle(pattern, http.StripPrefix(pattern, http.FileServer(http.Dir("./js")))) // or "js"

	pattern = "/assets/"
	http.Handle(pattern, http.StripPrefix(pattern, http.FileServer(http.Dir("./assets"))))

	pattern = "/avatars/"
	http.Handle(pattern, http.StripPrefix(pattern, http.FileServer(http.Dir("./avatars"))))

	// r := newRoom(UseAuthAvatar)
	// r := newRoom(UseGravatar)
	r := newRoom()
	http.Handle("/room", r)

	// get the room going
	go r.run()

	// http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	// 	w.Write([]byte(`
	// 	<html>
	// 	<head>
	// 		<title>Chat</title>
	// 	</head>
	// 	<body>
	// 	Let's chat!
	// 	</body>
	// 	</html>
	// 	`))
	// })

	// start the web server
	log.Println("starting web server on", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #24
0
func main() {

	// setup the providers
	gomniauth.SetSecurityKey("yLiCQYG7CAflDavqGH461IO0MHp7TEbpg6TwHBWdJzNwYod1i5ZTbrIF5bEoO3oP") // NOTE: DO NOT COPY THIS - MAKE YOR OWN!
	gomniauth.WithProviders(
		github.New("3d1e6ba69036e0624b61", "7e8938928d802e7582908a5eadaaaf22d64babf1", "http://localhost:8080/auth/github/callback"),
		google.New("1051709296778.apps.googleusercontent.com", "7oZxBGwpCI3UgFMgCq80Kx94", "http://localhost:8080/auth/google/callback"),
		facebook.New("537611606322077", "f9f4d77b3d3f4f5775369f5c9f88f65e", "http://localhost:8080/auth/facebook/callback"),
		uber.New("UBERKEY", "UBERSECRET", "http://localhost:8080/auth/uber/callback"),
	)

	goweb.Map("/", func(ctx context.Context) error {

		return goweb.Respond.With(ctx, http.StatusOK, []byte(`
      <html>
        <body>
          <h2>Log in with...</h2>
          <ul>
            <li>
              <a href="auth/github/login">GitHub</a>
            </li>
            <li>
              <a href="auth/google/login">Google</a>
            </li>
            <li>
              <a href="auth/facebook/login">Facebook</a>
            </li>
             <li>
              <a href="auth/uber/login">Uber</a>
            </li>
          </ul>
        </body>
      </html>
    `))

	})

	/*
	   GET /auth/{provider}/login

	   Redirects them to the fmtin page for the specified provider.
	*/
	goweb.Map("auth/{provider}/login", func(ctx context.Context) error {

		provider, err := gomniauth.Provider(ctx.PathValue("provider"))

		if err != nil {
			return err
		}

		state := gomniauth.NewState("after", "success")

		// if you want to request additional scopes from the provider,
		// pass them as login?scope=scope1,scope2
		//options := objx.MSI("scope", ctx.QueryValue("scope"))

		authUrl, err := provider.GetBeginAuthURL(state, nil)

		if err != nil {
			return err
		}

		// redirect
		return goweb.Respond.WithRedirect(ctx, authUrl)

	})

	goweb.Map("auth/{provider}/callback", func(ctx context.Context) error {

		provider, err := gomniauth.Provider(ctx.PathValue("provider"))

		if err != nil {
			return err
		}

		creds, err := provider.CompleteAuth(ctx.QueryParams())

		if err != nil {
			return err
		}

		/*
			// get the state
			state, stateErr := gomniauth.StateFromParam(ctx.QueryValue("state"))

			if stateErr != nil {
				return stateErr
			}

			// redirect to the 'after' URL
			afterUrl := state.GetStringOrDefault("after", "error?e=No after parameter was set in the state")

		*/

		// load the user
		user, userErr := provider.GetUser(creds)

		if userErr != nil {
			return userErr
		}

		return goweb.API.RespondWithData(ctx, user)

		// redirect
		//return goweb.Respond.WithRedirect(ctx, afterUrl)

	})

	/*
	   ----------------------------------------------------------------
	   START OF WEB SERVER CODE
	   ----------------------------------------------------------------
	*/

	log.Println("Starting...")
	fmt.Print("Gomniauth - Example web app\n")
	fmt.Print("by Mat Ryer and Tyler Bunnell\n")
	fmt.Print(" \n")
	fmt.Print("Starting Goweb powered server...\n")

	// make a http server using the goweb.DefaultHttpHandler()
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)

	fmt.Printf("  visit: %s\n", Address)

	if listenErr != nil {
		log.Fatalf("Could not listen: %s", listenErr)
	}

	fmt.Println("\n")
	fmt.Println("Try some of these routes:\n")
	fmt.Printf("%s", goweb.DefaultHttpHandler())
	fmt.Println("\n\n")

	go func() {
		for _ = range c {

			// sig is a ^C, handle it

			// stop the HTTP server
			fmt.Print("Stopping the server...\n")
			listener.Close()

			/*
			   Tidy up and tear down
			*/
			fmt.Print("Tearing down...\n")

			// TODO: tidy code up here

			log.Fatal("Finished - bye bye.  ;-)\n")

		}
	}()

	// begin the server
	log.Fatalf("Error in Serve: %s\n", s.Serve(listener))

	/*
	   ----------------------------------------------------------------
	   END OF WEB SERVER CODE
	   ----------------------------------------------------------------
	*/

}
Example #25
0
func main() {
	// reading configuration file and creating "configuration" object to store
	// values
	file, _ := os.Open("conf.json")
	decoder := json.NewDecoder(file)
	configuration := Configuration{}
	err := decoder.Decode(&configuration)
	if err != nil {
		fmt.Println("error:", err)
	}
	// looking for option args when starting App
	// like ./chat -addr=":3000" would start on this port
	var addr = flag.String("addr", ":8080", "App address")
	flag.Parse() // parse the flag
	// setting up gomniauth
	// creating random key http://godoc.org/github.com/stretchr/signature#RandomKey
	// in addition to gomniauth package we need to download:
	// go get github.com/clbanning/x2j
	// go get github.com/ugorji/go/codec
	// go get labix.org/v2/mgo/bson
	gomniauth.SetSecurityKey(signature.RandomKey(64))
	gomniauth.WithProviders(
		facebook.New("key", "secret",
			"http://localhost:8080/auth/callback/facebook"),
		github.New("key", "secret",
			"http://localhost:8080/auth/callback/github"),
		google.New(configuration.GoogleKey,
			configuration.GoogleSecret,
			"http://localhost:8080/auth/callback/google"),
	)
	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	// HTTP handlers
	// wrapping /chat handler with MustAuth to enforce authentication
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	// logout, deleting cookie data
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploadHandler)
	// servis static images
	// http.StripPrefix takes Handler in, modifies the path by removing
	// the specified prefix and passes functionality onto an inner
	// handler. Inner handler - http.FileServer servers static files,
	// provides index listing and generates 404 for missing objects
	// http.Dir function allows to specify exposed folders
	http.Handle("/avatars/",
		http.StripPrefix("/avatars/",
			http.FileServer(http.Dir("./avatars"))))
	// get the room going
	go r.run()
	// start the web server
	log.Println("Starting we server on ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #26
0
File: main.go Project: catanm/gms
func main() {

	log.Info("Glasgow Memories Server")
	log.Info("=======================")

	utils.InitEnv()
	var Address = ":" + utils.EnvPort()
	var baseURL = utils.EnvUrl()

	m.Connect()
	defer m.Close()

	// prepare the decryption key
	if utils.LoadCypherKey() != nil {
		log.Error("Failed to load the decryption key.")
		return
	}

	// GOMNIAUTH
	gomniauth.SetSecurityKey(signature.RandomKey(64))
	gomniauth.WithProviders(
		facebook.New("1497244403859030", "fbbb08c47e0441bcf23ea82b5f340fe5",
			baseURL+"/api/auth/facebook/callback/"),
	)

	// Attach the DB collection references to the context in order to pass it around
	goweb.MapBefore(func(ctx context.Context) error {
		var user = m.User{}
		cookieC, err := ctx.HttpRequest().Cookie("token")
		var cookie string
		if err != nil {
			cookie = ctx.FormValue("token")
			if cookie == "" {
				return nil
			}
		} else {
			cookie = cookieC.Value
		}
		err = m.GetDB("User").Find(bson.M{"token": cookie}).One(&user)
		if err != nil {
			// log.Info("MapBefore 2 " + err.Error())
			return nil
		}
		ctx.Data()["user"] = user
		return nil
	})

	goweb.MapStatic("/static", "../static")   // This is the directory with all static UI files
	goweb.MapStatic("/uploads", "../uploads") // This is the directory where we should store uploaded files

	// ENDPOINTS
	goweb.Map("GET", "/", endpoints.Root)
	goweb.Map("POST", "api/auth/local/register", endpoints.Register)
	goweb.Map("POST", "api/auth/local/login", endpoints.Login)
	goweb.Map("GET", "api/auth/{provider}/callback", endpoints.Callback)
	goweb.Map([]string{"GET", "POST"}, "api/auth/{provider}/{action}", endpoints.Connect)
	goweb.Map("POST", "api/upload/image", endpoints.UploadImage)
	goweb.Map("GET", "api/images/get", endpoints.GetImages)
	goweb.Map("POST", "api/upload/csv", endpoints.UploadTrail)
	goweb.Map("GET", "api/trails/get", endpoints.GetTrails)
	goweb.Map("POST", "api/upload/video", endpoints.UploadVideo)
	goweb.Map("GET", "api/videos/get", endpoints.GetVideos)
	goweb.Map("GET", "api/user", endpoints.GetUserInfo)
	goweb.Map("GET", "api/stats/get", endpoints.GetStats)
	goweb.Map("GET", "api/popLocations", endpoints.GetPopularLocations)
	goweb.Map("POST", "api/upload/imagetable", endpoints.UploadImageTable)
	goweb.Map("POST", "api/upload/zip", endpoints.UploadZip)
	// TODO: Add new endpoints here

	goweb.Map(endpoints.NotFound)

	// Remove the information from the data just in case the call is intercepted
	goweb.MapAfter(func(ctx context.Context) error {
		ctx.Data()["user"] = ""
		return nil
	})

	// setup the API responder
	codecService := services.NewWebCodecService()
	codecService.RemoveCodec("text/xml")
	apiResponder := responders.NewGowebAPIResponder(codecService, goweb.Respond)
	apiResponder.StandardFieldDataKey = "data"
	apiResponder.StandardFieldStatusKey = "status"
	apiResponder.StandardFieldErrorsKey = "errors"
	goweb.API = apiResponder

	// SERVER
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    5 * time.Minute,
		WriteTimeout:   5 * time.Minute,
		MaxHeaderBytes: 1 << 20,
	}
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)
	log.Info("Server port: " + Address)
	log.Info("Server running at: " + baseURL + "\n")
	if listenErr != nil {
		log.Error("Could not listen: " + listenErr.Error())
	}

	go func() {
		for _ = range c {
			// sig is a ^C, handle it
			// stop the HTTP server
			log.Info("Stopping the server...\n")
			listener.Close()
			log.Info("Server stopped.\n")
		}
	}()
	// begin the server
	log.Error("Error in Serve: " + s.Serve(listener).Error())
}
Example #27
0
func main() {
	// addrが格納されているアドレス
	var addr = flag.String("addr", ":8080", "アプリケーションのアドレス")
	// コマンドラインで渡された引数をセット
	flag.Parse()
	// Gomniauthのセットアップ
	securityKey := os.Getenv("GOMNIAUTH_SECURITY_KEY")
	gomniauth.SetSecurityKey(securityKey)

	oauthIDFacebook := os.Getenv("GOBLUEPRINTS_OAUTH_CLIENT_ID_FACEBOOK")
	oauthSecretFacebook := os.Getenv("GOBLUEPRINTS_OAUTH_CLIENT_SECRET_FACEBOOK")
	// oauthIdTwitter := os.Getenv("GOBLUEPRINTS_OAUTH_CLIENT_ID_TWITTER")
	// oauthSecretTwitter := os.Getenv("GOBLUEPRINTS_OAUTH_CLIENT_SECRET_TWITTER")
	oauthIDGithub := os.Getenv("GOBLUEPRINTS_OAUTH_CLIENT_ID_GITHUB")
	oauthSecretGithub := os.Getenv("GOBLUEPRINTS_OAUTH_CLIENT_SECRET_GITHUB")
	oauthIDGoogle := os.Getenv("GOBLUEPRINTS_OAUTH_CLIENT_ID_GOOGLE")
	oauthSecretGoogle := os.Getenv("GOBLUEPRINTS_OAUTH_CLIENT_SECRET_GOOGLE")

	gomniauth.WithProviders(
		facebook.New(oauthIDFacebook, oauthSecretFacebook, "http://localhost:8080/auth/callback/facebook"),
		// twitter.New(oauthIdTwitter, oauthSecretTwitter, "http://localhost:8080/auth/callback/twitter"),
		github.New(oauthIDGithub, oauthSecretGithub, "http://localhost:8080/auth/callback/github"),
		google.New(oauthIDGoogle, oauthSecretGoogle, "http://localhost:8080/auth/callback/google"),
	)

	// チャットルームが大量に作成されても、AuthAvatarのインスタンスは大量に作成されない
	r := newRoom()
	// room.goでr.tracerを使えるようにする
	r.tracer = trace.New(os.Stdout)
	// func Handle(pattern string, handler Handler)
	// TODO:ルーティングにはGoweb or Pat or Routes or mux等のパッケージを使用する
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)
	// MaxAgeでクッキーを削除する
	// MaxAgeが無効なブラウザのためにValueを空文字にする
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:   "auth",
			Value:  "",
			Path:   "/",
			MaxAge: -1,
		})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	})
	http.Handle("/upload", &templateHandler{filename: "upload.html"})
	http.HandleFunc("/uploader", uploaderHandler)
	// http.StripPrefixとhttp.FileServerは共にhttp.Handler型を返す
	http.Handle("/avatars/",
		http.StripPrefix("/avatars/",
			http.FileServer(http.Dir("./avatars"))))

	// 別スレッドでバックグラウンドで実行する
	// ※メインスレッドで実行される場合もある
	go r.run()
	log.Println("Webサーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #28
0
func main() {
	var configFileName string
	if len(os.Args) > 1 {
		configFileName = os.Args[1]
	} else {
		configFileName = os.Getenv(goimgshareConfigPathEnv)
	}

	if configFileName == "" {
		_, file := filepath.Split(os.Args[0])
		log.Printf("Syntax error. Must specify the configuration file either as ")
		log.Printf("environmental variable (%s) or as first command argument.", goimgshareConfigPathEnv)
		log.Fatalf("%s program exiting.", file)
		return
	}

	log.Printf("Opening %s", configFileName)

	file, err := os.Open(configFileName)
	if err != nil {
		panic(fmt.Sprintf("Cannot open configuration file: %s ", err))
	}
	defer file.Close()

	conf, err = config.Load(file)
	if err != nil {
		panic(fmt.Sprintf("Failed to load configuration file: %s ", err))
	}

	gomniauth.SetSecurityKey(signature.RandomKey(64))

	aDB = authdb.New()

	smallThumbCache = thumb.New(conf.ThumbnailCacheFolder, conf.SmallThumbnailSize, conf.SmallThumbnailSize)
	avgThumbCache = thumb.New(conf.ThumbnailCacheFolder, conf.AverageThumbnailSize, conf.AverageThumbnailSize)

	// load folders
	fmt.Printf("conf.SharedFoldersConfigurationFile == %s", conf.SharedFoldersConfigurationFile)
	file, err = os.Open(conf.SharedFoldersConfigurationFile)
	if err != nil {
		panic(fmt.Sprintf("Cannot open shared folder configuration file: %s ", err))
	}
	defer file.Close()
	phyFolders, err = physical.Load(file)
	if err != nil {
		panic(err)
	}
	// end load folders

	var prov []common.Provider
	var providers []string

	if conf.Google != nil {
		providers = append(providers, "google")
		prov = append(prov, google.New(conf.Google.ClientID, conf.Google.Secret, conf.Google.ReturnURL))
	}
	if conf.Facebook != nil {
		providers = append(providers, "facebook")
		prov = append(prov, facebook.New(conf.Facebook.ClientID, conf.Facebook.Secret, conf.Facebook.ReturnURL))
	}
	if conf.Github != nil {
		providers = append(providers, "github")
		prov = append(prov, github.New(conf.Github.ClientID, conf.Github.Secret, conf.Github.ReturnURL))
	}

	gomniauth.WithProviders(prov...)

	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", logHandler(requireAuth(handleStatic(staticDirectoryAuth, "index.html"))))
	router.HandleFunc("/folders", logHandler(requireAuth(handleFolders)))

	// images
	rImages := regexp.MustCompile("(.*[.]jpg$)|(.*[.]gif$)|(.*[.]png$)")
	router.HandleFunc("/images/{folderid}", logHandler(requireAuth(handleFolder(
		func(strtomatch string) bool {
			return rImages.MatchString(strings.ToLower(strtomatch))
		}))))

	//videos
	rVideos := regexp.MustCompile("(.*[.]mp4$)|(.*[.]mkv$)|(.*[.]avi$)")
	router.HandleFunc("/videos/{folderid}", logHandler(requireAuth(handleFolder(
		func(strtomatch string) bool {
			return rVideos.MatchString(strings.ToLower(strtomatch))
		}))))

	// everyting else
	router.HandleFunc("/extra/{folderid}", logHandler(requireAuth(handleFolder(
		func(strtomatch string) bool {
			return !(rVideos.MatchString(strings.ToLower(strtomatch)) || rImages.MatchString(strings.ToLower(strtomatch)))
		}))))

	// serve the files
	router.HandleFunc("/file/{folderid}/{fn}", logHandler(requireAuth(handleStaticFile)))

	// handle thumbnails
	router.HandleFunc("/smallthumb/{folderid}/{fn}", logHandler(requireAuth(handleThumbnail)))
	router.HandleFunc("/avgthumb/{folderid}/{fn}", logHandler(requireAuth(handleThumbnail)))

	// register all the static content with NO authentication
	files, err := ioutil.ReadDir(filepath.Join(conf.InternalHTTPFilesPath, staticDirectory, staticDirectoryNoAuth))
	if err != nil {
		panic(fmt.Sprintf("Cannot access static content folder: %s", err))
	}

	for _, file := range files {
		path := path.Join("/", staticDirectory, file.Name())
		log.Printf("Registering %s with noauth", path)

		if conf.LogInternalHTTPFilesAccess {
			router.HandleFunc(path, logHandler(handleStatic(staticDirectoryNoAuth, file.Name())))
		} else {
			router.HandleFunc(path, handleStatic(staticDirectoryNoAuth, file.Name()))
		}
	}

	// register all the static content with authentication
	files, err = ioutil.ReadDir(filepath.Join(conf.InternalHTTPFilesPath, staticDirectory, staticDirectoryAuth))
	if err != nil {
		panic(fmt.Sprintf("Cannot access static content folder: %s", err))
	}

	for _, file := range files {
		path := path.Join("/", staticDirectory, file.Name())
		log.Printf("Registering %s with auth", path)

		if conf.LogInternalHTTPFilesAccess {
			router.HandleFunc(path, logHandler(requireAuth(handleStatic(staticDirectoryAuth, file.Name()))))
		} else {
			router.HandleFunc(path, requireAuth(handleStatic(staticDirectoryAuth, file.Name())))
		}
	}

	http.HandleFunc("/", logHandler(requireAuth(handleStatic(staticDirectoryAuth, "index.html"))))

	for _, provider := range providers {
		router.HandleFunc(fmt.Sprintf("/auth/%s/login", provider), loginHandler(provider))
		router.HandleFunc(fmt.Sprintf("/auth/%s/callback", provider), callbackHandler(provider))
	}

	router.HandleFunc("/supportedAuths", logHandler(handleSupportedAuths))

	if conf.HTTPSCertificateFile != "" && conf.HTTPSCertificateKeyFile != "" {
		log.Printf("Starting encrypted TLS webserver on port %d...", conf.Port)
		if err := http.ListenAndServeTLS(fmt.Sprintf(":%d", conf.Port), conf.HTTPSCertificateFile, conf.HTTPSCertificateKeyFile, router); err != nil {
			log.Fatalf("ERROR starting webserver: %s", err)
		}
	} else {
		log.Printf("Starting non encrypted webserver on port %d...", conf.Port)
		if err := http.ListenAndServe(fmt.Sprintf(":%d", conf.Port), router); err != nil {
			log.Fatalf("ERROR starting webserver: %s", err)
		}
	}

	//	http.ListenAndServeTLS()
}