Example #1
0
func main() {
	flag.Parse()

	err := godotenv.Load(fmt.Sprintf("config/%s.env", *env))
	if err != nil {
		log.Fatal(err)
		return
	}

	goth.UseProviders(
		github.New(os.Getenv("GITHUB_CLIENT_KEY"), os.Getenv("GITHUB_SECRET"), os.Getenv("GITHUB_CALLBACK")),
	)

	p := pat.New()

	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	p.Add("GET", "/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	p.Add("GET", "/login", &templateHandler{filename: "login.html"})
	p.Get("/auth/{action}/{provider}", loginHandler)
	p.Add("GET", "/room", r)

	// チャットルームの開始
	go r.run()
	// Webサーバの起動
	log.Println("Webサーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, p); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #2
0
func init() {
	gothic.Store = sessions.NewFilesystemStore(os.TempDir(), []byte("goth-example"))
	goth.UseProviders(
		twitter.New(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),
		// If you'd like to use authenticate instead of authorize in Twitter provider, use this instead.
		// twitter.NewAuthenticate(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),

		facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), "http://localhost:3000/auth/facebook/callback"),
		gplus.New("281140391713-b1dskle4dtsi6nn4ce01tbkpcp3aovs6.apps.googleusercontent.com", "cIM92vsFvLyfhIZASmAo2ZaE", "http://localhost:8080/auth/gplus/callback"),
		github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:3000/auth/github/callback"),
		spotify.New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "http://localhost:3000/auth/spotify/callback"),
		linkedin.New(os.Getenv("LINKEDIN_KEY"), os.Getenv("LINKEDIN_SECRET"), "http://localhost:3000/auth/linkedin/callback"),
		lastfm.New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), "http://localhost:3000/auth/lastfm/callback"),
		twitch.New(os.Getenv("TWITCH_KEY"), os.Getenv("TWITCH_SECRET"), "http://localhost:3000/auth/twitch/callback"),
		dropbox.New(os.Getenv("DROPBOX_KEY"), os.Getenv("DROPBOX_SECRET"), "http://localhost:3000/auth/dropbox/callback"),
		digitalocean.New(os.Getenv("DIGITALOCEAN_KEY"), os.Getenv("DIGITALOCEAN_SECRET"), "http://localhost:3000/auth/digitalocean/callback", "read"),
		bitbucket.New(os.Getenv("BITBUCKET_KEY"), os.Getenv("BITBUCKET_SECRET"), "http://localhost:3000/auth/bitbucket/callback"),
		instagram.New(os.Getenv("INSTAGRAM_KEY"), os.Getenv("INSTAGRAM_SECRET"), "http://localhost:3000/auth/instagram/callback"),
		box.New(os.Getenv("BOX_KEY"), os.Getenv("BOX_SECRET"), "http://localhost:3000/auth/box/callback"),
		salesforce.New(os.Getenv("SALESFORCE_KEY"), os.Getenv("SALESFORCE_SECRET"), "http://localhost:3000/auth/salesforce/callback"),
		amazon.New(os.Getenv("AMAZON_KEY"), os.Getenv("AMAZON_SECRET"), "http://localhost:3000/auth/amazon/callback"),
		yammer.New(os.Getenv("YAMMER_KEY"), os.Getenv("YAMMER_SECRET"), "http://localhost:3000/auth/yammer/callback"),
		onedrive.New(os.Getenv("ONEDRIVE_KEY"), os.Getenv("ONEDRIVE_SECRET"), "http://localhost:3000/auth/onedrive/callback"),
	)

	//set a global session
	globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "sessionIDHashFunc": "sha1", "sessionIDHashKey": "", "cookieLifeTime": 3600, "providerConfig": ""}`)
	go globalSessions.GC()
}
Example #3
0
func init() {
	goth.UseProviders(
		twitter.New(os.Getenv("TWITTER_KEY"),
			os.Getenv("TWITTER_SECRET"),
			"http://localhost:8080/auth/twitter/callback?provider=twitter"),
	)
}
Example #4
0
func Service() helios.ServiceHandler {
	return func(h *helios.Engine) {
		g := &GithubService{
			Users:        make(map[string]User),
			EventChan:    h.NewBroadcastChannel("github", true),
			githubKey:    h.Config.GetString("github.apiKey"),
			githubSecret: h.Config.GetString("github.apiSecret"),
		}

		// Set the initial last event time to now
		g.LastEvent.EventTime = time.Now()

		// Setup Goth Authentication
		goth.UseProviders(
			githubProvider.New(g.githubKey, g.githubSecret, fmt.Sprintf("http://%s:%s/auth/github/callback", h.Config.GetString("host"), h.Config.GetString("port")), "repo", "user:email"),
		)

		// Setup github auth routes
		h.HTTPEngine.GET("/auth/github/callback", providerCallback(h, g))
		h.HTTPEngine.GET("/auth/github", providerAuth)

		// Load registered users
		err := loadUsersCSV(g)
		if err != nil {
			h.Error("Failed to load users from csv", "error", err.Error())
		}

		// Start Existing Users
		h.Debug("Starting existing github user go routines")
		startExistingUsers(g)
	}
}
Example #5
0
func main() {

	workingDirectory, err := os.Getwd()

	if err != nil {
		fmt.Println("working directory error")
		return
	}

	gothic.GetProviderName = func(req *http.Request) (string, error) {
		return "amazon", nil
	}

	goth.UseProviders(
		amazon.New(os.Getenv("AMAZON_KEY"), os.Getenv("AMAZON_SECRET"), "https://ecloud.nimbostrati.com:9898/auth/amazon/callback", "profile"),
	)

	router.HandleFunc("/", makeIndexPageHandler(workingDirectory+"/app/splash.html"))
	router.HandleFunc("/auth/amazon/callback", callbackPageHandler)
	router.HandleFunc("/auth/amazon", startAuthHandler)

	ServeStatic(router, workingDirectory)

	http.Handle("/", router)

	fmt.Println("About to listen and serve from(", workingDirectory, ").")
	http.ListenAndServeTLS(":9898", os.Getenv("GOTH_SSL_CERT"), os.Getenv("GOTH_SSL_KEY"), nil)
}
Example #6
0
func Test_UseProviders(t *testing.T) {
	a := assert.New(t)

	provider := &faux.Provider{}
	goth.UseProviders(provider)
	a.Equal(len(goth.GetProviders()), 1)
	a.Equal(goth.GetProviders()[provider.Name()], provider)
	goth.ClearProviders()
}
Example #7
0
func (s *Server) InitGothic() {
	goth.UseProviders(
		facebook.New(s.Config.Facebook.AppId, s.Config.Facebook.Secret, s.Config.Facebook.CallbackURL),
	)
	// Since we are using only ONE provider, FACEBOOK - it doesn't have make sense to parse url for provider name
	gothic.GetProviderName = func(req *http.Request) (string, error) {
		return "facebook", nil
	}
}
Example #8
0
File: gin.go Project: oov/gothic
func main() {
	const BaseURL = "http://localhost:8000"
	goth.UseProviders(
		twitter.New(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), BaseURL+"/auth/twitter/callback"),
		facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), BaseURL+"/auth/facebook/callback"),
		gplus.New(os.Getenv("GPLUS_KEY"), os.Getenv("GPLUS_SECRET"), BaseURL+"/auth/gplus/callback"),
		github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), BaseURL+"/auth/github/callback"),
		spotify.New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), BaseURL+"/auth/spotify/callback"),
		linkedin.New(os.Getenv("LINKEDIN_KEY"), os.Getenv("LINKEDIN_SECRET"), BaseURL+"/auth/linkedin/callback"),
		lastfm.New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), BaseURL+"/auth/lastfm/callback"),
		twitch.New(os.Getenv("TWITCH_KEY"), os.Getenv("TWITCH_SECRET"), BaseURL+"/auth/twitch/callback"),
	)

	tpl := template.New("")
	template.Must(tpl.New("index.html").Parse(`
