97 lines
2.1 KiB
Go
97 lines
2.1 KiB
Go
package route
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
|
|
"omctf.ru/block-game-backend/auth/session"
|
|
"omctf.ru/block-game-backend/codegen/ent"
|
|
"omctf.ru/block-game-backend/codegen/ent/user"
|
|
"omctf.ru/block-game-backend/db"
|
|
"omctf.ru/block-game-backend/utils"
|
|
)
|
|
|
|
func Login(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
|
|
req, err := utils.GetJSONBody[struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}](r)
|
|
if err != nil || req == nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
user, err := db.Client.User.Query().
|
|
Where(user.Username(req.Username)).
|
|
Where(user.Password(req.Password)).
|
|
Only(ctx)
|
|
|
|
if ent.IsNotFound(err) {
|
|
http.Error(w, "Invalid credentials", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err != nil || user == nil {
|
|
utils.BailInternalServerError(w, err)
|
|
return
|
|
}
|
|
|
|
err = session.SetUserId(w, r, user.ID)
|
|
if session.IsInvalidSession(err) {
|
|
http.Error(w, "Invalid session", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err != nil {
|
|
utils.BailInternalServerError(w, err)
|
|
return
|
|
}
|
|
}
|
|
|
|
func Register(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
|
|
req, err := utils.GetJSONBody[struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}](r)
|
|
if err != nil || req == nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
user, err := db.Client.User.CreateFrom(req).Save(ctx)
|
|
if ent.IsValidationError(err) {
|
|
http.Error(w, fmt.Sprintf("Invalid credentials: %s", err), http.StatusBadRequest)
|
|
return
|
|
}
|
|
if ent.IsConstraintError(err) {
|
|
http.Error(w, "Name taken", http.StatusConflict)
|
|
return
|
|
}
|
|
if err != nil || user == nil {
|
|
utils.BailInternalServerError(w, err)
|
|
return
|
|
}
|
|
|
|
err = session.SetUserId(w, r, user.ID)
|
|
if err != nil {
|
|
log.Printf("Couldn't set the session after registering the user: %s\n", err)
|
|
// anyway registering succeded
|
|
}
|
|
|
|
w.WriteHeader(http.StatusCreated)
|
|
utils.RespondWithJSON(w, map[string]any{
|
|
"id": user.ID,
|
|
})
|
|
}
|
|
|
|
func Logout(w http.ResponseWriter, r *http.Request) {
|
|
err := session.ClearSession(w, r)
|
|
if err != nil {
|
|
utils.BailInternalServerError(w, err)
|
|
return
|
|
}
|
|
}
|