mercury/web/auth/signup.go

68 lines
1.8 KiB
Go
Raw Permalink Normal View History

2023-09-04 03:33:13 +02:00
package auth
import (
"net/http"
"git.sleepycat.moe/sam/mercury/internal/database/sql"
"github.com/flosch/pongo2/v6"
"github.com/rs/zerolog/log"
)
func (app *Auth) GetSignup(w http.ResponseWriter, r *http.Request) {
app.Template(w, r, "auth/signup.tpl", pongo2.Context{})
}
func (app *Auth) PostSignup(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
username := r.FormValue("username")
email := r.FormValue("email")
password := r.FormValue("password")
password2 := r.FormValue("repeat_password")
if username == "" {
app.Template(w, r, "auth/signup.tpl", pongo2.Context{"flash_message": "Username cannot be empty."})
return
} else if password == "" {
app.Template(w, r, "auth/signup.tpl", pongo2.Context{"flash_message": "Password cannot be empty."})
return
} else if password != password2 {
app.Template(w, r, "auth/signup.tpl", pongo2.Context{"flash_message": "Passwords don't match."})
return
} else if email == "" {
app.Template(w, r, "auth/signup.tpl", pongo2.Context{"flash_message": "Email address cannot be empty."})
return
}
tx, err := app.Database.BeginTx(ctx)
if err != nil {
log.Err(err).Msg("acquiring database connection")
return
}
defer tx.Rollback(ctx)
acct, err := app.Account(tx).CreateLocal(ctx, username, email, []byte(password))
if err != nil {
if err == sql.ErrUsernameTaken {
app.Template(w, r, "auth/signup.tpl", pongo2.Context{"flash_message": "Username is already taken."})
return
}
log.Err(err).Msg("creating account")
return
}
_, err = app.Blog(tx).Create(ctx, acct.ID, username)
if err != nil {
log.Err(err).Msg("creating blog")
return
}
err = tx.Commit(ctx)
if err != nil {
log.Err(err).Msg("committing transaction")
return
}
app.Flash(w, "Successfully created account!")
http.Redirect(w, r, "/auth/login", http.StatusSeeOther)
}