<p><a href="/auth/twitter">Log in with Twitter</a></p>
<p><a href="/auth/facebook">Log in with Facebook</a></p>
<p><a href="/auth/gplus">Log in with GPlus</a></p>
<p><a href="/auth/github">Log in with Github</a></p>
<p><a href="/auth/spotify">Log in with Spotify</a></p>
<p><a href="/auth/lastfm">Log in with LastFM</a></p>
<p><a href="/auth/twitch">Log in with Twitch</a></p>
`))
	template.Must(tpl.New("user.html").Parse(`
<p>Name: {{.Name}}</p>
<p>Email: {{.Email}}</p>
<p>NickName: {{.NickName}}</p>
<p>Location: {{.Location}}</p>
<p>AvatarURL: {{.AvatarURL}} <img src="{{.AvatarURL}}"></p>
<p>Description: {{.Description}}</p>
<p>UserID: {{.UserID}}</p>
<p>AccessToken: {{.AccessToken}}</p>
`))

	r := gin.Default()
	r.SetHTMLTemplate(tpl)
	r.GET("/auth/:provider", func(c *gin.Context) {
		err := gothic.BeginAuth(c.Param("provider"), c.Writer, c.Request)
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
	})
	r.GET("/auth/:provider/callback", func(c *gin.Context) {
		user, err := gothic.CompleteAuth(c.Param("provider"), c.Writer, c.Request)
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		c.HTML(http.StatusOK, "user.html", user)
	})
	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})
	log.Fatal(r.Run(":8000"))
}
Example #9
0
// Init initializes the API, setting up the OAuth providers whose required
// information is contained within the given config.
func Init(config *config.Config) {
	apiConfig = config
	indexTemplate = template.Must(template.ParseFiles(apiConfig.Website.Directory + "index.html"))
	rest.ErrorFieldName = "error"
	goth.UseProviders(
		gplus.New(config.Google.ClientID, config.Google.ClientSecret, config.Google.CallbackURL),
		// facebook.New(config.Facebook.ClientID, config.Facebook.ClientSecret, config.Facebook.CallbackURL),
		// twitter.New(config.Twitter.ClientID, config.Twitter.ClientSecret, config.Twitter.CallbackURL),
	)
}
Example #10
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	beego.SetLogFuncCall(true)
	beego.SessionOn = true
	goth.UseProviders(
		gplus.New(
			beego.AppConfig.String("CLIENT_ID"),
			beego.AppConfig.String("CLIENT_SECRET"),
			beego.AppConfig.String("CLIENT_CALLBACK"),
		),
	)
	SessionTimeout, err := beego.AppConfig.Int("SESSION_TIMEOUT")
	if err != nil {
		beego.Critical(err)
	}
	SessionRefreshInterval, err := beego.AppConfig.Int("SESSION_REFRESH_INTERVAL")
	if err != nil {
		beego.Critical(err)
	}
	goJwt.Conf = goJwt.JwtConf{
		PrivateKeyFile:         beego.AppConfig.String("PrivateKeyFile"),
		PublicKeyFile:          beego.AppConfig.String("PublicKeyFile"),
		Algorithm:              beego.AppConfig.String("Algorithm"),
		SessionSecret:          beego.AppConfig.String("SESSION_SECRET"),
		SessionName:            beego.AppConfig.String("SESSION_NAME"),
		SessionTimeout:         SessionTimeout,
		SessionRefreshInterval: SessionRefreshInterval,
	}
	goJwt.Configure()
	goJwt.Store = sessions.NewCookieStore([]byte(beego.AppConfig.String("SESSION_SECRET")))

	ldapPort, err := beego.AppConfig.Int("Ldap_port")
	if err != nil {
		beego.Critical(err)
	}
	tim.Conf = tim.LdapConf{
		Ldap_server: beego.AppConfig.String("Ldap_server"),
		Ldap_port:   uint16(ldapPort),
		Base_dn:     beego.AppConfig.String("Base_dn"),
		Ldap_user:   beego.AppConfig.String("Ldap_user"),
		Ldap_pass:   beego.AppConfig.String("Ldap_pass"),
	}

	beego.SetStaticPath("/public", "static")

	if err != nil {
		beego.Critical("Cannot connect to Redis: ", err)
		return
	}

	beego.Run()
}
Example #11
0
func main() {
	goth.UseProviders(gplus.New(gPlusClientID, gPlusClientSecret, "http://localhost:8080/auth/gplus/callback"))

	mainRouter := http.NewServeMux()
	mainRouter.HandleFunc("/", logInHandler)
	mainRouter.HandleFunc("/auth/gplus", beginAuthHandler)
	mainRouter.HandleFunc("/auth/gplus/callback", callbackHandler)
	mainRouter.HandleFunc("/hello", helloHandler)
	fmt.Println("Serving http://localhost" + port)
	if err := http.ListenAndServe(port, mainRouter); err != nil {
		panic(err)
	}
}
Example #12
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	googleJsonKey, err := ioutil.ReadFile(GOOGLE_CLIENT_SECRET_FILE_PATH)
	if err != nil {
		log.Fatalln("unable to read file ", GOOGLE_CLIENT_SECRET_FILE_PATH,
			":", err)
	}
	facebookJsonKey, err := ioutil.ReadFile(FACEBOOK_CLIENT_SECRET_FILE_PATH)
	if err != nil {
		log.Fatalln("unable to read file ", FACEBOOK_CLIENT_SECRET_FILE_PATH,
			":", err)
	}

	// do I need more scopes?
	// https://developers.google.com/+/domains/authentication/scopes
	googleConfig, err := google.ConfigFromJSON(googleJsonKey)
	if err != nil {
		log.Fatalln("unable to get google provider config:", err)
	}
	facebookConfig := &genericConfig{}
	err = json.Unmarshal(facebookJsonKey, facebookConfig)
	if err != nil {
		log.Fatalln("unable to get facebook provider config:", err)
	}

	//I need "profile", "email", scopes. gplus and facebook provide these by
	//default.
	goth.UseProviders(
		gplus.New(googleConfig.ClientID, googleConfig.ClientSecret,
			AUTH_CALLBACK_URL),
		facebook.New(facebookConfig.Client_id, facebookConfig.Client_secret, AUTH_CALLBACK_URL),
	)

	chat = NewChat()
	router = pat.New()

	router.Get("/ws", WsHandler)
	router.Get("/oauth2callback", AuthCallbackHandler)
	router.Get("/auth/{provider}", BeginAuthHandler)
	router.Get("/", AuthChoiceHandler)
	// router.Add("GET", "/app", http.FileServer(http.Dir("app/")))
	// router.PathPrefix("/app").Handler(http.FileServer(http.Dir("app/")))
	http.Handle("/", router)
	http.Handle("/app/", http.StripPrefix("/app/",
		http.FileServer(http.Dir("app/"))))

	go http.ListenAndServeTLS(":8080", "cert.crt", "key.key", nil)
	http.ListenAndServe(":8000", http.HandlerFunc(redirectHandler))
}
Example #13
0
func Test_GetProvider(t *testing.T) {
	a := assert.New(t)

	provider := &faux.Provider{}
	goth.UseProviders(provider)

	p, err := goth.GetProvider(provider.Name())
	a.NoError(err)
	a.Equal(p, provider)

	p, err = goth.GetProvider("unknown")
	a.Error(err)
	a.Equal(err.Error(), "no provider for unknown exists")
	goth.ClearProviders()
}
Example #14
0
// PostPopulate sets up the oauth provider
func (s *authService) PostPopulate() error {
	goth.UseProviders(gplus.New(
		s.Config.GoogleKey,
		s.Config.GoogleSecret,
		s.Config.CallbackUrl,
	))

	var err error
	s.provider, err = goth.GetProvider("gplus")
	if err != nil {
		log.Error(fmt.Sprintf("Could not get gplus provider: %v", err))
		return err
	}

	return nil
}
Example #15
0
func Start(port, templatesDir string, publicDir string) error {
	dbmap = setupDb()
	defer dbmap.Db.Close()

	// Process our templates
	TemplatesDir = templatesDir
	var err error
	Templates, err = tmpl.ParseDir(TemplatesDir)
	if err != nil {
		logging.ErrorWithTags([]string{"templates"}, "Failed to parse templates", err.Error())
		return err
	}

	// Setup Goth Authentication
	goth.UseProviders(
		github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:3000/auth/github/callback", "repo", "user:email"),
	)

	// Setup Socket.io server and related activity fetching
	socketServer, err := SetupSocketIO()
	if err != nil {
		return err
	}

	err = StartSocketPusher(socketServer, activityChan)
	if err != nil {
		return err
	}

	err = StartExistingUsers(activityChan)
	if err != nil {
		return err
	}

	// Start up gin and its friends
	r := gin.Default()
	r.Use(cors.Middleware(cors.Options{AllowCredentials: true}))

	// Serve static assets
	r.Use(static.Serve("/", static.LocalFile(publicDir, false)))

	SetupRoutes(r, socketServer)
	r.Run(fmt.Sprintf(":%s", port))

	return nil
}
Example #16
0
func main() {
	goth.UseProviders(
		twitter.New(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),
		// If you'd like to use authenticate instead of authorize in Twitter provider, use this instead.
		// twitter.NewAuthenticate(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),

		facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), "http://localhost:3000/auth/facebook/callback"),
		gplus.New(os.Getenv("GPLUS_KEY"), os.Getenv("GPLUS_SECRET"), "http://localhost:3000/auth/gplus/callback"),
		github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:3000/auth/github/callback"),
		spotify.New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "http://localhost:3000/auth/spotify/callback"),
		linkedin.New(os.Getenv("LINKEDIN_KEY"), os.Getenv("LINKEDIN_SECRET"), "http://localhost:3000/auth/linkedin/callback"),
		lastfm.New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), "http://localhost:3000/auth/lastfm/callback"),
		twitch.New(os.Getenv("TWITCH_KEY"), os.Getenv("TWITCH_SECRET"), "http://localhost:3000/auth/twitch/callback"),
		dropbox.New(os.Getenv("DROPBOX_KEY"), os.Getenv("DROPBOX_SECRET"), "http://localhost:3000/auth/dropbox/callback"),
	)

	// Assign the GetState function variable so we can return the
	// state string we want to get back at the end of the oauth process.
	// Only works with facebook and gplus providers.
	gothic.GetState = func(req *http.Request) string {
		// Get the state string from the query parameters.
		return req.URL.Query().Get("state")
	}

	p := pat.New()
	p.Get("/auth/{provider}/callback", func(res http.ResponseWriter, req *http.Request) {

		// print our state string to the console
		fmt.Println(gothic.GetState(req))

		user, err := gothic.CompleteUserAuth(res, req)
		if err != nil {
			fmt.Fprintln(res, err)
			return
		}
		t, _ := template.New("foo").Parse(userTemplate)
		t.Execute(res, user)
	})

	p.Get("/auth/{provider}", gothic.BeginAuthHandler)
	p.Get("/", func(res http.ResponseWriter, req *http.Request) {
		t, _ := template.New("foo").Parse(indexTemplate)
		t.Execute(res, nil)
	})
	http.ListenAndServe(":3000", p)
}
Example #17
0
func Register(r *mux.Router) {
	goth.UseProviders(
		gplus.New(os.Getenv("GOOGLE_CLIENT_ID"), os.Getenv("GOOGLE_CLIENT_SECRET"), "http://localhost:8080/auth/gplus/callback"),
	)

	gothic.GetProviderName = func(request *http.Request) (string, error) {
		return "gplus", nil
	}

	gothic.Store = Store

	gothic.GetState = func(request *http.Request) string {
		return request.URL.Query().Get("state")
	}

	r.HandleFunc("/gplus/callback", CallbackHandler).Methods("GET")
	r.HandleFunc("/gplus", gothic.BeginAuthHandler).Methods("GET")
}
Example #18
0
func main() {
	goth.UseProviders(
		twitter.New(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),
		// If you'd like to use authenticate instead of authorize in Twitter provider, use this instead.
		// twitter.NewAuthenticate(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),

		facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), "http://localhost:3000/auth/facebook/callback"),
		gplus.New(os.Getenv("GPLUS_KEY"), os.Getenv("GPLUS_SECRET"), "http://localhost:3000/auth/gplus/callback"),
		github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:3000/auth/github/callback"),
		spotify.New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "http://localhost:3000/auth/spotify/callback"),
		linkedin.New(os.Getenv("LINKEDIN_KEY"), os.Getenv("LINKEDIN_SECRET"), "http://localhost:3000/auth/linkedin/callback"),
		lastfm.New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), "http://localhost:3000/auth/lastfm/callback"),
		twitch.New(os.Getenv("TWITCH_KEY"), os.Getenv("TWITCH_SECRET"), "http://localhost:3000/auth/twitch/callback"),
		dropbox.New(os.Getenv("DROPBOX_KEY"), os.Getenv("DROPBOX_SECRET"), "http://localhost:3000/auth/dropbox/callback"),
		digitalocean.New(os.Getenv("DIGITALOCEAN_KEY"), os.Getenv("DIGITALOCEAN_SECRET"), "http://localhost:3000/auth/digitalocean/callback", "read"),
		bitbucket.New(os.Getenv("BITBUCKET_KEY"), os.Getenv("BITBUCKET_SECRET"), "http://localhost:3000/auth/bitbucket/callback"),
		instagram.New(os.Getenv("INSTAGRAM_KEY"), os.Getenv("INSTAGRAM_SECRET"), "http://localhost:3000/auth/instagram/callback"),
	)

	p := pat.New()
	p.Get("/auth/{provider}/callback", func(res http.ResponseWriter, req *http.Request) {

		// print our state string to the console. Ideally, you should verify
		// that it's the same string as the one you set in `setState`
		fmt.Println("State: ", gothic.GetState(req))

		user, err := gothic.CompleteUserAuth(res, req)
		if err != nil {
			fmt.Fprintln(res, err)
			return
		}
		t, _ := template.New("foo").Parse(userTemplate)
		t.Execute(res, user)
	})

	p.Get("/auth/{provider}", gothic.BeginAuthHandler)
	p.Get("/", func(res http.ResponseWriter, req *http.Request) {
		t, _ := template.New("foo").Parse(indexTemplate)
		t.Execute(res, nil)
	})
	http.ListenAndServe(":3000", p)
}
Example #19
0
func init() {
	goth.UseProviders(
		gplus.New(os.Getenv("GOOGLE_CLIENT_ID"), os.Getenv("GOOGLE_CLIENT_SECRET"), os.Getenv("BASE")+"/login/gplus/callback", "email"),
		github.New(os.Getenv("GITHUB_CLIENT_ID"), os.Getenv("GITHUB_CLIENT_SECRET"), os.Getenv("BASE")+"/login/github/callback", "user:email"),
	)

	gothic.Store = store

	gothic.GetState = func(r *http.Request) string {
		return r.URL.Query().Get("state")
	}
	gothic.GetProviderName = func(r *http.Request) (string, error) {
		provider, _ := mux.Vars(r)["provider"]
		return provider, nil
	}

	Router.NewRoute().
		Methods("GET").
		Path("/").
		HandlerFunc(ServeIndex)
	Router.NewRoute().
		Methods("GET").
		Path("/login").
		HandlerFunc(ServeLogin)
	Router.NewRoute().
		Methods("GET").
		Path("/logout").
		HandlerFunc(HandleLogout)
	Router.NewRoute().
		Methods("GET").
		Path("/login/{provider}").
		HandlerFunc(gothic.BeginAuthHandler)
	Router.NewRoute().
		Methods("GET").
		Path("/login/{provider}/callback").
		HandlerFunc(HandleAuthCallback)
	Router.NewRoute().
		Methods("GET").
		Path("/d/{id}").
		HandlerFunc(ServeDocumentPage)

}
Example #20
0
func main() {
	//Register OAuth2 providers with Goth
	goth.UseProviders(
		twitter.New(config.TwitterKey, config.TwitterSecret, "http://localhost:8080/auth/twitter/callback"),
		facebook.New(config.FacebookKey, config.FacebookSecret, "http://localhost:8080/auth/facebook/callback"),
	)
	//Routing using Pat package
	r := pat.New()
	r.Get("/auth/{provider}/callback", callbackAuthHandler)
	r.Get("/auth/{provider}", gothic.BeginAuthHandler)
	r.Get("/", indexHandler)

	server := &http.Server{
		Addr:    ":8080",
		Handler: r,
	}
	log.Println("Listening...")
	server.ListenAndServe()

}
Example #21
0
func init() {
	util.Configure()
	util.ConfigureLogger()

	var (
		githubKey         = viper.GetString("AUTH_CLIENT_ID")
		githubSecret      = viper.GetString("AUTH_CLIENT_SECRET")
		githubPermissions = []string{"user:email", "repo", "admin:repo_hook", "admin:org_hook", "admin:org"}
		stateTime         = time.Now().UnixNano()
		hash              = strconv.Itoa(int(stateTime))
		err               error
	)

	goth.UseProviders(github.New(githubKey, githubSecret, "", githubPermissions[0], githubPermissions[1], githubPermissions[2], githubPermissions[3], githubPermissions[4]))

	generateFromPassword(err, hash)
	setState()

	gothic.Store = sessions.NewFilesystemStore(os.TempDir(), state_hash)
	getProviderName()
}
Example #22
0
func main() {
	log.SetPrefix("doit-server: ")
	var s Specification
	err := envconfig.Process("doit", &s)
	if err != nil {
		log.Fatal(err.Error())
	}

	port := os.Getenv("PORT")
	if port == "" {
		log.Fatal("environment variable PORT required")
	}

	if os.Getenv("SESSION_SECRET") == "" {
		log.Fatal("environment variable SESSION_SECRET required")
	}

	if s.DigitalOceanKey == "" {
		log.Fatal("environment variable DOIT_DIGITALOCEAN_KEY required")
	}

	if s.DigitalOceanSecret == "" {
		log.Fatal("environment variable DOIT_DIGITALOCEAN_SECRET required")
	}

	if s.EncodingKey == "" {
		log.Fatal("environment variable DOIT_ENCODING_KEY required")
	}

	goth.UseProviders(
		digitalocean.New(s.DigitalOceanKey, s.DigitalOceanSecret, s.Callback, scope),
	)

	serv := doitserver.NewServer(s.EncodingKey)

	addr := ":" + port
	log.Printf("server listening at %s", addr)
	log.Fatal(http.ListenAndServe(addr, serv.Mux))
}
Example #23
0
func Service() helios.ServiceHandler {
	return func(h *helios.Engine) error {
		githubKey := os.Getenv("GITHUB_KEY")
		githubSecret := os.Getenv("GITHUB_SECRET")

		// Set the initial last event time to now
		LastEvent.EventTime = time.Now()

		// Setup Goth Authentication
		goth.UseProviders(
			githubProvider.New(githubKey, githubSecret, fmt.Sprintf("http://localhost:8989/auth/github/callback"), "repo", "user:email"),
		)

		// Setup github auth routes
		h.HTTPEngine.GET("/auth/github/callback", providerCallback)
		h.HTTPEngine.GET("/auth/github", providerAuth)

		//Socket.io Route
		h.HTTPEngine.GET("/socket.io/", func(c *gin.Context) {
			h.Socket.ServeHTTP(c.Writer, c.Request)
		})

		// Start socket broadcast channel and save the channel to a global
		EventChan = h.NewBroadcastChannel("github")

		// Load registered users
		err := loadUsersCSV()
		if err != nil {
			return err
		}

		// Start Existing Users
		startExistingUsers()

		return nil

	}
}
Example #24
0
func main() {
	flag.Parse()

	// 本番環境実行時はバイナリのあるディレクトリへと移動する
	if *env == "production" {
		dir := path.Dir(os.Args[0])
		os.Chdir(dir)
	}

	err := godotenv.Load(fmt.Sprintf("config/%s.env", *env))
	if err != nil {
		log.Fatal(err)
		return
	}

	goth.UseProviders(
		github.New(os.Getenv("GITHUB_CLIENT_KEY"), os.Getenv("GITHUB_SECRET"), os.Getenv("GITHUB_CALLBACK")),
	)

	p := pat.New()

	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	p.Add("GET", "/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
	p.Add("GET", "/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	p.Add("GET", "/login", &templateHandler{filename: "login.html"})
	p.Add("GET", "/index", &templateHandler{filename: "index.html"})
	p.Get("/auth/{action}/{provider}", loginHandler)
	p.Add("GET", "/room", r)

	// チャットルームの開始
	go r.run()
	// Webサーバの起動
	log.Println("Webサーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, p); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Example #25
0
File: goji.go Project: oov/gothic
func main() {
	const BaseURL = "http://localhost:8000"
	goth.UseProviders(
		twitter.New(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), BaseURL+"/auth/twitter/callback"),
		facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), BaseURL+"/auth/facebook/callback"),
		gplus.New(os.Getenv("GPLUS_KEY"), os.Getenv("GPLUS_SECRET"), BaseURL+"/auth/gplus/callback"),
		github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), BaseURL+"/auth/github/callback"),
		spotify.New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), BaseURL+"/auth/spotify/callback"),
		linkedin.New(os.Getenv("LINKEDIN_KEY"), os.Getenv("LINKEDIN_SECRET"), BaseURL+"/auth/linkedin/callback"),
		lastfm.New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), BaseURL+"/auth/lastfm/callback"),
		twitch.New(os.Getenv("TWITCH_KEY"), os.Getenv("TWITCH_SECRET"), BaseURL+"/auth/twitch/callback"),
	)

	tpl := template.New("")
	template.Must(tpl.New("index.html").Parse(`
