Implemented new user registrations

This commit is contained in:
Eduard Urbach 2017-06-22 22:26:52 +02:00
parent cf0d47bfb0
commit efe8a36b7a
6 changed files with 105 additions and 31 deletions

View File

@ -1,6 +1,7 @@
package auth package auth
import "github.com/aerogo/aero" import "github.com/aerogo/aero"
import "github.com/animenotifier/notify.moe/utils"
// Install ... // Install ...
func Install(app *aero.Application) { func Install(app *aero.Application) {
@ -10,6 +11,12 @@ func Install(app *aero.Application) {
// Logout // Logout
app.Get("/logout", func(ctx *aero.Context) string { app.Get("/logout", func(ctx *aero.Context) string {
if ctx.HasSession() { if ctx.HasSession() {
user := utils.GetUser(ctx)
if user != nil {
authLog.Info("User logged out", user.ID, ctx.RealIP(), user.Email, user.RealName())
}
ctx.Session().Set("userId", nil) ctx.Session().Set("userId", nil)
} }

View File

@ -8,6 +8,7 @@ import (
"github.com/aerogo/aero" "github.com/aerogo/aero"
"github.com/animenotifier/arn" "github.com/animenotifier/arn"
"github.com/animenotifier/notify.moe/utils"
"golang.org/x/oauth2" "golang.org/x/oauth2"
"golang.org/x/oauth2/google" "golang.org/x/oauth2/google"
) )
@ -88,41 +89,86 @@ func InstallGoogleAuth(app *aero.Application) {
return ctx.Error(http.StatusBadRequest, "Failed parsing user data (JSON)", err) return ctx.Error(http.StatusBadRequest, "Failed parsing user data (JSON)", err)
} }
// Try to find an existing user by the Google user ID // Is this an existing user connecting another social account?
user, getErr := arn.GetUserFromTable("GoogleToUser", googleUser.Sub) user := utils.GetUser(ctx)
if user != nil {
println("Connected")
// Add GoogleToUser reference
err = user.ConnectGoogle(googleUser.Sub)
if err != nil {
ctx.Error(http.StatusInternalServerError, "Could not connect account to Google account", err)
}
return ctx.Redirect("/")
}
var getErr error
// Try to find an existing user via the Google user ID
user, getErr = arn.GetUserFromTable("GoogleToUser", googleUser.Sub)
if getErr == nil && user != nil { if getErr == nil && user != nil {
// Add GoogleToUser reference authLog.Info("User logged in via Google ID", user.ID, ctx.RealIP(), user.Email, user.RealName())
user.Accounts.Google.ID = googleUser.Sub
arn.DB.Set("GoogleToUser", googleUser.Sub, &arn.GoogleToUser{ user.LastLogin = arn.DateTimeUTC()
ID: googleUser.Sub, user.Save()
UserID: user.ID,
})
session.Set("userId", user.ID) session.Set("userId", user.ID)
return ctx.Redirect("/") return ctx.Redirect("/")
} }
// Try to find an existing user by the associated e-mail address // Try to find an existing user via the associated e-mail address
user, getErr = arn.GetUserByEmail(googleUser.Email) user, getErr = arn.GetUserByEmail(googleUser.Email)
if getErr == nil && user != nil { if getErr == nil && user != nil {
authLog.Info("User logged in via Email", user.ID, ctx.RealIP(), user.Email, user.RealName())
user.LastLogin = arn.DateTimeUTC()
user.Save()
session.Set("userId", user.ID) session.Set("userId", user.ID)
return ctx.Redirect("/") return ctx.Redirect("/")
} }
// Register new user
user = arn.NewUser() user = arn.NewUser()
user.Nick = "g" + googleUser.Sub user.Nick = "g" + googleUser.Sub
user.Email = googleUser.Email user.Email = googleUser.Email
user.FirstName = googleUser.GivenName user.FirstName = googleUser.GivenName
user.LastName = googleUser.FamilyName user.LastName = googleUser.FamilyName
user.Gender = googleUser.Gender user.Gender = googleUser.Gender
user.Accounts.Google.ID = googleUser.Sub
user.LastLogin = arn.DateTimeUTC() user.LastLogin = arn.DateTimeUTC()
arn.PrettyPrint(user) // Save basic user info already to avoid data inconsistency problems
// arn.RegisterUser(user) user.Save()
return ctx.Error(http.StatusForbidden, "Account does not exist", nil) // Register user
err = arn.RegisterUser(user)
if err != nil {
ctx.Error(http.StatusInternalServerError, "Could not register a new user", err)
}
// Connect account to a Google account
err = user.ConnectGoogle(googleUser.Sub)
if err != nil {
ctx.Error(http.StatusInternalServerError, "Could not connect account to Google account", err)
}
// Save user object again with updated data
user.Save()
// Login
session.Set("userId", user.ID)
// Log
authLog.Info("Registered new user", user.ID, ctx.RealIP(), user.Email, user.RealName())
// Redirect to frontpage
return ctx.Redirect("/")
}) })
} }

