179 lines
5.4 KiB
Go
Raw Normal View History

2017-07-02 21:42:46 +00:00
package auth
import (
2018-04-25 23:14:23 +00:00
"context"
2017-07-02 21:42:46 +00:00
"errors"
"io/ioutil"
"net/http"
"strings"
"github.com/aerogo/aero"
2019-06-03 09:32:43 +00:00
"github.com/animenotifier/notify.moe/arn"
2019-06-01 04:55:49 +00:00
"github.com/animenotifier/notify.moe/assets"
2017-07-02 21:42:46 +00:00
"github.com/animenotifier/notify.moe/utils"
2018-07-02 00:39:25 +00:00
jsoniter "github.com/json-iterator/go"
2017-07-02 21:42:46 +00:00
"golang.org/x/oauth2"
"golang.org/x/oauth2/facebook"
)
// FacebookUser is the user data we receive from Facebook
type FacebookUser struct {
ID string `json:"id"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Gender string `json:"gender"`
}
// InstallFacebookAuth enables Facebook login for the app.
func InstallFacebookAuth(app *aero.Application) {
// OAuth2 configuration defines the API keys,
// scopes of required data and the redirect URL
// that Facebook should send the user to after
// a successful login on their pages.
2017-07-02 21:42:46 +00:00
config := &oauth2.Config{
ClientID: arn.APIKeys.Facebook.ID,
ClientSecret: arn.APIKeys.Facebook.Secret,
2019-06-01 04:55:49 +00:00
RedirectURL: "https://" + assets.Domain + "/auth/facebook/callback",
2017-07-02 21:42:46 +00:00
Scopes: []string{
"public_profile",
"email",
},
Endpoint: facebook.Endpoint,
}
// When a user visits /auth/facebook, we ask OAuth2 config for a URL
// to redirect the user to. Once the user has logged in on that page,
// he'll be redirected back to our servers to the callback page.
2019-06-01 04:55:49 +00:00
app.Get("/auth/facebook", func(ctx aero.Context) error {
2017-07-02 21:42:46 +00:00
state := ctx.Session().ID()
url := config.AuthCodeURL(state)
2019-06-03 06:06:57 +00:00
return ctx.Redirect(http.StatusTemporaryRedirect, url)
2017-07-02 21:42:46 +00:00
})
// This is the redirect URL that we specified in the OAuth2 config.
// The user has successfully completed the login on Facebook servers.
// Now we have to check for fraud requests and request user information.
// If both Facebook ID and email can't be found in our DB, register a new user.
// Otherwise, log in the user with the given Facebook ID or email.
2019-06-01 04:55:49 +00:00
app.Get("/auth/facebook/callback", func(ctx aero.Context) error {
2017-07-02 21:42:46 +00:00
if !ctx.HasSession() {
return ctx.Error(http.StatusUnauthorized, "Facebook login failed", errors.New("Session does not exist"))
}
session := ctx.Session()
if session.ID() != ctx.Query("state") {
return ctx.Error(http.StatusUnauthorized, "Facebook login failed", errors.New("Incorrect state"))
}
// Handle the exchange code to initiate a transport
2018-04-25 23:14:23 +00:00
token, err := config.Exchange(context.Background(), ctx.Query("code"))
2017-07-02 21:42:46 +00:00
if err != nil {
return ctx.Error(http.StatusBadRequest, "Could not obtain OAuth token", err)
}
// Construct the OAuth client
2018-04-25 23:14:23 +00:00
client := config.Client(context.Background(), token)
2017-07-02 21:42:46 +00:00
// Fetch user data from Facebook
2019-03-04 02:33:08 +00:00
response, err := client.Get("https://graph.facebook.com/me?fields=email,first_name,last_name,gender")
2017-07-02 21:42:46 +00:00
if err != nil {
return ctx.Error(http.StatusBadRequest, "Failed requesting user data from Facebook", err)
}
2019-03-04 02:33:08 +00:00
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
2017-07-02 21:42:46 +00:00
// Construct a FacebookUser object
fbUser := FacebookUser{}
2018-07-02 00:39:25 +00:00
err = jsoniter.Unmarshal(body, &fbUser)
2017-07-02 21:42:46 +00:00
if err != nil {
return ctx.Error(http.StatusBadRequest, "Failed parsing user data (JSON)", err)
}
// Change googlemail.com to gmail.com
fbUser.Email = strings.Replace(fbUser.Email, "googlemail.com", "gmail.com", 1)
// Is this an existing user connecting another social account?
user := utils.GetUser(ctx)
if user != nil {
// Add FacebookToUser reference
2017-10-27 07:11:56 +00:00
user.ConnectFacebook(fbUser.ID)
2017-07-02 21:42:46 +00:00
2017-07-02 22:00:41 +00:00
// Save in DB
user.Save()
// Log
2019-06-01 04:55:49 +00:00
authLog.Info("Added Facebook ID to existing account | %s | %s | %s | %s | %s", user.Nick, user.ID, ctx.IP(), user.Email, user.RealName())
2017-07-02 21:42:46 +00:00
2019-06-03 06:06:57 +00:00
return ctx.Redirect(http.StatusTemporaryRedirect, "/")
2017-07-02 21:42:46 +00:00
}
var getErr error
// Try to find an existing user via the Facebook user ID
2017-10-27 07:11:56 +00:00
user, getErr = arn.GetUserByFacebookID(fbUser.ID)
2017-07-02 21:42:46 +00:00
if getErr == nil && user != nil {
2019-06-01 04:55:49 +00:00
authLog.Info("User logged in via Facebook ID | %s | %s | %s | %s | %s", user.Nick, user.ID, ctx.IP(), user.Email, user.RealName())
2017-07-02 21:42:46 +00:00
// Add FacebookToUser reference
user.ConnectFacebook(fbUser.ID)
2017-07-02 21:42:46 +00:00
user.LastLogin = arn.DateTimeUTC()
user.Save()
session.Set("userId", user.ID)
2019-06-03 06:06:57 +00:00
return ctx.Redirect(http.StatusTemporaryRedirect, "/")
2017-07-02 21:42:46 +00:00
}
// Try to find an existing user via the associated e-mail address
user, getErr = arn.GetUserByEmail(fbUser.Email)
if getErr == nil && user != nil {
2019-06-01 04:55:49 +00:00
authLog.Info("User logged in via Email | %s | %s | %s | %s | %s", user.Nick, user.ID, ctx.IP(), user.Email, user.RealName())
2017-07-02 21:42:46 +00:00
user.LastLogin = arn.DateTimeUTC()
user.Save()
session.Set("userId", user.ID)
2019-06-03 06:06:57 +00:00
return ctx.Redirect(http.StatusTemporaryRedirect, "/")
2017-07-02 21:42:46 +00:00
}
// Register new user
user = arn.NewUser()
user.Nick = "fb" + fbUser.ID
user.Email = fbUser.Email
user.FirstName = fbUser.FirstName
user.LastName = fbUser.LastName
user.Gender = fbUser.Gender
user.LastLogin = arn.DateTimeUTC()
// Save basic user info already to avoid data inconsistency problems
user.Save()
// Register user
2017-10-27 07:11:56 +00:00
arn.RegisterUser(user)
2017-07-02 21:42:46 +00:00
// Connect account to a Facebook account
2017-10-27 07:11:56 +00:00
user.ConnectFacebook(fbUser.ID)
2017-07-02 21:42:46 +00:00
// Save user object again with updated data
user.Save()
// Login
session.Set("userId", user.ID)
// Log
2019-06-01 04:55:49 +00:00
authLog.Info("Registered new user via Facebook | %s | %s | %s | %s | %s", user.Nick, user.ID, ctx.IP(), user.Email, user.RealName())
2017-07-02 21:42:46 +00:00
2018-06-04 08:18:07 +00:00
// Redirect to starting page for new users
2019-06-03 06:06:57 +00:00
return ctx.Redirect(http.StatusTemporaryRedirect, newUserStartRoute)
2017-07-02 21:42:46 +00:00
})
}