<p><a href="/auth/twitter">Log in with Twitter</a></p>
<p><a href="/auth/facebook">Log in with Facebook</a></p>
<p><a href="/auth/gplus">Log in with GPlus</a></p>
<p><a href="/auth/github">Log in with Github</a></p>
<p><a href="/auth/spotify">Log in with Spotify</a></p>
<p><a href="/auth/lastfm">Log in with LastFM</a></p>
<p><a href="/auth/twitch">Log in with Twitch</a></p>
`))
	template.Must(tpl.New("user.html").Parse(`
<p>Name: {{.Name}}</p>
<p>Email: {{.Email}}</p>
<p>NickName: {{.NickName}}</p>
<p>Location: {{.Location}}</p>
<p>AvatarURL: {{.AvatarURL}} <img src="{{.AvatarURL}}"></p>
<p>Description: {{.Description}}</p>
<p>UserID: {{.UserID}}</p>
<p>AccessToken: {{.AccessToken}}</p>
`))

	goji.Get("/auth/:provider", func(c web.C, w http.ResponseWriter, r *http.Request) {
		err := gothic.BeginAuth(c.URLParams["provider"], w, r)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})
	goji.Get("/auth/:provider/callback", func(c web.C, w http.ResponseWriter, r *http.Request) {
		user, err := gothic.CompleteAuth(c.URLParams["provider"], w, r)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		err = tpl.ExecuteTemplate(w, "user.html", user)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})
	goji.Get("/", func(c web.C, w http.ResponseWriter, r *http.Request) {
		err := tpl.ExecuteTemplate(w, "index.html", nil)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})
	goji.Serve()
}
Example #26
0
			Cfg: OAuthConfig{
				Key:           "mykey",
				Secret:        "mysecret",
				JWTPrivateKey: sk,
				JWTPublicKey:  &sk.PublicKey,
				Client:        http.DefaultClient,
			},
		}
		gothic.Store = &FakeSessionStore{}

		req, err = http.NewRequest("GET", "/", nil)
		if err != nil {
			panic(err)
		}
		gothic.Store.Get(req, gothic.SessionName)
		goth.UseProviders(&faux.Provider{})
		gothic.GetProviderName = func(req *http.Request) (string, error) {
			return "faux", nil
		}
		OAuthVerifier = &FakeVerifier{Allow: true}
	})

	Describe("When seeing if requests are authenticated", func() {
		Context("For bearer token authentication", func() {
			It("Returns false if no bearer token, or authenticated session", func() {
				delete(gothic.Store.(*FakeSessionStore).Session.Values, "User")
				delete(gothic.Store.(*FakeSessionStore).Session.Values, "Membership")
				delete(gothic.Store.(*FakeSessionStore).Session.Values, gothic.SessionName)

				Expect(oa.IsAuthenticated(req)).Should(BeFalse())
			})
Example #27
0
func init() {
	Store = sessions.NewFilesystemStore(os.TempDir(), []byte("goth-test"))
	goth.UseProviders(&faux.Provider{})
}
Example #28
0
func main() {
	goth.UseProviders(
		twitter.New(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),
		// If you'd like to use authenticate instead of authorize in Twitter provider, use this instead.
		// twitter.NewAuthenticate(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),

		facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), "http://localhost:3000/auth/facebook/callback"),
		gplus.New(os.Getenv("GPLUS_KEY"), os.Getenv("GPLUS_SECRET"), "http://localhost:3000/auth/gplus/callback"),
		github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:3000/auth/github/callback"),
		spotify.New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "http://localhost:3000/auth/spotify/callback"),
		linkedin.New(os.Getenv("LINKEDIN_KEY"), os.Getenv("LINKEDIN_SECRET"), "http://localhost:3000/auth/linkedin/callback"),
		lastfm.New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), "http://localhost:3000/auth/lastfm/callback"),
		twitch.New(os.Getenv("TWITCH_KEY"), os.Getenv("TWITCH_SECRET"), "http://localhost:3000/auth/twitch/callback"),
		dropbox.New(os.Getenv("DROPBOX_KEY"), os.Getenv("DROPBOX_SECRET"), "http://localhost:3000/auth/dropbox/callback"),
		digitalocean.New(os.Getenv("DIGITALOCEAN_KEY"), os.Getenv("DIGITALOCEAN_SECRET"), "http://localhost:3000/auth/digitalocean/callback", "read"),
		bitbucket.New(os.Getenv("BITBUCKET_KEY"), os.Getenv("BITBUCKET_SECRET"), "http://localhost:3000/auth/bitbucket/callback"),
		instagram.New(os.Getenv("INSTAGRAM_KEY"), os.Getenv("INSTAGRAM_SECRET"), "http://localhost:3000/auth/instagram/callback"),
		box.New(os.Getenv("BOX_KEY"), os.Getenv("BOX_SECRET"), "http://localhost:3000/auth/box/callback"),
		salesforce.New(os.Getenv("SALESFORCE_KEY"), os.Getenv("SALESFORCE_SECRET"), "http://localhost:3000/auth/salesforce/callback"),
		amazon.New(os.Getenv("AMAZON_KEY"), os.Getenv("AMAZON_SECRET"), "http://localhost:3000/auth/amazon/callback"),
		yammer.New(os.Getenv("YAMMER_KEY"), os.Getenv("YAMMER_SECRET"), "http://localhost:3000/auth/yammer/callback"),
		onedrive.New(os.Getenv("ONEDRIVE_KEY"), os.Getenv("ONEDRIVE_SECRET"), "http://localhost:3000/auth/onedrive/callback"),

		//Pointed localhost.com to http://localhost:3000/auth/yahoo/callback through proxy as yahoo
		// does not allow to put custom ports in redirection uri
		yahoo.New(os.Getenv("YAHOO_KEY"), os.Getenv("YAHOO_SECRET"), "http://localhost.com"),
		slack.New(os.Getenv("SLACK_KEY"), os.Getenv("SLACK_SECRET"), "http://localhost:3000/auth/slack/callback"),
		stripe.New(os.Getenv("STRIPE_KEY"), os.Getenv("STRIPE_SECRET"), "http://localhost:3000/auth/stripe/callback"),
		wepay.New(os.Getenv("WEPAY_KEY"), os.Getenv("WEPAY_SECRET"), "http://localhost:3000/auth/wepay/callback", "view_user"),
		//By default paypal production auth urls will be used, please set PAYPAL_ENV=sandbox as environment variable for testing
		//in sandbox environment
		paypal.New(os.Getenv("PAYPAL_KEY"), os.Getenv("PAYPAL_SECRET"), "http://localhost:3000/auth/paypal/callback"),
		steam.New(os.Getenv("STEAM_KEY"), "http://localhost:3000/auth/steam/callback"),
		heroku.New(os.Getenv("HEROKU_KEY"), os.Getenv("HEROKU_SECRET"), "http://localhost:3000/auth/heroku/callback"),
		uber.New(os.Getenv("UBER_KEY"), os.Getenv("UBER_SECRET"), "http://localhost:3000/auth/uber/callback"),
		soundcloud.New(os.Getenv("SOUNDCLOUD_KEY"), os.Getenv("SOUNDCLOUD_SECRET"), "http://localhost:3000/auth/soundcloud/callback"),
		gitlab.New(os.Getenv("GITLAB_KEY"), os.Getenv("GITLAB_SECRET"), "http://localhost:3000/auth/gitlab/callback"),
	)

	m := make(map[string]string)
	m["amazon"] = "Amazon"
	m["bitbucket"] = "Bitbucket"
	m["box"] = "Box"
	m["digitalocean"] = "Digital Ocean"
	m["dropbox"] = "Dropbox"
	m["facebook"] = "Facebook"
	m["github"] = "Github"
	m["gitlab"] = "Gitlab"
	m["soundcloud"] = "SoundCloud"
	m["spotify"] = "Spotify"
	m["steam"] = "Steam"
	m["stripe"] = "Stripe"
	m["twitch"] = "Twitch"
	m["uber"] = "Uber"
	m["wepay"] = "Wepay"
	m["yahoo"] = "Yahoo"
	m["yammer"] = "Yammer"
	m["gplus"] = "Google Plus"
	m["heroku"] = "Heroku"
	m["instagram"] = "Instagram"
	m["lastfm"] = "Last FM"
	m["linkedin"] = "Linkedin"
	m["onedrive"] = "Onedrive"
	m["paypal"] = "Paypal"
	m["twitter"] = "Twitter"
	m["salesforce"] = "Salesforce"
	m["slack"] = "Slack"

	var keys []string
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	providerIndex := &ProviderIndex{Providers: keys, ProvidersMap: m}

	p := pat.New()
	p.Get("/auth/{provider}/callback", func(res http.ResponseWriter, req *http.Request) {

		user, err := gothic.CompleteUserAuth(res, req)
		if err != nil {
			fmt.Fprintln(res, err)
			return
		}
		t, _ := template.New("foo").Parse(userTemplate)
		t.Execute(res, user)
	})

	p.Get("/auth/{provider}", gothic.BeginAuthHandler)
	p.Get("/", func(res http.ResponseWriter, req *http.Request) {
		t, _ := template.New("foo").Parse(indexTemplate)
		t.Execute(res, providerIndex)
	})
	http.ListenAndServe(":3000", p)
}
func useGPlus(providerKey, providerSecret string) {
	goth.UseProviders(
		gplus.New(providerKey, providerSecret, app.EndPointURL+"auth/gplus/callback"),
	)
}
func useFacebook(providerKey, providerSecret string) {
	goth.UseProviders(
		facebook.New(providerKey, providerSecret, app.EndPointURL+"auth/facebook/callback"),
	)
}