mirror of
https://github.com/acaloiaro/newsbox
synced 2026-07-21 18:29:15 +00:00
68 lines
1.6 KiB
Go
68 lines
1.6 KiB
Go
package actions
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"newsbox/internal"
|
|
"newsbox/models"
|
|
|
|
"github.com/gobuffalo/buffalo"
|
|
"github.com/gobuffalo/nulls"
|
|
"github.com/gobuffalo/pop/v6"
|
|
"github.com/markbates/going/defaults"
|
|
"github.com/markbates/goth"
|
|
"github.com/markbates/goth/gothic"
|
|
"github.com/markbates/goth/providers/github"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
func init() {
|
|
gothic.Store = App().SessionStore
|
|
callbackBaseURL := internal.BaseUrl()
|
|
callbackURL := fmt.Sprintf("%s%s", callbackBaseURL, "/oauth/github/callback")
|
|
goth.UseProviders(
|
|
github.New(os.Getenv("GH_OAUTH_CLIENT_ID"), os.Getenv("GH_OAUTH_CLIENT_SECRET"), callbackURL),
|
|
)
|
|
}
|
|
|
|
// AuthCallback handles Oauth callback requests
|
|
func OauthCallback(c buffalo.Context) error {
|
|
gu, err := gothic.CompleteUserAuth(c.Response(), c.Request())
|
|
if err != nil {
|
|
return c.Error(401, err)
|
|
}
|
|
tx := c.Value("tx").(*pop.Connection)
|
|
q := tx.Where("provider = ? and provider_id = ?", gu.Provider, gu.UserID)
|
|
exists, err := q.Exists("users")
|
|
if err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
u := &models.User{}
|
|
if exists {
|
|
if err = q.First(u); err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
}
|
|
|
|
u.Provider = gu.Provider
|
|
u.Username = gu.RawData["login"].(string)
|
|
u.Name = defaults.String(gu.Name, gu.NickName)
|
|
u.ProviderID = gu.UserID
|
|
if gu.Email != "" {
|
|
u.Email = nulls.NewString(gu.Email)
|
|
}
|
|
|
|
if err = tx.Save(u); err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
|
|
c.Session().Set("current_user_id", u.ID)
|
|
if err = c.Session().Save(); err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
|
|
c.Flash().Add("success", fmt.Sprintf("Welcome Back, %s!", u.Name))
|
|
|
|
return c.Redirect(302, "/")
|
|
}
|