189 lines
5.6 KiB
Go
Raw Normal View History

2017-06-16 23:32:47 +00:00
package auth
2017-06-07 16:06:57 +00:00
import (
2018-04-25 23:14:23 +00:00
"context"
2017-06-07 16:06:57 +00:00
"errors"
"io/ioutil"
"net/http"
2017-07-02 21:42:46 +00:00
"strings"
2017-06-07 16:06:57 +00:00
"github.com/aerogo/aero"
2017-06-07 19:12:59 +00:00
"github.com/animenotifier/arn"
2017-06-22 20:26:52 +00:00
"github.com/animenotifier/notify.moe/utils"
2018-07-02 00:39:25 +00:00
jsoniter "github.com/json-iterator/go"
2017-06-07 16:06:57 +00:00
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
2017-06-07 19:12:59 +00:00
// GoogleUser is the user data we receive from Google
type GoogleUser struct {
2018-12-07 01:06:01 +00:00
Sub string `json:"sub"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Email string `json:"email"`
Gender string `json:"gender"`
// Name string `json:"name"`
// Profile string `json:"profile"`
// Picture string `json:"picture"`
// EmailVerified bool `json:"email_verified"`
2017-06-07 19:12:59 +00:00
}
2017-06-16 23:32:47 +00:00
// InstallGoogleAuth enables Google login for the app.
func InstallGoogleAuth(app *aero.Application) {
// OAuth2 configuration defines the API keys,
// scopes of required data and the redirect URL
// that Google should send the user to after
// a successful login on their pages.
2017-06-17 17:50:30 +00:00
config := &oauth2.Config{
2017-06-27 14:23:57 +00:00
ClientID: arn.APIKeys.Google.ID,
ClientSecret: arn.APIKeys.Google.Secret,
2017-06-15 17:56:09 +00:00
RedirectURL: "https://" + app.Config.Domain + "/auth/google/callback",
2017-06-07 16:06:57 +00:00
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.email",
2017-06-17 17:50:30 +00:00
"https://www.googleapis.com/auth/userinfo.profile",
// "https://www.googleapis.com/auth/plus.me",
// "https://www.googleapis.com/auth/plus.login",
2017-06-07 16:06:57 +00:00
},
Endpoint: google.Endpoint,
}
// When a user visits /auth/google, 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.
2017-06-07 16:06:57 +00:00
app.Get("/auth/google", func(ctx *aero.Context) string {
2017-07-02 21:42:46 +00:00
state := ctx.Session().ID()
url := config.AuthCodeURL(state)
2018-06-04 08:15:49 +00:00
return ctx.Redirect(url)
2017-06-07 16:06:57 +00:00
})
// This is the redirect URL that we specified in the OAuth2 config.
// The user has successfully completed the login on Google servers.
// Now we have to check for fraud requests and request user information.
// If both Google ID and email can't be found in our DB, register a new user.
// Otherwise, log in the user with the given Google ID or email.
2017-06-07 16:06:57 +00:00
app.Get("/auth/google/callback", func(ctx *aero.Context) string {
2017-06-17 20:19:26 +00:00
if !ctx.HasSession() {
2017-06-17 21:43:57 +00:00
return ctx.Error(http.StatusUnauthorized, "Google login failed", errors.New("Session does not exist"))
2017-06-17 20:19:26 +00:00
}
2017-06-08 21:26:58 +00:00
session := ctx.Session()
if session.ID() != ctx.Query("state") {
2017-06-17 21:43:57 +00:00
return ctx.Error(http.StatusUnauthorized, "Google login failed", errors.New("Incorrect state"))
2017-06-07 16:06:57 +00:00
}
// 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-06-07 19:12:59 +00:00
2017-06-07 16:06:57 +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-06-07 16:06:57 +00:00
2017-06-15 13:50:39 +00:00
// Fetch user data from Google
2019-03-04 02:33:08 +00:00
response, err := client.Get("https://www.googleapis.com/oauth2/v3/userinfo")
2017-06-07 19:12:59 +00:00
2017-06-07 16:06:57 +00:00
if err != nil {
return ctx.Error(http.StatusBadRequest, "Failed requesting user data from Google", err)
}
2017-06-07 19:12:59 +00:00
2019-03-04 02:33:08 +00:00
defer response.Body.Close()
data, _ := ioutil.ReadAll(response.Body)
2017-06-07 19:12:59 +00:00
2017-06-15 13:50:39 +00:00
// Construct a GoogleUser object
2017-06-07 19:12:59 +00:00
var googleUser GoogleUser
2018-07-02 00:39:25 +00:00
err = jsoniter.Unmarshal(data, &googleUser)
2017-06-07 19:12:59 +00:00
if err != nil {
return ctx.Error(http.StatusBadRequest, "Failed parsing user data (JSON)", err)
}
2017-07-12 18:37:34 +00:00
if googleUser.Sub == "" {
return ctx.Error(http.StatusBadRequest, "Failed retrieving Google data", errors.New("Empty ID"))
}
2017-07-02 21:42:46 +00:00
// Change googlemail.com to gmail.com
googleUser.Email = strings.Replace(googleUser.Email, "googlemail.com", "gmail.com", 1)
2017-06-22 20:26:52 +00:00
// Is this an existing user connecting another social account?
user := utils.GetUser(ctx)
if user != nil {
// Add GoogleToUser reference
2017-10-27 07:11:56 +00:00
user.ConnectGoogle(googleUser.Sub)
2017-06-22 20:26:52 +00:00
2017-07-02 22:00:41 +00:00
// Save in DB
user.Save()
// Log
2019-05-07 14:01:51 +00:00
authLog.Info("Added Google ID to existing account | %s | %s | %s | %s | %s", user.Nick, user.ID, ctx.RealIP(), user.Email, user.RealName())
2017-07-02 21:42:46 +00:00
2017-06-22 20:26:52 +00:00
return ctx.Redirect("/")
}
var getErr error
// Try to find an existing user via the Google user ID
2017-10-27 07:11:56 +00:00
user, getErr = arn.GetUserByGoogleID(googleUser.Sub)
2017-06-22 20:26:52 +00:00
if getErr == nil && user != nil {
2019-05-07 14:01:51 +00:00
authLog.Info("User logged in via Google ID | %s | %s | %s | %s | %s", user.Nick, user.ID, ctx.RealIP(), user.Email, user.RealName())
2017-06-22 20:26:52 +00:00
user.LastLogin = arn.DateTimeUTC()
user.Save()
2017-06-15 19:59:14 +00:00
session.Set("userId", user.ID)
return ctx.Redirect("/")
2017-06-07 19:12:59 +00:00
}
2017-06-22 20:26:52 +00:00
// Try to find an existing user via the associated e-mail address
2017-06-15 19:59:14 +00:00
user, getErr = arn.GetUserByEmail(googleUser.Email)
if getErr == nil && user != nil {
2019-05-07 14:01:51 +00:00
authLog.Info("User logged in via Email | %s | %s | %s | %s | %s", user.Nick, user.ID, ctx.RealIP(), user.Email, user.RealName())
2017-06-22 20:26:52 +00:00
// Add GoogleToUser reference
user.ConnectGoogle(googleUser.Sub)
2017-06-22 20:26:52 +00:00
user.LastLogin = arn.DateTimeUTC()
user.Save()
2017-06-15 19:59:14 +00:00
session.Set("userId", user.ID)
return ctx.Redirect("/")
}
2017-06-07 16:06:57 +00:00
2017-06-22 20:26:52 +00:00
// Register new user
user = arn.NewUser()
user.Nick = "g" + googleUser.Sub
user.Email = googleUser.Email
user.FirstName = googleUser.GivenName
user.LastName = googleUser.FamilyName
user.Gender = googleUser.Gender
user.LastLogin = arn.DateTimeUTC()
2017-06-22 20:26:52 +00:00
// 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-06-22 20:26:52 +00:00
// Connect account to a Google account
2017-10-27 07:11:56 +00:00
user.ConnectGoogle(googleUser.Sub)
2017-06-22 20:26:52 +00:00
// Save user object again with updated data
user.Save()
// Login
session.Set("userId", user.ID)
// Log
2019-05-07 14:01:51 +00:00
authLog.Info("Registered new user via Google | %s | %s | %s | %s | %s", user.Nick, user.ID, ctx.RealIP(), user.Email, user.RealName())
2018-06-04 08:18:07 +00:00
// Redirect to starting page for new users
2017-10-06 03:53:49 +00:00
return ctx.Redirect(newUserStartRoute)
2017-06-07 16:06:57 +00:00
})
}