14
auth/log.go Normal file
View File

@ -0,0 +1,14 @@
package auth
import (
"os"
"github.com/aerogo/log"
)
var authLog = log.New()
func init() {
authLog.AddOutput(os.Stdout)
authLog.AddOutput(log.File("logs/auth.log"))
}

View File

@ -9,6 +9,7 @@ import (
"github.com/aerogo/aero" "github.com/aerogo/aero"
"github.com/aerogo/log" "github.com/aerogo/log"
"github.com/animenotifier/notify.moe/utils"
) )
// Log middleware logs every request into logs/request.log and errors into logs/error.log. // Log middleware logs every request into logs/request.log and errors into logs/error.log.
@ -27,8 +28,14 @@ func Log() aero.Middleware {
responseTimeString := strconv.Itoa(int(responseTime.Nanoseconds()/1000000)) + " ms" responseTimeString := strconv.Itoa(int(responseTime.Nanoseconds()/1000000)) + " ms"
responseTimeString = strings.Repeat(" ", 8-len(responseTimeString)) + responseTimeString responseTimeString = strings.Repeat(" ", 8-len(responseTimeString)) + responseTimeString
user := utils.GetUser(ctx)
// Log every request // Log every request
request.Info(ctx.RealIP(), ctx.StatusCode, responseTimeString, ctx.URI()) if user != nil {
request.Info(user.Nick, ctx.RealIP(), ctx.StatusCode, responseTimeString, ctx.URI())
} else {
request.Info("[guest]", ctx.RealIP(), ctx.StatusCode, responseTimeString, ctx.URI())
}
// Log all requests that failed // Log all requests that failed
switch ctx.StatusCode { switch ctx.StatusCode {

View File

@ -2,7 +2,6 @@ package middleware
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strings" "strings"
@ -46,8 +45,7 @@ func updateUserInfo(ctx *aero.Context) {
} }
// Ignore non-HTML requests // Ignore non-HTML requests
println(ctx.GetRequestHeader("Accept-Type")) if strings.Index(ctx.GetRequestHeader("Accept"), "text/html") == -1 {
if strings.Index(ctx.GetRequestHeader("Accept-Type"), "text/html") == -1 {
return return
} }
@ -63,37 +61,36 @@ func updateUserInfo(ctx *aero.Context) {
// Browser // Browser
user.Browser.Name, user.Browser.Version = parsed.Browser() user.Browser.Name, user.Browser.Version = parsed.Browser()
arn.PrettyPrint(user.Browser)
// OS // OS
os := parsed.OSInfo() os := parsed.OSInfo()
user.OS.Name = os.Name user.OS.Name = os.Name
user.OS.Version = os.Version user.OS.Version = os.Version
arn.PrettyPrint(user.OS)
} }
if user.IP != newIP { if user.IP != newIP {
user.IP = newIP user.IP = newIP
locationAPI := "https://api.ipinfodb.com/v3/ip-city/?key=" + apiKeys.IPInfoDB.ID + "&ip=" + "2a02:8108:8dc0:3000:6cf1:af03:ce6e:679a" + "&format=json" locationAPI := "https://api.ipinfodb.com/v3/ip-city/?key=" + apiKeys.IPInfoDB.ID + "&ip=" + user.IP + "&format=json"
response, data, err := gorequest.New().Get(locationAPI).EndBytes() response, data, err := gorequest.New().Get(locationAPI).EndBytes()
if len(err) > 0 && err[0] != nil { if len(err) > 0 && err[0] != nil {
color.Red(err[0].Error()) color.Red("Couldn't fetch location data | Error: %s | IP: %s", err[0].Error(), user.IP)
return return
} }
if response.StatusCode != http.StatusOK { if response.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(response.Body) color.Red("Couldn't fetch location data | Status: %d | IP: %s", response.StatusCode, user.IP)
fmt.Println(response.StatusCode, locationAPI)
fmt.Println(string(body))
return return
} }
json.Unmarshal(data, &user.Location) newLocation := arn.UserLocation{}
arn.PrettyPrint(user.Location) json.Unmarshal(data, &newLocation)
if newLocation.CountryName != "-" {
user.Location = newLocation
}
} }
// user.Save() user.LastSeen = arn.DateTimeUTC()
user.Save()
} }

View File

@ -11,5 +11,8 @@ component Forum(tag string, threads []*arn.Thread, threadsPerPage int)
span Load more span Load more
component ThreadList(threads []*arn.Thread) component ThreadList(threads []*arn.Thread)
if len(threads) == 0
p No threads found.
else
each thread in threads each thread in threads
ThreadLink(thread) ThreadLink(thread)