Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 20 additions & 87 deletions internal/api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/tscrond/dropper/internal/mappings"
"github.com/tscrond/dropper/internal/repo/sqlc"
"github.com/tscrond/dropper/internal/userdata"
pkg "github.com/tscrond/dropper/pkg"
"golang.org/x/oauth2"
)

Expand All @@ -30,21 +31,13 @@ func (s *APIServer) authCallback(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
code := r.URL.Query().Get("code")
if code == "" {
w.WriteHeader(http.StatusBadRequest)
JSON(w, map[string]any{
"status": http.StatusBadRequest,
"response": "Missing authorization code",
})
pkg.WriteJSONResponse(w, http.StatusBadRequest, "", "Missing authorization code")
return
}

t, err := s.OAuthConfig.Exchange(ctx, code)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
JSON(w, map[string]any{
"status": http.StatusBadRequest,
"response": "Missing authorization code",
})
pkg.WriteJSONResponse(w, http.StatusBadRequest, "", "Missing authorization code")
return
}

Expand All @@ -53,11 +46,7 @@ func (s *APIServer) authCallback(w http.ResponseWriter, r *http.Request) {
// Getting the user public details from google API endpoint
resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
if err != nil {
w.WriteHeader(http.StatusBadRequest)
JSON(w, map[string]any{
"status": http.StatusBadRequest,
"response": "Missing authorization code",
})
pkg.WriteJSONResponse(w, http.StatusBadRequest, "", "Missing authorization code")
return
}
defer resp.Body.Close()
Expand All @@ -67,11 +56,7 @@ func (s *APIServer) authCallback(w http.ResponseWriter, r *http.Request) {
// Reading the JSON body using JSON decoder
err = json.NewDecoder(resp.Body).Decode(&jsonResp)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
JSON(w, map[string]any{
"status": http.StatusInternalServerError,
"response": err.Error(),
})
pkg.WriteJSONResponse(w, http.StatusBadRequest, "", "Error decoding JSON response")
return
}

Expand Down Expand Up @@ -182,32 +167,20 @@ func (s *APIServer) authMiddleware(next http.Handler) http.Handler {
cookie, err := r.Cookie("access_token")
// fmt.Println(cookie)
if err != nil || cookie.Value == "" {
w.WriteHeader(http.StatusForbidden)
JSON(w, map[string]any{
"status": http.StatusForbidden,
"response": "Unauthorized",
})
pkg.WriteJSONResponse(w, http.StatusForbidden, "", "Unauthorized")
return
}

valid, verifiedUserData := s.verifyToken(cookie.Value)
if !valid {
w.WriteHeader(http.StatusForbidden)
JSON(w, map[string]any{
"status": http.StatusForbidden,
"response": "Unauthorized (invalid or expired session)",
})
pkg.WriteJSONResponse(w, http.StatusForbidden, "", "Unauthorized (invalid or expired session)")
return
}
// log.Println("verified user:", verifiedUserData)

userInfo, err := s.fetchUserInfo(cookie.Value)
if err != nil {
w.WriteHeader(http.StatusForbidden)
JSON(w, map[string]any{
"status": http.StatusForbidden,
"response": "Could not fetch logged user info",
})
pkg.WriteJSONResponse(w, http.StatusForbidden, "", "Could not fetch logged user info")
return
}
// log.Println("logged user info::", userInfo)
Expand Down Expand Up @@ -256,10 +229,7 @@ func (s *APIServer) logout(w http.ResponseWriter, r *http.Request) {
// Check if access_token cookie exists
cookie, err := r.Cookie("access_token")
if err != nil {
w.WriteHeader(http.StatusNotFound)
JSON(w, map[string]any{
"response": "cookie_not_found",
"code": http.StatusNotFound,
pkg.WriteJSONResponse(w, http.StatusNotFound, "cookie_not_found", map[string]any{
"logout_successful": true,
})
return
Expand All @@ -272,9 +242,7 @@ func (s *APIServer) logout(w http.ResponseWriter, r *http.Request) {

req, err := http.NewRequest("POST", revokeURL, nil)
if err != nil {
JSON(w, map[string]interface{}{
"response": "internal_server_error",
"code": http.StatusInternalServerError,
pkg.WriteJSONResponse(w, http.StatusInternalServerError, "logout_error", map[string]any{
"logout_successful": false,
})
return
Expand All @@ -287,9 +255,7 @@ func (s *APIServer) logout(w http.ResponseWriter, r *http.Request) {
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
JSON(w, map[string]any{
"response": "internal_server_error",
"code": http.StatusInternalServerError,
pkg.WriteJSONResponse(w, http.StatusInternalServerError, "logout_error", map[string]any{
"logout_successful": false,
})
return
Expand All @@ -298,10 +264,7 @@ func (s *APIServer) logout(w http.ResponseWriter, r *http.Request) {

// Check response status
if resp.StatusCode != http.StatusOK {
w.WriteHeader(resp.StatusCode)
JSON(w, map[string]any{
"response": "failed_to_revoke_token",
"code": resp.StatusCode,
pkg.WriteJSONResponse(w, resp.StatusCode, "failed_to_revoke_token", map[string]any{
"logout_successful": false,
})
return
Expand All @@ -321,60 +284,43 @@ func (s *APIServer) logout(w http.ResponseWriter, r *http.Request) {

w.WriteHeader(http.StatusOK)
// Return success response
JSON(w, map[string]any{
"response": "session_invalidated",
"code": http.StatusOK,
pkg.WriteJSONResponse(w, http.StatusOK, "session_invalidated", map[string]any{
"logout_successful": true,
})
}

func (s *APIServer) isValid(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusBadRequest)
JSON(w, map[string]any{
"response": "bad_request",
"code": http.StatusBadRequest,
pkg.WriteJSONResponse(w, http.StatusBadRequest, "bad_request", map[string]any{
"authenticated": false,
"user_info": nil,
})
return
}
cookie, err := r.Cookie("access_token")
if err != nil || cookie.Value == "" {
w.WriteHeader(http.StatusForbidden)
response := map[string]any{
"response": "access_denied",
"code": http.StatusForbidden,
pkg.WriteJSONResponse(w, http.StatusForbidden, "access_denied", map[string]any{
"authenticated": false,
"user_info": nil,
}
JSON(w, response)
})
return
}

// fmt.Println(cookie.Value)

valid, userInfo := s.verifyToken(cookie.Value)
if !valid {
w.WriteHeader(http.StatusForbidden)
response := map[string]interface{}{
"response": "access_denied",
"code": http.StatusForbidden,
pkg.WriteJSONResponse(w, http.StatusForbidden, "access_denied", map[string]any{
"authenticated": false,
"user_info": nil,
}
JSON(w, response)
})
return
}

w.WriteHeader(http.StatusOK)
response := map[string]interface{}{
"response": "access_granted",
"code": http.StatusOK,
pkg.WriteJSONResponse(w, http.StatusOK, "access_granted", map[string]any{
"authenticated": true,
"user_info": userInfo,
}
JSON(w, response)
})
}

func (s *APIServer) fetchUserInfo(accessToken string) (*userdata.AuthorizedUserInfo, error) {
Expand Down Expand Up @@ -402,16 +348,3 @@ func (s *APIServer) fetchUserInfo(accessToken string) (*userdata.AuthorizedUserI

return &user, nil
}

func JSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")

if err := json.NewEncoder(w).Encode(v); err != nil {
w.WriteHeader(http.StatusInternalServerError)
JSON(w, map[string]any{
"status": http.StatusInternalServerError,
"response": "Error encoding JSON",
})
return
}
}
58 changes: 13 additions & 45 deletions internal/api/data_delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,39 +8,28 @@ import (

"github.com/tscrond/dropper/internal/repo/sqlc"
"github.com/tscrond/dropper/internal/userdata"
pkg "github.com/tscrond/dropper/pkg"
)

func (s *APIServer) deleteFile(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()

if r.Method != http.MethodDelete {
w.WriteHeader(http.StatusBadRequest)
JSON(w, map[string]any{
"response": "bad_request",
"code": http.StatusBadRequest,
})
pkg.WriteJSONResponse(w, http.StatusBadRequest, "bad_request", nil)
return
}

object := r.URL.Query().Get("file")
if object == "" {
w.WriteHeader(http.StatusBadRequest)
JSON(w, map[string]any{
"response": "bad_request",
"code": http.StatusBadRequest,
})
pkg.WriteJSONResponse(w, http.StatusBadRequest, "bad_request", nil)
}

// parse data of logged in user
authorizedUserData := ctx.Value(userdata.AuthorizedUserContextKey)
authUserData, ok := authorizedUserData.(*userdata.AuthorizedUserInfo)
if !ok {
log.Println("cannot read authorized user data")
w.WriteHeader(http.StatusForbidden)
JSON(w, map[string]any{
"response": "authorization_failed",
"code": http.StatusForbidden,
})
pkg.WriteJSONResponse(w, http.StatusForbidden, "authorization_failed", nil)
return
}

Expand All @@ -56,31 +45,20 @@ func (s *APIServer) deleteFile(w http.ResponseWriter, r *http.Request) {
FileName: object,
}); err != nil {
log.Println("errors deleting file from DB: ", err)
w.WriteHeader(http.StatusInternalServerError)
JSON(w, map[string]any{
"response": "delete_file_error",
"code": http.StatusInternalServerError,
})
pkg.WriteJSONResponse(w, http.StatusInternalServerError, "delete_file_error", nil)
return
}
w.WriteHeader(http.StatusOK)
JSON(w, map[string]any{
"response": "success",
"code": http.StatusOK,

pkg.WriteJSONResponse(w, http.StatusOK, "success", map[string]any{
"file_deleted": object,
})

}

func (s *APIServer) deleteAccount(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()

if r.Method != http.MethodDelete {
w.WriteHeader(http.StatusBadRequest)
JSON(w, map[string]any{
"response": "bad_request",
"code": http.StatusBadRequest,
})
pkg.WriteJSONResponse(w, http.StatusBadRequest, "bad_request", nil)
return
}

Expand All @@ -89,33 +67,23 @@ func (s *APIServer) deleteAccount(w http.ResponseWriter, r *http.Request) {
authUserData, ok := authorizedUserData.(*userdata.AuthorizedUserInfo)
if !ok {
log.Println("cannot read authorized user data")
w.WriteHeader(http.StatusForbidden)
JSON(w, map[string]any{
"response": "authorization_failed",
"code": http.StatusForbidden,
})
pkg.WriteJSONResponse(w, http.StatusForbidden, "authorization_failed", nil)
return
}

deletedAccount, err := s.repository.Queries.DeleteAccount(ctx, authUserData.Id)
if err != nil {
log.Println("issues deleting object: ", err)
w.WriteHeader(http.StatusInternalServerError)
JSON(w, map[string]any{
"response": "authorization_failed",
"code": http.StatusInternalServerError,
})
pkg.WriteJSONResponse(w, http.StatusInternalServerError, "authorization_failed", nil)
return
}

w.WriteHeader(http.StatusOK)
JSON(w, map[string]any{
"response": "success",
"code": http.StatusOK,

pkg.WriteJSONResponse(w, http.StatusOK, "success", map[string]any{
"account_deleted": map[string]any{
"id": deletedAccount.GoogleID,
"email": deletedAccount.UserEmail,
"user_name": deletedAccount.UserName.String,
},
})

}
Loading