2024-03-25 15:52:18 +05:00
|
|
|
package pages
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
2024-03-26 01:15:51 +05:00
|
|
|
"strings"
|
2024-03-25 15:52:18 +05:00
|
|
|
|
|
|
|
"github.com/ordinary-dev/phoenix/database"
|
|
|
|
"github.com/ordinary-dev/phoenix/jwttoken"
|
|
|
|
)
|
|
|
|
|
|
|
|
func ShowRegistrationForm(w http.ResponseWriter, _ *http.Request) {
|
2024-03-26 00:40:52 +05:00
|
|
|
userCount, err := database.CountAdmins()
|
|
|
|
if err != nil {
|
|
|
|
ShowError(w, http.StatusInternalServerError, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if userCount > 0 {
|
2024-03-25 15:52:18 +05:00
|
|
|
ShowError(w, http.StatusBadRequest, errors.New("at least 1 user already exists"))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
Render("auth.html.tmpl", w, map[string]any{
|
|
|
|
"title": "Create an account",
|
|
|
|
"description": "To prevent other people from seeing your links, create an account.",
|
|
|
|
"button": "Create",
|
|
|
|
"formAction": "/registration",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func CreateUser(w http.ResponseWriter, r *http.Request) {
|
2024-03-26 00:40:52 +05:00
|
|
|
userCount, err := database.CountAdmins()
|
|
|
|
if err != nil {
|
|
|
|
ShowError(w, http.StatusInternalServerError, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if userCount > 0 {
|
2024-03-25 15:52:18 +05:00
|
|
|
ShowError(w, http.StatusBadRequest, errors.New("at least 1 user already exists"))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try to create a user.
|
2024-03-26 01:15:51 +05:00
|
|
|
username := strings.TrimSpace(r.FormValue("username"))
|
|
|
|
password := strings.TrimSpace(r.FormValue("password"))
|
2024-03-26 00:40:52 +05:00
|
|
|
_, err = database.CreateAdmin(username, password)
|
2024-03-25 15:52:18 +05:00
|
|
|
if err != nil {
|
|
|
|
ShowError(w, http.StatusInternalServerError, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate access token.
|
|
|
|
token, err := jwttoken.GetJWTToken()
|
|
|
|
if err != nil {
|
|
|
|
ShowError(w, http.StatusInternalServerError, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
http.SetCookie(w, jwttoken.TokenToCookie(token))
|
|
|
|
|
|
|
|
// Redirect to homepage.
|
|
|
|
http.Redirect(w, r, "/", http.StatusFound)
|
|
|
|
}
|