initial commit

This commit is contained in:
Daniel Hjartland
2024-11-26 18:08:49 +01:00
commit 75be79c6cf
26 changed files with 1885 additions and 0 deletions

56
handler_refresh.go Normal file
View File

@@ -0,0 +1,56 @@
package main
import (
"net/http"
"time"
"github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/auth"
)
func (cfg *apiConfig) handlerRefresh(w http.ResponseWriter, r *http.Request) {
type response struct {
Token string `json:"token"`
}
refreshToken, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't find token", err)
return
}
user, err := cfg.db.GetUserByRefreshToken(refreshToken)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't get user for refresh token", err)
return
}
accessToken, err := auth.MakeJWT(
user.ID,
cfg.jwtSecret,
time.Hour,
)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't validate token", err)
return
}
respondWithJSON(w, http.StatusOK, response{
Token: accessToken,
})
}
func (cfg *apiConfig) handlerRevoke(w http.ResponseWriter, r *http.Request) {
refreshToken, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't find token", err)
return
}
err = cfg.db.RevokeRefreshToken(refreshToken)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't revoke session", err)
return
}
w.WriteHeader(http.StatusNoContent)
}