Esempio n. 1
0
func loginHandler(providerName string, auth bool) http.HandlerFunc {
	if auth != true {
		return func(w http.ResponseWriter, r *http.Request) {}
	}

	return func(w http.ResponseWriter, r *http.Request) {

		provider, err := gomniauth.Provider(providerName)
		if err != nil {
			log.Printf("error getting gomniauth provider")
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

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

		authURL, err := provider.GetBeginAuthURL(state, nil)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		http.Redirect(w, r, authURL, http.StatusFound)
	}
}
Esempio n. 2
0
func loginHandler(providerName string) http.HandlerFunc {
	provider, err := gomniauth.Provider(providerName)
	if err != nil {
		panic(err)
	}
	return func(w http.ResponseWriter, r *http.Request) {

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

		// This code borrowed from goweb example and not fixed.
		// 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 {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// redirect
		http.Redirect(w, r, authUrl, http.StatusFound)

	}
}
Esempio n. 3
0
func generateAuthRoutes() {
	/* Perform the auth */
	goweb.Map("/auth/{provider}", func(c context.Context) error {
		log.Println("Starting authentication")
		provider, err := gomniauth.Provider(c.PathValue("provider"))
		log.Println("Created new provider")
		if err != nil {
			return err
		}
		state := gomniauth.NewState("after", "success")
		log.Println("Set to new state")
		authUrl, err := provider.GetBeginAuthURL(state, nil)
		log.Println("Getting auth url")
		if err != nil {
			return err
		}
		log.Println("Responding with redirect")
		return goweb.Respond.WithRedirect(c, authUrl)
	})
	/* Callback from auth */
	goweb.Map("/auth/{provider}/callback", func(c context.Context) error {
		log.Println("Authentication response")
		provider, err := gomniauth.Provider(c.PathValue("provider"))
		if err != nil {
			log.Fatalf("Error with provider")
			return goweb.Respond.WithRedirect(c, "/auth/status/failed")
		}
		creds, err := provider.CompleteAuth(c.QueryParams())
		log.Println("Completing authentication")
		if err != nil {
			log.Fatalf("Error completing authentication")
			return goweb.Respond.WithRedirect(c, "/auth/status/failed")
		}
		log.Println("Getting user credentials")
		user, userErr := provider.GetUser(creds)
		if userErr != nil {
			log.Fatalf("Get user error")
			return goweb.Respond.WithRedirect(c, "/auth/status/failed")
		}

		log.Println("Authenticated successfully!")
		log.Println("Username: %s User email: %s", user.Name(), user.Email())
		return goweb.Respond.WithRedirect(c, "/auth/status/successful")
	})
	/* Complete auth notification */
	goweb.Map("/auth/status/successful", func(c context.Context) error {

		return goweb.Respond.With(c, 200, []byte("Authentication completed successfully"))
	})
	/* Failed auth notification */
	goweb.Map("/auth/status/failed", func(c context.Context) error {
		return goweb.Respond.With(c, 400, []byte("Authentication failed"))
	})
}
Esempio n. 4
0
func (a *defaultAuthenticator) getRedirectURL(r *http.Request, providerName string) (string, error) {
	provider, err := a.getAuthProvider(r, providerName)
	if err != nil {
		return "", errgo.Mask(err)
	}
	state := gomniauth.NewState("after", "success")
	url, err := provider.GetBeginAuthURL(state, nil)
	if err != nil {
		return url, errgo.Mask(err)
	}
	return url, nil
}
Esempio n. 5
0
func login(w http.ResponseWriter, r *http.Request, redirect string) {

	provider, err := gomniauth.Provider("google")
	if err != nil {
		log.Fatal(err)
	}

	state := gomniauth.NewState("redirect", redirect)
	authUrl, err := provider.GetBeginAuthURL(state, nil)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	loginPage.Execute(w, []Provider{{URL: template.URL(authUrl), Name: "Google"}})
}
Esempio n. 6
0
func loginHandler(providerName string) http.HandlerFunc {
	provider, err := gomniauth.Provider(providerName)
	if err != nil {
		panic(err)
	}

	return func(w http.ResponseWriter, r *http.Request) {
		state := gomniauth.NewState("after", "success")

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

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// redirect
		http.Redirect(w, r, authURL, http.StatusFound)
	}
}
Esempio n. 7
0
// LoginHandler begins github OAuth2 authentication
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	if !enabled {
		return
	}

	provider, err := gomniauth.Provider(providerName)
	if err != nil {
		glog.Errorf("failed to get authentication provider %s: %v", providerName, err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

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

	authURL, err := provider.GetBeginAuthURL(state, nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, authURL, http.StatusFound)
}
Esempio n. 8
0
func Connect(ctx context.Context) error {
	provider_type := ctx.PathValue("provider")
	action := ctx.PathValue("action")

	if provider_type == "facebook" {
		provider, err := gomniauth.Provider(provider_type)
		if err != nil {
			log.Error("Error on getting provider: " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."})
		}
		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 {
			log.Error("Error on getting url: " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."})
		}
		// redirect
		return goweb.Respond.WithRedirect(ctx, authUrl)
	} else if provider_type == "local" && ctx.MethodString() == "POST" {
		// This is taken care of in separate functions.
		// Local login only with POST
		if action == "login" {
			return nil
		} else if action == "register" {
			return nil
		} else if action == "connect" {
			return nil
		} else {
			return goweb.API.Respond(ctx, 200, nil, []string{"Invalid action."})
		}
	} else {
		return goweb.API.Respond(ctx, 200, nil, []string{"Invalid provider type."})
	}
}
Esempio n. 9
0
func main() {
	usr := hero.User{
		UserName: "******",
		Password: "******",
		Email:    "*****@*****.**",
	}

	genericClient := hero.Client{
		Name:   "simple",
		UUID:   "sampleUUID",
		Secret: "mysecret",
	}

	heroCfg := hero.DefaultConfig()

	heroURL := "http://localhost:8000"
	demoserver := "http://localhost:8001"

	s := hero.NewServer(heroCfg, &hero.SimpleTokenGen{}, nil)
	s.DropAllTables()
	s.Migrate()
	cCliet := genericClient
	cCliet.RedirectURL = demoserver + "/callback"
	cUsr := usr
	s.TestClient(&cUsr, &cCliet)

	clientCfg := &client.Config{
		ProviderName:        "hero",
		ProviderDisplayName: "Hero",
		AuthURL:             fmt.Sprintf("%s%s", heroURL, heroCfg.AuthEndpoint),
		TokenURL:            fmt.Sprintf("%s%s", heroURL, heroCfg.TokenEndpoint),
		ProfileURL:          heroURL + heroCfg.InfoEndpoint,
		CLientID:            genericClient.UUID,
		CLientSecret:        genericClient.Secret,
		DefaultScope:        "user",
		RedirectURL:         fmt.Sprintf("%s/callback", demoserver),
	}
	gomniauth.SetSecurityKey("ylqRcG4sLnhgOUIt3hbPKiHULHgrutOkpBNwibeJjL4eZ08zzR6YQ0WPl476Cubo")
	gomniauth.WithProviders(
		client.New(clientCfg),
	)
	demo := http.NewServeMux()

	demo.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		provider, err := gomniauth.Provider(clientCfg.ProviderName)
		if err != nil {
			//			w.Write([]byte(err.Error()))
			//			return
			panic(err)
		}
		state := gomniauth.NewState("after", "success")

		// This code borrowed from goweb example and not fixed.
		// 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 {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// redirect
		http.Redirect(w, r, authUrl, http.StatusFound)
	})

	demo.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
		provider, err := gomniauth.Provider(clientCfg.ProviderName)
		if err != nil {
			panic(err)
		}
		omap, err := objx.FromURLQuery(r.URL.RawQuery)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		creds, err := provider.CompleteAuth(omap)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		/*
			// This code borrowed from goweb example and not fixed.
			// get the state
			state, err := gomniauth.StateFromParam(ctx.QueryValue("state"))

			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			// 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 {
			http.Error(w, userErr.Error(), http.StatusInternalServerError)
			return
		}

		rst := make(map[string]interface{})
		rst["name"] = user.Name()
		rst["email"] = user.Email()
		json.NewEncoder(w).Encode(rst)

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

	go http.ListenAndServe(":8000", s)
	log.Println(" visit server at " + demoserver + "/login")
	log.Fatal(http.ListenAndServe(":8001", demo))
}
Esempio n. 10
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
	   ----------------------------------------------------------------
	*/

}