Exemple #1
0
func main() {
	//Loads environment variables from a .env file
	godotenv.Load("environment")

	var (
		clientID     = getEnv("OAUTH2_CLIENT_ID", "client_id")
		clientSecret = getEnv("OAUTH2_CLIENT_SECRET", "client_secret")
		redirectURL  = getEnv("OAUTH2_REDIRECT_URL", "redirect_url")
	)

	secureMux := http.NewServeMux()

	// Routes that require a logged in user
	// can be protected by using a separate route handler
	// If the user is not authenticated, they will be
	// redirected to the login path.
	secureMux.HandleFunc("/restrict", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		fmt.Fprintf(w, "OK: %s", token.Access())
	})

	secure := negroni.New()
	secure.Use(oauth2.LoginRequired())
	secure.UseHandler(secureMux)

	n := negroni.New()
	n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123"))))
	n.Use(oauth2.Google(&oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RedirectURL:  redirectURL,
		Scopes:       []string{"https://www.googleapis.com/auth/drive"},
	}))

	router := http.NewServeMux()

	//routes added to mux do not require authentication
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		if token == nil || !token.Valid() {
			fmt.Fprintf(w, "not logged in, or the access token is expired")
			return
		}
		fmt.Fprintf(w, "logged in")
		return
	})

	//There is probably a nicer way to handle this than repeat the restricted routes again
	//of course, you could use something like gorilla/mux and define prefix / regex etc.
	router.Handle("/restrict", secure)

	n.UseHandler(router)

	n.Run(":3000")
}
Exemple #2
0
func main() {

	secureMux := http.NewServeMux()

	// Routes that require a logged in user
	// can be protected by using a separate route handler
	// If the user is not authenticated, they will be
	// redirected to the login path.
	secureMux.HandleFunc("/restrict", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		fmt.Fprintf(w, "OK: %s", token.Access())
	})

	secure := negroni.New()
	secure.Use(oauth2.LoginRequired())
	secure.UseHandler(secureMux)

	n := negroni.New()
	n.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	n.Use(oauth2.Google(
		goauth2.Client("client_id", "client_secret"),
		goauth2.RedirectURL("redirect_url"),
		goauth2.Scope("https://www.googleapis.com/auth/drive"),
	))

	router := http.NewServeMux()

	//routes added to mux do not require authentication
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		if token == nil || token.Expired() {
			fmt.Fprintf(w, "not logged in, or the access token is expired")
			return
		}
		fmt.Fprintf(w, "logged in")
		return
	})

	//There is probably a nicer way to handle this than repeat the restricted routes again
	//of course, you could use something like gorilla/mux and define prefix / regex etc.
	router.Handle("/restrict", secure)

	n.UseHandler(router)

	n.Run(":3000")
}
Exemple #3
0
func fetch(w http.ResponseWriter, r *http.Request) {
	query := r.FormValue("q")
	tasks := make([]Item, 0)

	if len(query) > 0 {
		log.Println("Fetch request received. Query=" + query)
	} else {
		log.Println("Fetch request received. Query=<none>")
	}

	tokens := oauth2.GetToken(r)
	// Retrieve the access token if it's available. If not then
	// its an error.
	if !UserLoggedIn(r) {
		log.Println("ERR: no retrievable token for this user")
		http.Error(w, "", 500)
	} else {
		service, err := getGmailService(tokens)
		if err != nil {
			http.Error(w, "", 500)
		}

		// Get labels and create a mapping between ID's and names. Note that a label
		// on a message will be dropped unless it's mapping is available in this table.
		labelTable := make(map[string]string)
		labelReq := service.Users.Labels.List("me")
		labelResponse, err := labelReq.Do()
		if err != nil {
			log.Println(err.Error())
		}

		for _, label := range labelResponse.Labels {
			// Only keep user-defined labels. Gmail also creates some as well
			// but users don't see them so it's going to look whacky / broken here.
			if label.Type == "user" {
				labelTable[label.Id] = label.Name
			}
		}

		// Get messages
		messageReq := new(gmail.UsersMessagesListCall)
		if len(query) > 0 {
			messageReq = service.Users.Messages.List("me").Q(query)
		} else {
			messageReq = service.Users.Messages.List("me")
		}
		messageResponse, err := messageReq.Do()

		if err != nil {
			log.Println(err.Error())
		} else {
			// TODO: if the query succeeded, save this as the user's filter.
		}

		log.Println(fmt.Sprintf("Retrieving %d messages...", len(messageResponse.Messages)))
		for _, m := range messageResponse.Messages {
			msg, err := service.Users.Messages.Get("me", m.Id).Do()
			if err != nil {
				log.Println(err.Error())
			}

			tasks = append(tasks, parseMessage(msg, labelTable))
		}
	}

	data, err := json.Marshal(tasks)

	if err != nil {
		log.Println("Couldn't serialize item list: " + err.Error())
	}

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, string(data))
}
Exemple #4
0
func GetOAuth2Token(r *http.Request) OAuthToken {
	return oauth2.GetToken(r)
}
Exemple #5
0
func UserLoggedIn(r *http.Request) bool {
	token := oauth2.GetToken(r)
	return token != nil && token.Valid()
}