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) } }
// Initialize collects server-side credential from environment variables and prepare for authentication with Github OAuth. // // Client authentication is disabled and CurrentUser always returns "anonymous" if any of the environment variables are missing. func Initialize(anynomous User, cookieSecret []byte) { store = sessions.NewCookieStore(cookieSecret) githubCallbackBase = os.Getenv("GITHUB_CALLBACK_URL") cred := struct { githubRandomHashKey string githubOmniauthID string githubOmniauthKey string }{ os.Getenv("GITHUB_RANDOM_HASH_KEY"), os.Getenv("GITHUB_OMNI_AUTH_ID"), os.Getenv("GITHUB_OMNI_AUTH_KEY"), } defaultUser = anynomous if cred.githubRandomHashKey == "" || cred.githubOmniauthID == "" || cred.githubOmniauthKey == "" || githubCallbackBase == "" { glog.Warningf( "Missing one or more Gomniauth Environment Variables: Running with with limited functionality! \n GITHUB_RANDOM_HASH_KEY [%s] \n GITHUB_OMNI_AUTH_ID [%s] \n GITHUB_OMNI_AUTH_KEY [%s] \n GITHUB_CALLBACK_URL [%s]", cred.githubRandomHashKey, cred.githubOmniauthID, cred.githubOmniauthKey, githubCallbackBase, ) enabled = false return } url := fmt.Sprintf("%s/auth/github/callback", githubCallbackBase) gomniauth.SetSecurityKey(cred.githubRandomHashKey) gomniauth.WithProviders( githubOauth.New(cred.githubOmniauthID, cred.githubOmniauthKey, url), ) glog.Infof("Enabled authentication by github OAuth2") enabled = true }
func main() { addr := flag.String("addr", ":8080", "address") flag.Parse() gomniauth.SetSecurityKey("key") gomniauth.WithProviders( github.New("clientid", "secretkey", "http://localhost:8080/auth/callback/github"), ) http.HandleFunc("/1/0", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hoge")) }) http.Handle("/1/1", &templateHandler{filename: "chat.html"}) http.Handle("/2/1", MustAuth(&templateHandler{filename: "chat.html"})) http.Handle("/login", &templateHandler{filename: "login.html"}) http.HandleFunc("/auth", loginHandler) r := newRoom() r.tracer = trace.New(os.Stdout) http.Handle("/1/2", r) go r.run() 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.") // 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) } }
// Initialize collects server-side credential from environment variables and prepare for authentication with Github OAuth. // // Client authentication is disabled and CurrentUser always returns "anonymous" if any of the environment variables are missing. func Initialize(anynomous User, cookieSecret []byte) { store = sessions.NewCookieStore(cookieSecret) githubCallbackURL = os.Getenv("GITHUB_CALLBACK_URL") cred := struct { githubRandomHashKey string githubOmniauthID string githubOmniauthKey string }{ os.Getenv("GITHUB_RANDOM_HASH_KEY"), os.Getenv("GITHUB_OMNI_AUTH_ID"), os.Getenv("GITHUB_OMNI_AUTH_KEY"), } defaultUser = anynomous if cred.githubRandomHashKey == "" || cred.githubOmniauthID == "" || cred.githubOmniauthKey == "" || githubCallbackURL == "" { log.Printf( "Missing one or more Gomniauth Environment Variables: Running with with limited functionality! \n githubRandomHashKey [%s] \n githubOmniauthID [%s] \n githubOmniauthKey[%s] \n githubCallbackURL[%s]", cred.githubRandomHashKey, cred.githubOmniauthID, cred.githubOmniauthKey, githubCallbackURL, ) enabled = false return } githubCallbackURL = path.Join(githubCallbackURL, "/auth/github/callback") gomniauth.SetSecurityKey(cred.githubRandomHashKey) gomniauth.WithProviders( githubOauth.New(cred.githubOmniauthID, cred.githubOmniauthKey, githubCallbackURL), ) enabled = true }
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) } }
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) } }
func main() { var addr = flag.String("addr", ":8080", "The addr of the application.") flag.Parse() gomniauth.SetSecurityKey(os.Getenv("GOCHAT_SEC_KEY")) gomniauth.WithProviders( soundcloud.New(os.Getenv("ENV_SC_CLIENT_ID"), os.Getenv("ENV_SC_SECRET"), os.Getenv("ENV_SC_CALLBACK_URL")), github.New(os.Getenv("ENV_GH_CLIENT_ID"), os.Getenv("ENV_GH_SECRET"), os.Getenv("ENV_GH_CALLBACK_URL")), ) r := newRoom(UseGravatar) r.tracer = trace.New(os.Stdout) http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"})) http.Handle("/login", &templateHandler{filename: "login.html"}) http.HandleFunc("/logout", logoutHandler) http.HandleFunc("/auth/", loginHandler) http.Handle("/room", r) 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() log.Println("Starting web server on ", *addr) if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal("ListenAndServe:", err) } }
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) } }
// Authenticate with Github. If env data is missing turn Auth off. func getAuth() auth { a := auth{} a.githubRandomHashKey = os.Getenv("GITHUB_RANDOM_HASH_KEY") a.githubOmniauthID = os.Getenv("GITHUB_OMNI_AUTH_ID") a.githubOmniauthKey = os.Getenv("GITHUB_OMNI_AUTH_KEY") a.githubCallbackURL = os.Getenv("GITHUB_CALLBACK_URL") // Let user know if a key is missing and that auth is disabled. if a.githubRandomHashKey == "" || a.githubOmniauthID == "" || a.githubOmniauthKey == "" || a.githubCallbackURL == "" { log.Printf("Missing one or more Gomniauth Environment Variables: Running with with limited functionality! \n githubRandomHashKey [%s] \n githubOmniauthID [%s] \n githubOmniauthKey[%s] \n githubCallbackURL[%s]", a.githubRandomHashKey, a.githubOmniauthID, a.githubOmniauthKey, a.githubCallbackURL) a.authorization = false return a } gomniauth.SetSecurityKey(a.githubRandomHashKey) gomniauth.WithProviders( githubOauth.New(a.githubOmniauthID, a.githubOmniauthKey, a.githubCallbackURL+"/auth/github/callback"), ) a.authorization = true return a }
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) } }
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) } }
func main() { secretKey := "kyokomi-secret" gomniauth.SetSecurityKey(secretKey) gomniauth.WithProviders( github.New(githubClientID, githubSecretKey, githubRedirectURL), google.New(googleClientID, googleSecretKey, googleRedirectURL), ) kami.Get("/", indexHandler) kami.Get("/auth/login/:provider", loginHandler) kami.Get("/auth/callback/:provider", callbackHandler) kami.Serve() }
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) } }
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) } }
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) } }
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) } }
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) } }
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) }
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) } }
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) } }
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) } }
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) } }
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) } }
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) } }
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) } }
func (c *Configuration) StartAuth() { clientSecret := c.Json.ClientSecret if !c.Json.RunLocalMode { if os.Getenv("CRASHMAT_CLIENTSECRET") != "" { log.Println("Using environmental for CRASHMAT_CLIENTSECRET") clientSecret = os.Getenv("CRASHMAT_CLIENTSECRET") } } clientId := c.Json.ClientId if !c.Json.RunLocalMode { if os.Getenv("CRASHMAT_CLIENTID") != "" { log.Println("Using environmental for CRASHMAT_CLIENTID") clientId = os.Getenv("CRASHMAT_CLIENTID") } } gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders(github.New(clientId, clientSecret, c.Json.GithubAuthCallback)) }
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) } }
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() }
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) } }