pomme/internal/api/auth.go
Sam Therapy 5d52caab70
fix(backend): make cookie more strict
THIS IS STILL NOT ENOUGH!

Signed-off-by: Sam Therapy <sam@samtherapy.net>
2023-02-20 18:05:09 +01:00

137 lines
3.4 KiB
Go

package api
import (
"net/http"
"time"
"dns.froth.zone/pomme/internal"
"github.com/go-chi/render"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
// Auth godoc
//
// @Summary authenticate as a regular user
// @Description login to Pomme
//
// @Description Rate limited: 5 requests every 5 second
//
// @Tags accounts
// @Accept json
// @Produce json
// @Param username query string true "Username"
// @Param password query string true "Password"
// @Success 200 {object} internal.SwaggerGenericResponse[internal.Response]
// @failure 401 {object} internal.SwaggerGenericResponse[internal.Response] "authFailed is a 401 error when logging in fails, includes realm"
// @Router /api/login [post]
func Login(w http.ResponseWriter, r *http.Request) {
var result internal.User
if _, err := r.Cookie("jwt"); err == nil {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
resp := internal.Response{
Message: "Already logged in",
}
render.JSON(w, r, resp)
return
}
err := r.ParseForm()
if err != nil {
APIError(w, r, genericResponseFields{"message": "internal server error", "status": http.StatusInternalServerError, "error": err.Error()})
return
}
username := r.Form.Get("username")
password := r.Form.Get("password")
if username == "" {
APIError(w, r, genericResponseFields{"message": "no password provided", "status": http.StatusInternalServerError})
return
}
if password == "" {
APIError(w, r, genericResponseFields{"message": "no password provided", "status": http.StatusInternalServerError})
return
}
db, ok := r.Context().Value(keyPrincipalContextID).(*gorm.DB)
if !ok {
APIError(w, r, genericResponseFields{"message": "internal server error", "status": http.StatusInternalServerError, "error": "DB connection failed"})
return
}
db.Where("username = ?", username).First(&result)
if result.Username == "" {
APIError(w, r, genericResponseFields{"message": "login failed", "status": http.StatusUnauthorized, "realm": "authentication"})
return
}
err = bcrypt.CompareHashAndPassword([]byte(result.HashedPassword), []byte(password))
if err != nil {
APIError(w, r, genericResponseFields{"message": "login failed", "status": http.StatusUnauthorized, "realm": "authentication"})
return
}
token, err := makeToken(username)
if err != nil {
APIError(w, r, genericResponseFields{"message": "internal server error", "status": http.StatusInternalServerError, "error": err.Error()})
return
}
http.SetCookie(w, &http.Cookie{
HttpOnly: true,
Expires: time.Now().Add(1 * time.Hour),
MaxAge: 3600,
SameSite: http.SameSiteStrictMode,
// Comment below to disable HTTPS:
Secure: true,
Name: "jwt", // Must be named "jwt" or else the token cannot be searched for by jwtauth.Verifier.
Value: token,
})
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
resp := internal.Response{
Message: "Successfully logged in",
}
render.JSON(w, r, resp)
}
// Logout destroys a users JWT cookie.
func Logout(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
HttpOnly: true,
MaxAge: -1, // Delete the cookie.
SameSite: http.SameSiteStrictMode,
Secure: true,
Name: "jwt",
Value: "",
})
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
resp := internal.Response{
Message: "Successfully logged out",
}
render.JSON(w, r, resp)
}