if already logged in return on login func and generate cookie for newly created users -- ensure all redirect to index

This commit is contained in:
grumbulon 2023-01-06 22:37:52 -05:00 committed by Gitea
parent 6e8f401e70
commit e363c83009
3 changed files with 40 additions and 5 deletions

View file

@ -14,7 +14,26 @@ import (
func Login(w http.ResponseWriter, r *http.Request) {
var result internal.User
err := r.ParseForm()
if _, err := r.Cookie("jwt"); err == nil {
http.Error(w, "Logged in", http.StatusCreated)
return
}
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(
internal.Response{
Message: "Successfully logged in",
HTTPResponse: 200,
})
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
err = r.ParseForm()
if err != nil {
http.Error(w, "Unable to parse request", http.StatusInternalServerError)
@ -107,6 +126,7 @@ func Logout(w http.ResponseWriter, r *http.Request) {
Message: "Successfully logged out",
HTTPResponse: 200,
})
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)

View file

@ -6,6 +6,7 @@ import (
"fmt"
"math/big"
"net/http"
"time"
"git.freecumextremist.com/grumbulon/pomme/internal"
"golang.org/x/crypto/bcrypt"
@ -59,12 +60,26 @@ func NewUser(w http.ResponseWriter, r *http.Request) {
db.Create(&internal.User{Username: username, HashedPassword: string(hashedPassword)})
w.Header().Set("Content-Type", "application/json")
token := makeToken(username)
http.SetCookie(w, &http.Cookie{
HttpOnly: true,
Expires: time.Now().Add(1 * time.Hour),
MaxAge: 3600,
SameSite: http.SameSiteLaxMode,
// Uncomment below for HTTPS:
// Secure: true,
Name: "jwt", // Must be named "jwt" or else the token cannot be searched for by jwtauth.Verifier.
Value: token,
})
w.WriteHeader(http.StatusCreated)
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(
internal.Response{
Username: username,
HTTPResponse: http.StatusCreated,
Message: "Successfully created account and logged in",
})
if err != nil {
@ -72,6 +87,7 @@ func NewUser(w http.ResponseWriter, r *http.Request) {
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func autoUname() string {

View file

@ -74,9 +74,8 @@ func RecieveFile(w http.ResponseWriter, r *http.Request) {
db.Create(zoneReq)
err = zoneReq.Parse()
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
if err = zoneReq.Parse(); err != nil {
http.Error(w, fmt.Sprintf("unable to parse zonefile: %v", err), http.StatusInternalServerError)
return
}