adding error returns or else bad things happen and adding max cookie age of 1 hr

This commit is contained in:
grumbulon 2023-01-05 19:15:15 -05:00
parent e5bf6169d8
commit c005016cb2
2 changed files with 16 additions and 1 deletions

View file

@ -25,8 +25,16 @@ func Login(w http.ResponseWriter, r *http.Request) {
password := r.Form.Get("password")
if username == "" {
http.Error(w, "No username provided", http.StatusInternalServerError) // this should prob be handled by the frontend
return
}
if password == "" {
http.Error(w, "No password provided", http.StatusInternalServerError) // this should prob be handled by the frontend
return
}
db, ok := r.Context().Value(keyPrincipalContextID).(*gorm.DB)
@ -37,11 +45,13 @@ func Login(w http.ResponseWriter, r *http.Request) {
}
db.Where("username = ?", username).First(&result)
if result.Username == "" {
http.Error(w, "login failed", http.StatusUnauthorized)
return
}
err = bcrypt.CompareHashAndPassword([]byte(result.HashedPassword), []byte(password))
if err != nil {
@ -54,7 +64,8 @@ func Login(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
HttpOnly: true,
Expires: time.Now().Add(7 * 24 * time.Hour),
Expires: time.Now().Add(1 * time.Hour),
MaxAge: 3600,
SameSite: http.SameSiteLaxMode,
// Uncomment below for HTTPS:
// Secure: true,

View file

@ -38,6 +38,8 @@ func NewUser(w http.ResponseWriter, r *http.Request) {
if password == "" {
http.Error(w, "No password entered", http.StatusInternalServerError)
return
}
db.Where("username = ?", username).First(&result)
@ -51,6 +53,8 @@ func NewUser(w http.ResponseWriter, r *http.Request) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
db.Create(&internal.User{Username: username, HashedPassword: string(hashedPassword)})