Exemplo n.º 1
0
func authCallback(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))
	fmt.Println("request method: " + req.Method)

	user, err := gothic.CompleteUserAuth(res, req)
	if err != nil {
		fmt.Fprintln(res, err)
		return
	}

	//t, _ := template.New("foo").Parse(userTemplate)

	account := &models.Account{user.Email, ""}
	fmt.Println(account.CheckExist())

	//if everything is fine, set the session for the current user
	sess, err := globalSessions.SessionStart(res, req)
	if err != nil {
		fmt.Println("set error,", err)
	}
	defer sess.SessionRelease(res)
	err = sess.Set("username", user.Email)
	if err != nil {
		fmt.Println("set error,", err)
	}

	//set the status of the user
	sess.Set("logged", "true")
	http.Redirect(res, req, "/user/"+user.Email, http.StatusFound)
	//t.Execute(res, user)
}
Exemplo n.º 2
0
func AuthCallback(w http.ResponseWriter, r *http.Request) {

	observedState := []byte(gothic.GetState(r))
	expectedState := state_hash

	if subtle.ConstantTimeCompare(observedState, expectedState) != 1 {
		http.Error(w, "State sent did not match state received.", http.StatusBadRequest)
		log.Info("Observed and expected states do not match.")
		return
	}

	user, err := gothic.CompleteUserAuth(w, r)
	if err != nil {
		log.Warn(w, err)
		return
	}

	t, err := template.ParseFiles("oauth/templates/user.html.tmpl")
	if err != nil {
		log.Warn(w, err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	t.Execute(w, user)
}
Exemplo n.º 3
0
func CallbackHandler(response http.ResponseWriter, request *http.Request) {
	session, err := Store.Get(request, "brewlog")
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	fmt.Println(gothic.GetState(request))
	gUser, err := gothic.CompleteUserAuth(response, request)
	if err != nil {
		fmt.Println(response, err)
		return
	}

	user, err := models.FindOrCreateUser(&gUser)
	if err != nil {
		fmt.Println(err.Error())
	}

	fmt.Println(user.Name)

	session.Values["user"] = user
	err = session.Save(request, response)
	if err != nil {
		fmt.Println(err.Error())
	}

	http.Redirect(response, request, "/", http.StatusFound)
}
Exemplo n.º 4
0
func HandleAuthCallback(w http.ResponseWriter, r *http.Request) {
	ctx := GetContext(r)

	if ctx.Account != nil {
		http.Redirect(w, r, "/organizations", http.StatusSeeOther)
		return
	}

	user, err := gothic.CompleteUserAuth(w, r)
	if err != nil {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return
	}

	acc, err := data.GetAccountEmail(user.Email)
	catch(r, err)
	if acc == nil {
		accEmail, err := data.NewAccountEmail(user.Email)
		catch(r, err)
		accEmail.Primary = true
		accEmail.Verified = true
		accEmail.VerifiedAt = time.Now()

		nAcc := data.Account{}
		nAcc.Emails = append(nAcc.Emails, accEmail)
		err = nAcc.Put()

		acc = &nAcc
	}

	ctx.Session.Values["accountID"] = acc.ID.Hex()
	ctx.Session.Save(r, w)
	http.Redirect(w, r, "/organizations", http.StatusSeeOther)
}
Exemplo n.º 5
0
// loginHandlerはサードパーティへのログインの処理を受け持ちます
// パスの形式: /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
	action := r.URL.Query().Get(":action")
	provider := r.URL.Query().Get(":provider")

	switch action {
	case "login":
		gothic.BeginAuthHandler(w, r)
		log.Println("TODO: ログイン処理", provider)
	case "callback":
		// 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(r))

		user, err := gothic.CompleteUserAuth(w, r)
		if err != nil {
			log.Fatal("CompleteUserAuth error: ", err)
			return
		}

		authCookieValue := base64.StdEncoding.EncodeToString([]byte(user.Name))
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})
		fmt.Println(user)
		w.Header().Set("Location", "/chat")
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "アクション%sには非対応です", action)
	}
}
Exemplo n.º 6
0
func providerCallback(h *helios.Engine, g *GithubService) gin.HandlerFunc {
	return func(c *gin.Context) {
		var user User

		// Run user auth using the gothic library
		githubUser, err := gothic.CompleteUserAuth(c.Writer, c.Request)
		if err != nil {
			h.Warn("Failed to create user from callback", "error", err.Error())
		}

		user.Username = githubUser.RawData["login"].(string)
		user.AccessToken = githubUser.AccessToken

		// If the user doesn't exist yet
		if _, ok := g.Users[user.Username]; !ok {
			userFile, err := os.OpenFile("users.csv", os.O_APPEND|os.O_WRONLY, 0644)
			defer userFile.Close()

			_, err = userFile.WriteString(fmt.Sprintf("%s,%s\n", user.Username, user.AccessToken))
			if err != nil {
				h.Error("Failed to write new users to CSV", "error", err.Error())
			}

			g.Users[user.Username] = user
			// startUser(user)

		} else {
			h.Info("User already exists")
		}

		c.JSON(200, user)
	}
}
Exemplo n.º 7
0
func callbackAuthHandler(res http.ResponseWriter, req *http.Request) {
	user, err := gothic.CompleteUserAuth(res, req)
	if err != nil {
		fmt.Fprintln(res, err)
		return
	}
	t, _ := template.New("userinfo").Parse(userTemplate)
	t.Execute(res, user)
}
Exemplo n.º 8
0
func (s *Server) AuthCallback(c *gin.Context) {
	fn := gothic.GetProviderName
	gothic.GetProviderName = func(req *http.Request) (string, error) {
		provider := c.Params.ByName("provider")
		if provider == "" {
			return fn(req)
		}
		return provider, nil
	}

	provider, _ := gothic.GetProviderName(c.Request)
	u, err := gothic.CompleteUserAuth(c.Writer, c.Request)
	if err != nil {
		c.String(400, err.Error())
		return
	}

	ctx, cancel := DefaultTimeoutContext()
	defer cancel()

	authinfo := &pb.OAuthUser{
		UserId:            u.UserID,
		Name:              u.Name,
		NickName:          u.NickName,
		Email:             u.Email,
		AccessToken:       u.AccessToken,
		AccessTokenSecret: u.AccessTokenSecret,
		Provider:          provider,
	}

	profile, err := s.CurrentUser(c)
	if err != nil {
		c.Fail(500, err)
		return
	}
	authinfo.Uuid = profile.Uuid
	profile, err = s.client.PutOAuth(ctx, authinfo)
	if RequestError(c, err) {
		return
	}

	// Only allow login from google
	// Twitter only for importing feed
	if provider == "google" {
		sess := sessions.Default(c)
		sess.Set("user_id", u.UserID)
		sess.Set("uuid", profile.Uuid)
		sess.Save()
	}

	next := extractNextPath(c.Request.URL.Query().Get("state"))
	if next == "/" && provider == "twitter" {
		next = "/account/import"
	}
	http.Redirect(c.Writer, c.Request, next, http.StatusFound)
}
Exemplo n.º 9
0
// loginHandlerはサードパーティへのログインの処理を受け持ちます
// パスの形式: /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
	action := r.URL.Query().Get(":action")
	// provider := r.URL.Query().Get(":provider")

	switch action {
	case "login":
		gothic.BeginAuthHandler(w, r)
	case "callback":
		// 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(r))

		githubUser, err := gothic.CompleteUserAuth(w, r)
		if err != nil {
			log.Fatal("CompleteUserAuth error: ", err)
			return
		}

		// ユーザーの保存
		var user User
		err = mapstructure.Decode(githubUser.RawData, &user)
		if err != nil {
			log.Fatal("mapstructure error: ", err)
			return
		}

		session, err := mgo.Dial("mongodb://localhost")
		if err != nil {
			log.Fatal("mgo database dial error:", err)
			return
		}
		defer session.Close()

		session.SetMode(mgo.Monotonic, true)
		c := session.DB("donuts_tech_calendar").C("users")
		err = user.FindOrCreate(c)
		if err != nil {
			log.Fatal("user.FindOrCreate error:", err)
			return
		}

		authCookieValue := base64.StdEncoding.EncodeToString([]byte(user.UserName))
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})

		w.Header().Set("Location", "/index#/chat")
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "アクション%sには非対応です", action)
	}
}
Exemplo n.º 10
0
func callbackPageHandler(res http.ResponseWriter, req *http.Request) {

	// print our state string to the console
	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)
}
Exemplo n.º 11
0
func (ac *AuthCallback) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	session, err := gothic.Store.Get(r, "doit-server")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	var isCLIAuth bool
	id := session.Values["current-auth"].(string)
	if _, ok := session.Values["cli-auth"]; ok {
		isCLIAuth = true
	}

	user, err := gothic.CompleteUserAuth(w, r)

	if !isCLIAuth {
		c := ac.consumers.Get(id)

		if err != nil {
			c <- Consumer{
				ID:      id,
				Err:     err.Error(),
				Message: "unble to complete authorization",
			}

			return
		}

		c <- Consumer{
			ID:          id,
			AccessToken: user.AccessToken,
		}

		fmt.Fprintf(w, updateTemplate)
		return
	}

	if err != nil {
		fmt.Fprintln(w, "Unable to retrieve access token")
		delete(session.Values, "cli-auth")
		_ = session.Save(r, w)
		return
	}

	delete(session.Values, "cli-auth")
	_ = session.Save(r, w)

	t, _ := template.New("cliTemplate").Parse(cliTemplate)
	t.Execute(w, user)
}
Exemplo n.º 12
0
func handleSocialLogin(rw http.ResponseWriter, req *http.Request) {
	log.Println(gothic.GetState(req))
	socialUser, err := gothic.CompleteUserAuth(rw, req)
	if err != nil {
		log.Println(err)
		http.Error(rw, err.Error(), http.StatusBadRequest)
		return
	}

	user := auth.User{}
	user.UserID = socialUser.UserID
	user.Email = socialUser.Email

	log.Println(socialUser.UserID)
	log.Println(socialUser.AccessToken)
	log.Println(socialUser.NickName)
}
Exemplo n.º 13
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)
}
Exemplo n.º 14
0
func providerCallback(c *gin.Context) {
	// Run user auth using the gothic library
	user, err := gothic.CompleteUserAuth(c.Writer, c.Request)
	if err != nil {
		logging.ErrorWithTags([]string{"github", "api"}, "Failed to create user from callback", err.Error())
	}

	u := User{}

	err = u.GetByUsername(user.RawData["login"].(string))
	if err != nil {
		if err != sql.ErrNoRows {
			logging.ErrorWithTags([]string{"api"}, "Failed to read from user table", err.Error())
			return
		}
	}

	//Add user to the user table
	u.Name = user.Name
	u.Username = user.RawData["login"].(string)
	u.AvatarUrl = user.AvatarURL
	u.AccessToken = user.AccessToken
	u.ProfileUrl = user.RawData["url"].(string)
	u.Email = user.Email
	u.Joined = user.RawData["created_at"].(string)
	u.Raw = user.RawData

	if u.Id != 0 {
		u.UpdateTime()
		_, err = dbmap.Update(&u)
		if err != nil {
			logging.ErrorWithTags([]string{"db"}, "Failed to update user row", err.Error())
		}
	} else {
		err = u.Create()
		if err != nil {
			logging.ErrorWithTags([]string{"db"}, "Failed to create new user row", err.Error())
		}

		//Add the user's go routine
		StartUserRoutine(u, activityChan)
	}

	c.JSON(200, u)
}
func sessionsCreate(res http.ResponseWriter, req *http.Request) {
	user, err := gothic.CompleteUserAuth(res, req)
	if err != nil {
		panic(err)
	}

	currentUser := FindOrCreateUserFromAuthHash(user)

	encriptKey := os.Getenv("ENCRIPT_KEY")
	token := hex.EncodeToString(encrypt(encriptKey, make([]byte, currentUser.Id)))

	http.SetCookie(res, &http.Cookie{
		Name:  "session",
		Value: token,
		Path:  "/",
	})
	http.Redirect(res, req, "/", http.StatusFound)
}
Exemplo n.º 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"),
		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)
}
Exemplo n.º 17
0
func (ah *AuthHandler) FacebookCallback(c *gin.Context) {
	user, err := gothic.CompleteUserAuth(c.Writer, c.Request)

	if err != nil {
		c.JSON(http.StatusInternalServerError, responses.ResponseError{
			ErrorCodeId:      78, // some fictional code
			DeveloperMessage: err.Error(),
			UserMessage:      "An error occured whipe processing your request.",
		})
		return
	}

	// @TODO Here we have got user access token and base information

	c.JSON(http.StatusOK, map[string]string{
		"UserAccessToken": user.AccessToken,
		"UserName":        user.Name,
		"UserEmail":       user.Email,
	})
}
func callbackHandler(c *echo.Context) error {
	user, err := gothic.CompleteUserAuth(c.Response(), c.Request())
	if err != nil {
		log.Println(err)
		return err
	}
	provider, _ := gothic.GetProviderName(c.Request())
	var u *models.User
	u, err = storage.Users.Find(provider, user.UserID)
	if err != nil {
		u, err = appAuth.CreateNewOAuthUser(user)
		if err != nil {
			return err
		}
	}

	log.Println("te user : "******"oauthCallback.html", user)

	return nil
}
Exemplo n.º 19
0
// CallbackAuth handles callbacks from OAuth 2 APIs, signing in users and
// creating them if they do not exist. Once the user is signed in, their userID
// is stored into their session for identification. Afterwards they are
// redirected to the main site.
func CallbackAuth(w rest.ResponseWriter, req *rest.Request) {
	setProvider(req)
	gothUser, err := gothic.CompleteUserAuth(w.(http.ResponseWriter), req.Request)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	user, httpErr := transactions.GetUserByEmail(gothUser.Email)
	if httpErr != nil {
		rest.Error(w, httpErr.Error(), httpErr.Code())
		return
	}
	if user == nil {
		user = &types.User{
			Name:   gothUser.Name,
			Avatar: gothUser.AvatarURL,
			Email:  gothUser.Email,
			ID:     base64.RawURLEncoding.EncodeToString(uuid.NewRandom()),
		}
		httpErr = transactions.AddUser(user)
		if httpErr != nil {
			rest.Error(w, httpErr.Error(), httpErr.Code())
			return
		}
	}
	session, err := gothic.Store.Get(req.Request, gothic.SessionName)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	session.Values["userID"] = user.ID
	err = session.Save(req.Request, w.(http.ResponseWriter))
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w.(http.ResponseWriter), req.Request, fmt.Sprintf("https://%s%s", apiConfig.Website.URL, apiConfig.Website.HTTPSPort), http.StatusTemporaryRedirect)
}
Exemplo n.º 20
0
func (c *LoginController) Validate() {
	c.mapUrl()
	if c.isLoggedIn() {
		log.Print("Yes a token exist")
		c.Ctx.Redirect(301, "/secure")
		return
	}

	// Check if the user already have a valid token
	var j goJwt.GOJWT

	res := c.Ctx.ResponseWriter
	req := c.Ctx.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("key: ", gothic.)

	user, err := gothic.CompleteUserAuth(res, req)
	log.Print("GothUser: "******"GothError: ", err)
	userAttributes := make(map[string]interface{})
	userAttributes["Name"] = user.Name
	userAttributes["Email"] = user.Email
	userAttributes["AccessToken"] = user.AccessToken

	token, err := j.CreateToken(userAttributes, &res, req)
	if err != nil {
		log.Print(res, err)
		return
	}
	token = token

	log.Print("Authentication completed")
	c.Ctx.Redirect(301, "/secure")

}
Exemplo n.º 21
0
func (oa OAuthenticator) OAuthCallback() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Debugf("Incoming Auth request: %s", r)
		sess, err := gothic.Store.Get(r, gothic.SessionName)
		if err != nil {
			log.Errorf("Error retrieving session info: %s", err)
			w.WriteHeader(500)
			return
		}
		log.Debugf("Processing oauth callback for '%s'", sess.ID)
		if gothic.GetState(r) != sess.Values["state"] {
			w.WriteHeader(403)
			w.Write([]byte("Unauthorized"))
			return
		}

		if r.URL.Query().Get("code") == "" {
			log.Errorf("No code detected in oauth callback: %v", r)
			w.WriteHeader(403)
			w.Write([]byte("No oauth code issued from provider"))
			return
		}

		user, err := gothic.CompleteUserAuth(w, r)
		if err != nil {
			log.Errorf("Error verifying oauth success: %s. Request: %v", err, r)
			w.WriteHeader(403)
			w.Write([]byte("UnOAuthorized"))
			return
		}

		log.Debugf("Authenticated user %#v", user)

		ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: user.AccessToken})
		ctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, oa.Cfg.Client)
		tc := oauth2.NewClient(ctx, ts)

		log.Debugf("Checking authorization...")
		membership, err := OAuthVerifier.Membership(user, tc)
		if err != nil {
			log.Errorf("Error retreiving user membership: %s", err)
			w.WriteHeader(403)
			w.Write([]byte("Unable to verify your membership"))
			return
		}

		if !OAuthVerifier.Verify(user.NickName, membership) {
			log.Debugf("Authorization denied")
			w.WriteHeader(403)
			w.Write([]byte("You are not authorized to view this content"))
			return
		}

		log.Infof("Successful login for %s", user.NickName)

		redirect := "/"
		if flashes := sess.Flashes(); len(flashes) > 0 {
			if flash, ok := flashes[0].(string); ok {
				// don't redirect back to api calls, to prevent auth redirection loops
				if !apiCall.MatchString(flash) || cliAuthCall.MatchString(flash) {
					redirect = flash
				}
			}
		}

		sess.Values["User"] = user.NickName
		sess.Values["Membership"] = membership
		err = sess.Save(r, w)
		if err != nil {
			log.Errorf("Error saving session: %s", err)
			w.WriteHeader(500)
			w.Write([]byte("Unable to save authentication data. Check the SHIELD logs for more info."))
			return
		}

		http.Redirect(w, r, redirect, 302) // checks auth
	})
}
Exemplo n.º 22
0
func main() {

	getPathFromParameterAndLoadConfigFile()

	goth.UseProviders(
		facebook.New("870850926323133", "54c9687312192961b6e2b5caa319db4b", "http://localhost:8081/auth/facebook/callback"),
	)

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

	router := gin.New()

	router.Use(cors.Middleware(cors.Options{
		AllowHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "Access-Control-Allow-Origin"},
	}))

	// Set Logger
	gin.DefaultWriter = config.GetLogFile()
	router.Use(gin.Logger())
	router.Use(gin.Recovery())

	tasks.SetRoutes(router)

	public := router.Group("/api")

	public.GET("/", func(c *gin.Context) {
		tokenString, err := createJWTToken("AnonymousUser")
		if err != nil {
			c.JSON(500, gin.H{"message": "Could not generate token"})
			return
		}
		c.JSON(200, gin.H{"accessToken": tokenString})
	})

	private := router.Group("/api/private")
	private.Use(jwt.Auth(config.TokenSecret))

	/*
		Set this header in your request to get here.
		Authorization: Bearer `token`
	*/
	private.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello from private"})
	})

	authRoute := router.Group("/auth")
	authRoute.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Go to /auth/facebook"})
	})
	authRoute.GET("/facebook", func(c *gin.Context) {
		gothic.GetProviderName = getProviderFacebook
		gothic.BeginAuthHandler(c.Writer, c.Request)
	})
	authRoute.GET("/facebook/callback", func(c *gin.Context) {

		user, err := gothic.CompleteUserAuth(c.Writer, c.Request)
		if err != nil {
			fmt.Fprintln(c.Writer, err)
			return
		}

		tokenString, err := createJWTToken(user.Email)
		if err != nil {
			c.JSON(500, gin.H{"message": "Could not generate token"})
		}

		c.JSON(200, gin.H{
			"name":                user.Name,
			"email":               user.Email,
			"userId":              user.UserID,
			"facebookAccessToken": user.AccessToken,
			"accessToken":         tokenString,
		})
	})

	router.Run(config.Settings["ListenAddress"].(string))
}
Exemplo n.º 23
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)
}