Implement user setup for Google OAuth2 unregistered users
This commit is contained in:
@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"github.com/fossyy/filekeeper/cache"
|
||||
"github.com/fossyy/filekeeper/db"
|
||||
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
|
||||
signinHandler "github.com/fossyy/filekeeper/handler/signin"
|
||||
"github.com/fossyy/filekeeper/logger"
|
||||
"github.com/fossyy/filekeeper/session"
|
||||
@ -70,7 +71,7 @@ func init() {
|
||||
|
||||
for _, data := range CsrfTokens {
|
||||
data.mu.Lock()
|
||||
if currentTime.Sub(data.CreateTime) > time.Minute-10 {
|
||||
if currentTime.Sub(data.CreateTime) > time.Minute*10 {
|
||||
delete(CsrfTokens, data.Token)
|
||||
cacheClean++
|
||||
}
|
||||
@ -133,7 +134,13 @@ func GET(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if !db.DB.IsUserRegistered(oauthUser.Email, "ll") {
|
||||
http.Redirect(w, r, "/signup", http.StatusSeeOther)
|
||||
code := utils.GenerateRandomString(64)
|
||||
googleOauthSetupHandler.SetupUser[code] = &googleOauthSetupHandler.UnregisteredUser{
|
||||
Code: code,
|
||||
Email: oauthUser.Email,
|
||||
CreateTime: time.Now(),
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/auth/google/setup/%s", code), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
|
159
handler/auth/google/setup/setup.go
Normal file
159
handler/auth/google/setup/setup.go
Normal file
@ -0,0 +1,159 @@
|
||||
package googleOauthSetupHandler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/fossyy/filekeeper/db"
|
||||
signinHandler "github.com/fossyy/filekeeper/handler/signin"
|
||||
"github.com/fossyy/filekeeper/logger"
|
||||
"github.com/fossyy/filekeeper/session"
|
||||
"github.com/fossyy/filekeeper/types"
|
||||
"github.com/fossyy/filekeeper/types/models"
|
||||
"github.com/fossyy/filekeeper/utils"
|
||||
authView "github.com/fossyy/filekeeper/view/auth"
|
||||
signupView "github.com/fossyy/filekeeper/view/signup"
|
||||
"github.com/google/uuid"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type UnregisteredUser struct {
|
||||
Code string
|
||||
Email string
|
||||
CreateTime time.Time
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var log *logger.AggregatedLogger
|
||||
var SetupUser map[string]*UnregisteredUser
|
||||
|
||||
func init() {
|
||||
log = logger.Logger()
|
||||
SetupUser = make(map[string]*UnregisteredUser)
|
||||
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
go func() {
|
||||
for {
|
||||
<-ticker.C
|
||||
currentTime := time.Now()
|
||||
cacheClean := 0
|
||||
cleanID := utils.GenerateRandomString(10)
|
||||
log.Info(fmt.Sprintf("Cache cleanup [GoogleSetup] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
|
||||
|
||||
for _, data := range SetupUser {
|
||||
data.mu.Lock()
|
||||
if currentTime.Sub(data.CreateTime) > time.Minute*10 {
|
||||
delete(SetupUser, data.Code)
|
||||
cacheClean++
|
||||
}
|
||||
|
||||
data.mu.Unlock()
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("Cache cleanup [GoogleSetup] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func GET(w http.ResponseWriter, r *http.Request) {
|
||||
code := r.PathValue("code")
|
||||
if _, ok := SetupUser[code]; !ok {
|
||||
http.Redirect(w, r, "/signup", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
component := authView.GoogleSetup("Setup page", types.Message{
|
||||
Code: 3,
|
||||
Message: "",
|
||||
})
|
||||
err := component.Render(r.Context(), w)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
log.Error(err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func POST(w http.ResponseWriter, r *http.Request) {
|
||||
code := r.PathValue("code")
|
||||
unregisteredUser, ok := SetupUser[code]
|
||||
if !ok {
|
||||
http.Error(w, "Unauthorized Action", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
err := r.ParseForm()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
log.Error(err.Error())
|
||||
return
|
||||
}
|
||||
username := r.Form.Get("username")
|
||||
password := r.Form.Get("password")
|
||||
|
||||
isValid := utils.ValidatePassword(password)
|
||||
if !isValid {
|
||||
component := authView.GoogleSetup("Setup page", types.Message{
|
||||
Code: 0,
|
||||
Message: "Password is invalid",
|
||||
})
|
||||
err := component.Render(r.Context(), w)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
log.Error(err.Error())
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword, err := utils.HashPassword(password)
|
||||
userID := uuid.New()
|
||||
newUser := models.User{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
Email: unregisteredUser.Email,
|
||||
Password: hashedPassword,
|
||||
}
|
||||
|
||||
err = db.DB.CreateUser(&newUser)
|
||||
if err != nil {
|
||||
component := signupView.Main("Sign up Page", types.Message{
|
||||
Code: 0,
|
||||
Message: "Email or Username has been registered",
|
||||
})
|
||||
err := component.Render(r.Context(), w)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
log.Error(err.Error())
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
delete(SetupUser, code)
|
||||
|
||||
storeSession := session.GlobalSessionStore.Create()
|
||||
storeSession.Values["user"] = types.User{
|
||||
UserID: userID,
|
||||
Email: unregisteredUser.Email,
|
||||
Username: username,
|
||||
Authenticated: true,
|
||||
}
|
||||
|
||||
userAgent := r.Header.Get("User-Agent")
|
||||
browserInfo, osInfo := signinHandler.ParseUserAgent(userAgent)
|
||||
|
||||
sessionInfo := session.SessionInfo{
|
||||
SessionID: storeSession.ID,
|
||||
Browser: browserInfo["browser"],
|
||||
Version: browserInfo["version"],
|
||||
OS: osInfo["os"],
|
||||
OSVersion: osInfo["version"],
|
||||
IP: utils.ClientIP(r),
|
||||
Location: "Indonesia",
|
||||
}
|
||||
|
||||
storeSession.Save(w)
|
||||
session.AddSessionInfo(unregisteredUser.Email, &sessionInfo)
|
||||
|
||||
http.Redirect(w, r, "/user", http.StatusSeeOther)
|
||||
return
|
||||
}
|
@ -3,6 +3,7 @@ package routes
|
||||
import (
|
||||
googleOauthHandler "github.com/fossyy/filekeeper/handler/auth/google"
|
||||
googleOauthCallbackHandler "github.com/fossyy/filekeeper/handler/auth/google/callback"
|
||||
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
|
||||
downloadHandler "github.com/fossyy/filekeeper/handler/download"
|
||||
downloadFileHandler "github.com/fossyy/filekeeper/handler/download/file"
|
||||
forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword"
|
||||
@ -58,15 +59,16 @@ func SetupRoutes() *http.ServeMux {
|
||||
}
|
||||
})
|
||||
|
||||
//TODO make a setup route for unregistered google oauth user
|
||||
//authRouter.HandleFunc("/google/setup", func(w http.ResponseWriter, r *http.Request) {
|
||||
// switch r.Method {
|
||||
// case http.MethodGet:
|
||||
// middleware.Guest(googleOauthSetupHandler.GET, w, r)
|
||||
// default:
|
||||
// http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
// }
|
||||
//})
|
||||
authRouter.HandleFunc("/google/setup/{code}", func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
middleware.Guest(googleOauthSetupHandler.GET, w, r)
|
||||
case http.MethodPost:
|
||||
middleware.Guest(googleOauthSetupHandler.POST, w, r)
|
||||
default:
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
})
|
||||
|
||||
handler.HandleFunc("/signin", func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
|
90
view/auth/auth.templ
Normal file
90
view/auth/auth.templ
Normal file
@ -0,0 +1,90 @@
|
||||
package authView
|
||||
|
||||
import (
|
||||
"github.com/fossyy/filekeeper/types"
|
||||
"github.com/fossyy/filekeeper/view/layout"
|
||||
)
|
||||
|
||||
templ form(err types.Message, title string) {
|
||||
@layout.Base(title){
|
||||
<div class="dark flex items-center min-h-screen p-4 sm:p-6 bg-gray-900">
|
||||
<div class="mx-auto w-full max-w-md space-y-8">
|
||||
<header class="text-center">
|
||||
<div class="space-y-2">
|
||||
<h1 class="text-3xl font-bold text-white">Sign Up</h1>
|
||||
<p class="text-gray-500 dark:text-gray-400">Enter your email below to login to your account</p>
|
||||
switch err.Code {
|
||||
case 0:
|
||||
<div class="p-4 mb-4 text-sm text-red-800 rounded-lg bg-red-50 dark:bg-gray-800 dark:text-red-400" role="alert">
|
||||
<span class="font-medium">Danger alert!</span> {err.Message}
|
||||
</div>
|
||||
case 1:
|
||||
<div class="p-4 mb-4 text-sm text-green-800 rounded-lg bg-green-50 dark:bg-gray-800 dark:text-green-400" role="alert">
|
||||
<span class="font-medium">Success alert!</span> {err.Message}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
<form class="space-y-4" method="post" action="">
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-white" for="username">Username</label>
|
||||
<input type="text" class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-gray-800 dark:text-white" id="username" name="username" required="" />
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-white" for="password">Password</label>
|
||||
<input type="password" class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-gray-800 dark:text-white" id="password" name="password" required />
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-white" for="confirmPassword">Confirm Password</label>
|
||||
<input type="password" class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-gray-800 dark:text-white" id="confirmPassword" required />
|
||||
</div>
|
||||
<div class="flex justify-start mt-3 ml-4 p-1">
|
||||
<ul>
|
||||
<li class="flex items-center py-1">
|
||||
<div id="matchSvgContainer" class="rounded-full p-1 fill-current bg-red-200 text-green-700">
|
||||
<svg id="matchSvgIcon" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path id="matchGoodPath" style="display: none;" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||
<path id="matchBadPath" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<span id="matchStatusText" class="font-medium text-sm ml-3 text-red-700"> Passwords do not match</span>
|
||||
</li>
|
||||
<li class="flex items-center py-1">
|
||||
<div id="lengthSvgContainer" class="rounded-full p-1 fill-current bg-red-200 text-green-700">
|
||||
<svg id="lengthSvgIcon" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path id="lengthGoodPath" style="display: none;" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||
<path id="lengthBadPath" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<span id="lengthStatusText" class="font-medium text-sm ml-3 text-red-700"> Password length must be at least 8 characters</span>
|
||||
</li>
|
||||
<li class="flex items-center py-1">
|
||||
<div id="requirementsSvgContainer" class="rounded-full p-1 fill-current bg-red-200 text-green-700">
|
||||
<svg id="requirementsSvgIcon" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path id="requirementsGoodPath" style="display: none;" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||
<path id="requirementsBadPath" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<span id="requirementsStatusText" class="font-medium text-sm ml-3 text-red-700">The password must contain at least one symbol (!@#$%^&*), one uppercase letter, and three numbers</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="bg-slate-200 inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2 w-full" type="submit" id="submit" name="submit" disabled>
|
||||
Sign up
|
||||
</button>
|
||||
</form>
|
||||
<div class="text-center text-sm text-white">
|
||||
Already have an account?
|
||||
<a class="underline" href="/signin" rel="ugc">
|
||||
Sign in
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/public/validatePassword.js" />
|
||||
}
|
||||
}
|
||||
|
||||
templ GoogleSetup(title string, err types.Message) {
|
||||
@form(err, title)
|
||||
}
|
Reference in New Issue
Block a user