finished login/registration
This commit is contained in:
@@ -5,7 +5,6 @@ import (
|
||||
"time"
|
||||
|
||||
"git.haelnorr.com/h/oslstats/internal/discord"
|
||||
"github.com/bwmarrin/discordgo"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
@@ -19,10 +18,7 @@ type DiscordToken struct {
|
||||
ExpiresAt int64 `bun:"expires_at,notnull"`
|
||||
}
|
||||
|
||||
func UpdateDiscordToken(ctx context.Context, db *bun.DB, user *discordgo.User, token *discord.Token) error {
|
||||
if db == nil {
|
||||
return errors.New("db cannot be nil")
|
||||
}
|
||||
func UpdateDiscordToken(ctx context.Context, tx bun.Tx, user *User, token *discord.Token) error {
|
||||
if user == nil {
|
||||
return errors.New("user cannot be nil")
|
||||
}
|
||||
@@ -32,13 +28,13 @@ func UpdateDiscordToken(ctx context.Context, db *bun.DB, user *discordgo.User, t
|
||||
expiresAt := time.Now().Add(time.Duration(token.ExpiresIn) * time.Second).Unix()
|
||||
|
||||
discordToken := &DiscordToken{
|
||||
DiscordID: user.ID,
|
||||
DiscordID: user.DiscordID,
|
||||
AccessToken: token.AccessToken,
|
||||
RefreshToken: token.RefreshToken,
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
|
||||
_, err := db.NewInsert().
|
||||
_, err := tx.NewInsert().
|
||||
Model(discordToken).
|
||||
On("CONFLICT (discord_id) DO UPDATE").
|
||||
Set("access_token = EXCLUDED.access_token").
|
||||
@@ -46,5 +42,8 @@ func UpdateDiscordToken(ctx context.Context, db *bun.DB, user *discordgo.User, t
|
||||
Set("expires_at = EXCLUDED.expires_at").
|
||||
Exec(ctx)
|
||||
|
||||
return err
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "tx.NewInsert")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.haelnorr.com/h/golib/hwsauth"
|
||||
@@ -63,6 +64,7 @@ func CreateUser(ctx context.Context, tx bun.Tx, username string, discorduser *di
|
||||
// GetUserByID queries the database for a user matching the given ID
|
||||
// Returns nil, nil if no user is found
|
||||
func GetUserByID(ctx context.Context, tx bun.Tx, id int) (*User, error) {
|
||||
fmt.Printf("user id requested: %v", id)
|
||||
user := new(User)
|
||||
err := tx.NewSelect().
|
||||
Model(user).
|
||||
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.haelnorr.com/h/golib/cookies"
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
"git.haelnorr.com/h/golib/hwsauth"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/uptrace/bun"
|
||||
|
||||
@@ -16,7 +18,14 @@ import (
|
||||
"git.haelnorr.com/h/oslstats/pkg/oauth"
|
||||
)
|
||||
|
||||
func Callback(server *hws.Server, conn *bun.DB, cfg *config.Config, store *store.Store, discordAPI *discord.APIClient) http.Handler {
|
||||
func Callback(
|
||||
server *hws.Server,
|
||||
auth *hwsauth.Authenticator[*db.User, bun.Tx],
|
||||
conn *bun.DB,
|
||||
cfg *config.Config,
|
||||
store *store.Store,
|
||||
discordAPI *discord.APIClient,
|
||||
) http.Handler {
|
||||
return http.HandlerFunc(
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
// Track callback redirect attempts
|
||||
@@ -86,7 +95,7 @@ func Callback(server *hws.Server, conn *bun.DB, cfg *config.Config, store *store
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
redirect, err := login(ctx, tx, cfg, w, r, code, store, discordAPI)
|
||||
redirect, err := login(ctx, auth, tx, cfg, w, r, code, store, discordAPI)
|
||||
if err != nil {
|
||||
throwInternalServiceError(server, w, r, "OAuth login failed", err)
|
||||
return
|
||||
@@ -152,6 +161,7 @@ func verifyState(
|
||||
|
||||
func login(
|
||||
ctx context.Context,
|
||||
auth *hwsauth.Authenticator[*db.User, bun.Tx],
|
||||
tx bun.Tx,
|
||||
cfg *config.Config,
|
||||
w http.ResponseWriter,
|
||||
@@ -194,7 +204,11 @@ func login(
|
||||
})
|
||||
redirect = "/register"
|
||||
} else {
|
||||
// TODO: log them in
|
||||
err := auth.Login(w, r, user, true)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "auth.Login")
|
||||
}
|
||||
redirect = cookies.CheckPageFrom(w, r)
|
||||
}
|
||||
return func() {
|
||||
http.Redirect(w, r, redirect, http.StatusSeeOther)
|
||||
|
||||
@@ -3,6 +3,7 @@ package handlers
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.haelnorr.com/h/golib/cookies"
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
func Login(server *hws.Server, cfg *config.Config, st *store.Store, discordAPI *discord.APIClient) http.Handler {
|
||||
return http.HandlerFunc(
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
cookies.SetPageFrom(w, r, cfg.HWSAuth.TrustedHost)
|
||||
// Track login redirect attempts
|
||||
attempts, exceeded, track := st.TrackRedirect(r, "/login", 5)
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.haelnorr.com/h/golib/cookies"
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
"git.haelnorr.com/h/golib/hwsauth"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/uptrace/bun"
|
||||
|
||||
@@ -17,6 +19,7 @@ import (
|
||||
|
||||
func Register(
|
||||
server *hws.Server,
|
||||
auth *hwsauth.Authenticator[*db.User, bun.Tx],
|
||||
conn *bun.DB,
|
||||
cfg *config.Config,
|
||||
store *store.Store,
|
||||
@@ -56,7 +59,6 @@ func Register(
|
||||
return
|
||||
}
|
||||
details, ok := store.GetRegistrationSession(sessionCookie.Value)
|
||||
ok = false
|
||||
if !ok {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
@@ -73,20 +75,27 @@ func Register(
|
||||
defer tx.Rollback()
|
||||
method := r.Method
|
||||
if method == "GET" {
|
||||
unique, err := db.IsUsernameUnique(ctx, tx, details.DiscordUser.Username)
|
||||
if err != nil {
|
||||
throwInternalServiceError(server, w, r, "Database query failed", err)
|
||||
return
|
||||
}
|
||||
tx.Commit()
|
||||
page.Register(details.DiscordUser.Username, unique).Render(r.Context(), w)
|
||||
page.Register(details.DiscordUser.Username).Render(r.Context(), w)
|
||||
return
|
||||
}
|
||||
if method == "POST" {
|
||||
// TODO: register the user
|
||||
|
||||
// get the form data
|
||||
//
|
||||
username := r.FormValue("username")
|
||||
user, err := registerUser(ctx, tx, username, details)
|
||||
if err != nil {
|
||||
throwInternalServiceError(server, w, r, "Registration failed", err)
|
||||
}
|
||||
tx.Commit()
|
||||
if user == nil {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
} else {
|
||||
err = auth.Login(w, r, user, true)
|
||||
if err != nil {
|
||||
throwInternalServiceError(server, w, r, "Login failed", err)
|
||||
}
|
||||
pageFrom := cookies.CheckPageFrom(w, r)
|
||||
w.Header().Set("HX-Redirect", pageFrom)
|
||||
}
|
||||
return
|
||||
}
|
||||
},
|
||||
@@ -124,3 +133,27 @@ func IsUsernameUnique(
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func registerUser(
|
||||
ctx context.Context,
|
||||
tx bun.Tx,
|
||||
username string,
|
||||
details *store.RegistrationSession,
|
||||
) (*db.User, error) {
|
||||
unique, err := db.IsUsernameUnique(ctx, tx, username)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "db.IsUsernameUnique")
|
||||
}
|
||||
if !unique {
|
||||
return nil, nil
|
||||
}
|
||||
user, err := db.CreateUser(ctx, tx, username, details.DiscordUser)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "db.CreateUser")
|
||||
}
|
||||
err = db.UpdateDiscordToken(ctx, tx, user, details.Token)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "db.UpdateDiscordToken")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
@@ -1,25 +1,42 @@
|
||||
package form
|
||||
|
||||
templ RegisterForm(username, registerError string) {
|
||||
{{ usernameErr := "Username is taken" }}
|
||||
templ RegisterForm(username string) {
|
||||
<form
|
||||
hx-post="/register"
|
||||
x-data={ templ.JSFuncCall(
|
||||
"registerFormData", registerError, usernameErr,
|
||||
).CallInline }
|
||||
x-on:htmx:xhr:loadstart="submitted=true;buttontext='Loading...'"
|
||||
hx-swap="none"
|
||||
x-data={ templ.JSFuncCall("registerFormData").CallInline }
|
||||
@submit="handleSubmit()"
|
||||
@htmx:after-request="if(submitTimeout) clearTimeout(submitTimeout); if(!$event.detail.successful) { isSubmitting=false; buttontext='Register'; if($event.detail.xhr.status === 409) { errorMessage='Username is already taken'; isUnique=false; } else { errorMessage='An error occurred. Please try again.'; } }"
|
||||
>
|
||||
<script>
|
||||
function registerFormData(err, usernameErr) {
|
||||
function registerFormData() {
|
||||
return {
|
||||
submitted: false,
|
||||
canSubmit: false,
|
||||
buttontext: "Register",
|
||||
errorMessage: err,
|
||||
errUsername: err === usernameErr ? true : false,
|
||||
errorMessage: "",
|
||||
isChecking: false,
|
||||
isUnique: false,
|
||||
isEmpty: true,
|
||||
isSubmitting: false,
|
||||
submitTimeout: null,
|
||||
resetErr() {
|
||||
this.errorMessage = "";
|
||||
this.errUsername = false;
|
||||
this.isChecking = false;
|
||||
this.isUnique = false;
|
||||
},
|
||||
enableSubmit() {
|
||||
this.canSubmit = true;
|
||||
},
|
||||
handleSubmit() {
|
||||
this.isSubmitting = true;
|
||||
this.buttontext = 'Loading...';
|
||||
// Set timeout for 10 seconds
|
||||
this.submitTimeout = setTimeout(() => {
|
||||
this.isSubmitting = false;
|
||||
this.buttontext = 'Register';
|
||||
this.errorMessage = 'Request timed out. Please try again.';
|
||||
}, 10000);
|
||||
}
|
||||
};
|
||||
}
|
||||
</script>
|
||||
@@ -32,48 +49,34 @@ templ RegisterForm(username, registerError string) {
|
||||
type="text"
|
||||
id="username"
|
||||
name="username"
|
||||
class="py-3 px-4 block w-full rounded-lg text-sm
|
||||
focus:border-blue focus:ring-blue bg-base
|
||||
disabled:opacity-50
|
||||
disabled:pointer-events-none"
|
||||
x-bind:class="{
|
||||
'py-3 px-4 block w-full rounded-lg text-sm bg-base disabled:opacity-50 disabled:pointer-events-none border-2 outline-none': true,
|
||||
'border-overlay0 focus:border-blue': !isUnique && !errorMessage,
|
||||
'border-green focus:border-green': isUnique && !isChecking && !errorMessage,
|
||||
'border-red focus:border-red': errorMessage && !isChecking
|
||||
}"
|
||||
required
|
||||
aria-describedby="username-error"
|
||||
value={ username }
|
||||
@input="resetErr()"
|
||||
@input="resetErr(); isEmpty = $el.value.trim() === ''; if(isEmpty) { errorMessage='Username is required'; isUnique=false; }"
|
||||
hx-post="/htmx/isusernameunique"
|
||||
hx-trigger="load delay:100ms, input changed delay:500ms"
|
||||
hx-swap="none"
|
||||
@htmx:before-request="if($el.value.trim() === '') { isEmpty=true; return; } isEmpty=false; isChecking=true; isUnique=false; errorMessage=''"
|
||||
@htmx:after-request="isChecking=false; if($event.detail.successful) { isUnique=true; canSubmit=true; } else if($event.detail.xhr.status === 409) { errorMessage='Username is already taken'; isUnique=false; canSubmit=false; }"
|
||||
/>
|
||||
<div
|
||||
class="absolute inset-y-0 end-0
|
||||
pointer-events-none pe-3 pt-3"
|
||||
x-show="errUsername"
|
||||
x-cloak
|
||||
>
|
||||
<svg
|
||||
class="size-5 text-red"
|
||||
width="16"
|
||||
height="16"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 16 16"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM8
|
||||
4a.905.905 0 0 0-.9.995l.35 3.507a.552.552 0 0
|
||||
0 1.1 0l.35-3.507A.905.905 0 0 0 8 4zm.002 6a1
|
||||
1 0 1 0 0 2 1 1 0 0 0 0-2z"
|
||||
></path>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<p
|
||||
class="text-center text-xs text-red mt-2"
|
||||
id="username-error"
|
||||
x-show="errUsername"
|
||||
x-show="errorMessage"
|
||||
x-cloak
|
||||
x-text="if (errUsername) return errorMessage;"
|
||||
x-text="errorMessage"
|
||||
></p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
x-bind:disabled="submitted"
|
||||
x-bind:disabled="isEmpty || !isUnique || isChecking || isSubmitting"
|
||||
x-text="buttontext"
|
||||
type="submit"
|
||||
class="w-full py-3 px-4 inline-flex justify-center items-center
|
||||
|
||||
@@ -4,13 +4,7 @@ import "git.haelnorr.com/h/oslstats/internal/view/layout"
|
||||
import "git.haelnorr.com/h/oslstats/internal/view/component/form"
|
||||
|
||||
// Returns the login page
|
||||
templ Register(username string, unique bool) {
|
||||
{{
|
||||
err := ""
|
||||
if !unique {
|
||||
err = "Username is taken"
|
||||
}
|
||||
}}
|
||||
templ Register(username string) {
|
||||
@layout.Global("Register") {
|
||||
<div class="max-w-100 mx-auto px-2">
|
||||
<div class="mt-7 bg-mantle border border-surface1 rounded-xl">
|
||||
@@ -26,7 +20,7 @@ templ Register(username string, unique bool) {
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-5">
|
||||
@form.RegisterForm(username, err)
|
||||
@form.RegisterForm(username)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user