//GithubLoginCallback Called by github after authorization is granted
func GithubLoginCallback(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	log.Println("GithubLoginCallback")
	state := r.FormValue("state")
	if state != oauth.RandomString {
		log.Printf("invalid oauth state, expected '%s', got '%s'\n", oauth.RandomString, state)
		http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
		return
	}

	code := r.FormValue("code")
	// Convert the auth code into a token
	token, err := oauth.Conf.Exchange(oauth2.NoContext, code)
	if err != nil {
		log.Printf("oauthConf.Exchange() failed with '%s'\n", err)
		http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
		return
	}

	// Get a client that uses the auth token
	oauthClient := oauth.Conf.Client(oauth2.NoContext, token)
	githubClient := github.NewClient(oauthClient)
	// Get the user info
	user, _, err := githubClient.Users.Get("")
	if err != nil {
		log.Printf("client.Users.Get() failed with '%s'\n", err)
		http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
		return
	}

	u, err := store.GetUser(*user.Login)
	if err != nil {
		log.Printf("store.GetUser failed with '%s'\n", err)
	}
	u.Username = *user.Login
	//	u.Email = *user.Email
	u.Token = *token
	u.AvatarURL = *user.AvatarURL
	u.GithubProfile = *user.HTMLURL
	err = store.SaveUser(u)

	session := sessions.GetSession(r)
	session.Set("username", *user.Login)

	log.Printf("Logged in as GitHub user: %s\n", *user.Login)
	http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
Esempio n. 2
0
// Index is the Hugoku home page handler will redirect a non logged user to do the logging with Github
// or show a list of projectst and a form to add a project to a logged user,
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {

	session := sessions.GetSession(r)
	username := session.Get("username")

	if username == nil {
		t, err := template.ParseFiles("templates/index.html",
			"templates/partials/header.html",
			"templates/partials/footer.html",
		)
		if err != nil {
			log.Fatal("Error parsing the index page template: ", err)
		}
		err = t.Execute(w, nil)
		if err != nil {
			log.Fatal("Error executing the index page template: ", err)
		}
	} else {
		t, err := template.ParseFiles("templates/home.html",
			"templates/partials/header.html",
			"templates/partials/footer.html")
		if err != nil {
			log.Fatal("Error parsing the home page template: ", err)
		}
		log.Println("Recovering user data")
		user, err := store.GetUser(username.(string))
		if err != nil {
			log.Fatal(err)
		}
		log.Println(user)
		err = t.Execute(w, user)
		if err != nil {
			log.Fatal("Error executing the home page template: ", err)
		}
	}
}
Esempio n. 3
0
// GetUser gets the user from the usernane in the session on the http Request
func GetUser(r *http.Request) (store.User, error) {
	session := sessions.GetSession(r)
	username := session.Get("username")
	return store.GetUser(username.(string))
}