feat: generate auth code and save

This commit is contained in:
2025-06-07 19:16:45 +02:00
parent 2209846525
commit b09567620f

View File

@ -1,10 +1,13 @@
package oauth
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"gitea.local/admin/hspguard/internal/cache"
"gitea.local/admin/hspguard/internal/util"
"gitea.local/admin/hspguard/internal/web"
"github.com/google/uuid"
@ -24,7 +27,8 @@ func (h *OAuthHandler) getAuthCode(w http.ResponseWriter, r *http.Request) {
}
type Request struct {
Nonce string `json:"nonce"`
Nonce string `json:"nonce"`
ClientID string `json:"client_id"`
}
var req Request
@ -35,7 +39,29 @@ func (h *OAuthHandler) getAuthCode(w http.ResponseWriter, r *http.Request) {
return
}
// TODO: Create real authorization code
buf := make([]byte, 32)
_, err = rand.Read(buf)
if err != nil {
log.Println("ERR: Failed to generate auth code:", err)
web.Error(w, "failed to create authorization code", http.StatusInternalServerError)
return
}
authCode := base64.RawURLEncoding.EncodeToString(buf)
params := cache.SaveAuthCodeParams{
AuthCode: authCode,
UserID: user.ID.String(),
ClientID: req.ClientID,
Nonce: req.Nonce,
}
log.Printf("DEBUG: Saving auth code session with params: %#v\n", params)
if err := h.cache.SaveAuthCode(r.Context(), &params); err != nil {
log.Println("ERR: Failed to save auth code in redis:", err)
web.Error(w, "failed to generate auth code", http.StatusInternalServerError)
return
}
type Response struct {
Code string `json:"code"`
@ -46,7 +72,7 @@ func (h *OAuthHandler) getAuthCode(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := encoder.Encode(Response{
Code: fmt.Sprintf("%s,%s", user.ID.String(), req.Nonce),
Code: authCode,
}); err != nil {
web.Error(w, "failed to encode response", http.StatusInternalServerError)
}