diff options
| -rw-r--r-- | api/handlers.go | 36 | ||||
| -rw-r--r-- | db/db.go | 5 | ||||
| -rw-r--r-- | main.go | 1 |
3 files changed, 41 insertions, 1 deletions
diff --git a/api/handlers.go b/api/handlers.go index f98dd6b..3b09d22 100644 --- a/api/handlers.go +++ b/api/handlers.go @@ -2,6 +2,8 @@ package api import ( "context" + "database/sql" + "errors" "encoding/json" "log" "net/http" @@ -37,7 +39,11 @@ type loginReq struct { Username string `json:"username"` Password string `json:"password"` } - +// tokenResp is returned by GET /token. +type tokenResp struct { + AccessToken string `json:"access_token"` + ValidUntil string `json:"valid_until"` +} // --- helper writers --- func writeJSON(w http.ResponseWriter, code int, v any) { @@ -168,3 +174,31 @@ func (h *Handler) Health(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) } + +// --- Get Token: GET /token?username=... --- + +func (h *Handler) GetToken(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), defaultTimeout) + defer cancel() + + username := r.URL.Query().Get("username") + if username == "" { + badRequest(w, "username query parameter is required") + return + } + + acct, err := h.db.GetAccount(ctx, username) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + unauthorized(w) + return + } + serverError(w, "could not retrieve token") + return + } + + writeJSON(w, http.StatusOK, tokenResp{ + AccessToken: acct.AccessToken, + ValidUntil: acct.AccessTokenExpiry.Format(time.RFC3339), + }) +} @@ -315,6 +315,11 @@ func (d *DB) getAccountByUsername(ctx context.Context, username string) (*Accoun return &acct, nil } +// GetAccount fetches the current tokens for a username. +func (d *DB) GetAccount(ctx context.Context, username string) (*Account, error) { + return d.getAccountByUsername(ctx, username) +} + // HealthCheck runs a trivial query to verify DB liveness. func (d *DB) HealthCheck(ctx context.Context) error { _, err := d.conn.ExecContext(ctx, "SELECT 1") @@ -86,6 +86,7 @@ func main() { mux.HandleFunc("POST /login", handler.Login) mux.HandleFunc("POST /refresh", handler.Refresh) mux.HandleFunc("GET /health", handler.Health) + mux.HandleFunc("GET /token", handler.GetToken) addr := fmt.Sprintf(":%d", cfg.Server.Port) srv := &http.Server{ |
