Skip to content

Commit

Permalink
reformats todos for vscode
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinGallauner committed May 10, 2024
1 parent d41be3a commit bdac325
Show file tree
Hide file tree
Showing 13 changed files with 43 additions and 35 deletions.
2 changes: 1 addition & 1 deletion internal/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func (c *Client) FetchBook(isbn string) (Book, error) {
}

// mapBookResponse reads the ugly response from the OpenLibraryAPI and maps it to a simple book entity.
// todo clean that crap up
// TODO: clean that crap up
func mapBookResponse(response map[string]map[string]interface{}) (Book, error) {
var book Book
for isbn, bookData := range response {
Expand Down
2 changes: 1 addition & 1 deletion internal/collection_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ func (cfg *BookclubServer) AddBookToCollection(isbn string, userId uint) (Book,
}

var book Book
book, _ = cfg.BookRepository.GetBook(isbn) //todo handle error
book, _ = cfg.BookRepository.GetBook(isbn) //TODO: handle error
if book.ISBN == "" {
book, err = cfg.Client.FetchBook(isbn)
if err != nil {
Expand Down
5 changes: 3 additions & 2 deletions internal/entities.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package internal

import (
"gorm.io/gorm"
"time"

"gorm.io/gorm"
)

type User struct {
Expand All @@ -26,7 +27,7 @@ type UserBooks struct {
}

type Link struct {
SenderId uint `gorm:"primaryKey"` //todo the concept of sender/receiver id is crap
SenderId uint `gorm:"primaryKey"` //TODO: the concept of sender/receiver id is crap
ReceiverId uint `gorm:"primaryKey"`
CreatedAt time.Time
AcceptedAt time.Time
Expand Down
7 changes: 4 additions & 3 deletions internal/handler_add_book.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
)

// handlerAddBook handles requests to add books to user collection
func (cfg *BookclubServer) handlerAddBook(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
body := AddBookRequest{}
Expand All @@ -20,11 +21,11 @@ func (cfg *BookclubServer) handlerAddBook(w http.ResponseWriter, r *http.Request
respondWithError(w, 400, "Unable to add the requested book")
return
}
respondWithJSON(w, 200, book) //todo reconsider response body
respondWithJSON(w, 200, book) //TODO: reconsider response body
return
}

type AddBookRequest struct { //todo what is the best location for this struct definition?
UserId uint `json:"user_id"` //todo this needs to be changed later when auth is in place
type AddBookRequest struct { //TODO: what is the best location for this struct definition?
UserId uint `json:"user_id"` //TODO: this needs to be changed later when auth is in place
ISBN string `json:"isbn"`
}
13 changes: 7 additions & 6 deletions internal/handler_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ package internal
import (
"context"
"fmt"
"net/http"

"github.com/markbates/goth/gothic"
"gorm.io/gorm"
"net/http"
)

func (cfg *BookclubServer) handlerCallback(w http.ResponseWriter, r *http.Request) {
Expand All @@ -16,13 +17,13 @@ func (cfg *BookclubServer) handlerCallback(w http.ResponseWriter, r *http.Reques
fmt.Fprintln(w, err)
return
}
fmt.Println("logging in user: ", user.Email) //todo delete
fmt.Println("logging in user: ", user.Email) //TODO: delete

http.Redirect(w, r, "http://localhost:5173", http.StatusFound)
}

func (cfg *BookclubServer) handlerLogout(w http.ResponseWriter, r *http.Request) {
fmt.Println("loggin out user") //todo delete
fmt.Println("loggin out user") //TODO: delete

gothic.Logout(w, r)
w.Header().Set("Location", "http://localhost:5173")
Expand All @@ -36,7 +37,7 @@ func (cfg *BookclubServer) handlerLogin(w http.ResponseWriter, r *http.Request)
// try to get the user without re-authenticating
gothUser, err := cfg.AuthService.CompleteUserAuth(w, r)
if err != nil {
gothic.BeginAuthHandler(w, r) //todo add to interface
gothic.BeginAuthHandler(w, r) //TODO: add to interface
}
//check if user exists, if not, create
persistedUser, err := cfg.UserRepository.GetByEmail(gothUser.Email)
Expand All @@ -48,7 +49,7 @@ func (cfg *BookclubServer) handlerLogin(w http.ResponseWriter, r *http.Request)
}
jwt, err := cfg.JwtService.CreateToken("bookclub-access", int(persistedUser.ID))
if err != nil {
//todo logging
//TODO: logging
respondWithError(w, 400, "Unable to login user.")
}
loginResponse := LoginResponse{Name: persistedUser.Name, Email: persistedUser.Email, Jwt: jwt}
Expand All @@ -58,5 +59,5 @@ func (cfg *BookclubServer) handlerLogin(w http.ResponseWriter, r *http.Request)
type LoginResponse struct {
Name string
Email string
Jwt string //todo naming?
Jwt string //TODO: naming?
}
2 changes: 1 addition & 1 deletion internal/handler_get_links.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
)

func (cfg *BookclubServer) handlerGetLinks(w http.ResponseWriter, r *http.Request) {
userId := r.PathValue("id") //todo in the future I want to read the userId from the token
userId := r.PathValue("id") //TODO: in the future I want to read the userId from the token

links, err := cfg.GetLinks(userId)
var result []LinkResponse
Expand Down
4 changes: 2 additions & 2 deletions internal/handler_search.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"net/http"
)

// Search a book in the database //todo filter for connected users
// Search a book in the database //TODO: filter for connected users
func (cfg *BookclubServer) handlerSearch(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
body := AddBookRequest{}
Expand All @@ -15,7 +15,7 @@ func (cfg *BookclubServer) handlerSearch(w http.ResponseWriter, r *http.Request)
respondWithError(w, 400, fmt.Sprintf("Error decoding parameters: %s", err))
return
}
//todo remove ID from user response
//TODO: remove ID from user response
users, err := cfg.SearchBookInNetwork(body.UserId, body.ISBN)
if err != nil {
respondWithError(w, 404, "Book is not available in the users network.")
Expand Down
7 changes: 4 additions & 3 deletions internal/jwt_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package internal
import (
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
"os"
"strconv"
"time"

"github.com/golang-jwt/jwt/v5"
)

type JwtService interface {
Expand All @@ -21,15 +22,15 @@ func (srv JwtServiceImpl) CreateToken(issuer string, id int) (string, error) {
now := time.Now()
var expiresAt time.Time

if issuer == "bookclub-access" { //todo constant
if issuer == "bookclub-access" { //TODO: constant
expiresAt = now.Add(time.Duration(time.Hour) * 1)
} else {
expiresAt = now.Add(time.Hour * 1440)
}

jwt := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{Issuer: issuer, IssuedAt: jwt.NewNumericDate(now), ExpiresAt: jwt.NewNumericDate(expiresAt), Subject: strconv.Itoa(id)})
jwtSecret := os.Getenv("JWT_SECRET")
signedJwt, err := jwt.SignedString([]byte(jwtSecret)) //todo change the jwt secret
signedJwt, err := jwt.SignedString([]byte(jwtSecret)) //TODO: change the jwt secret
if err != nil {
return "", errors.New("Coudn't create JWT token")
}
Expand Down
5 changes: 3 additions & 2 deletions internal/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package internal

import (
"fmt"

"gorm.io/gorm"
)

Expand Down Expand Up @@ -67,7 +68,7 @@ func (r *PostgresUserRepository) GetByEmail(email string) (User, error) {
err := r.Database.Table("users").Preload("Books").First(&user).Where("email = ?", email).Error
if err != nil {
return User{}, err
} //todo return ErrNotFound
} //TODO: return ErrNotFound
return user, nil
}

Expand Down Expand Up @@ -96,7 +97,7 @@ func (r *PostgresLinkRepository) Get(senderId uint, receiverId uint) (Link, erro
return Link{}, err
}

if link.SenderId == 0 && link.ReceiverId == 0 { //todo I feel like that check is bad
if link.SenderId == 0 && link.ReceiverId == 0 { //TODO: I feel like that check is bad
return Link{}, gorm.ErrRecordNotFound
}
return link, nil
Expand Down
16 changes: 9 additions & 7 deletions internal/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@ import (
"context"
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
_ "github.com/martingallauner/bookclub/docs"
"github.com/swaggo/http-swagger"
"log"
"net/http"
"os"
"strings"

"github.com/golang-jwt/jwt/v5"
_ "github.com/martingallauner/bookclub/docs"
httpSwagger "github.com/swaggo/http-swagger"
)

// StartServer starts the server :)
func StartServer(cfg *BookclubServer) error {
log.Print("Starting bookclub on port: 8080")
log.Print("Starting bookclub on port: 8080") //TODO:: make the port configurable
return http.ListenAndServe(":8080", cfg.Handler)
}

Expand All @@ -36,7 +38,7 @@ func NewBookclubServer(client Client, repository BookRepository, userRepository
s.Client = client
s.AuthService = authService
s.JwtService = jwtService
router := http.NewServeMux() //todo add jwtMiddleware to all concerned handler
router := http.NewServeMux() //TODO: add jwtMiddleware to all concerned handler
router.Handle("/api/search", http.HandlerFunc(s.handlerSearch))
router.Handle("/api/collections", http.HandlerFunc(jwtMiddleware(s.handlerAddBook)))
router.Handle("/api/books/{isbn}", http.HandlerFunc(s.handlerGetBookByISBN))
Expand All @@ -54,7 +56,7 @@ func NewBookclubServer(client Client, repository BookRepository, userRepository

func jwtMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tokenString := extractToken(r) //todo extract token
tokenString := extractToken(r) //TODO: extract token
if tokenString == "" {
respondWithError(w, http.StatusUnauthorized, "Missing JWT")
return
Expand All @@ -76,7 +78,7 @@ func extractToken(r *http.Request) string {
}

func validateToken(tokenString string) (jwt.RegisteredClaims, error) {
jwtSecret := os.Getenv("JWT_SECRET") //todo load from .env
jwtSecret := os.Getenv("JWT_SECRET") //TODO: load from .env
claims := jwt.RegisteredClaims{}
token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
return []byte(jwtSecret), nil
Expand Down
2 changes: 1 addition & 1 deletion internal/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func Test_jwtMiddleware(t *testing.T) {
args args
want http.HandlerFunc
}{
// TODO: Add test cases.
// TODO:: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down
11 changes: 6 additions & 5 deletions internal/test_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package internal

import (
"context"
"github.com/markbates/goth"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
"log"
"net/http"
"testing"
"time"

"github.com/markbates/goth"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
)

func assertResponseBody(t testing.TB, got, want string) {
Expand All @@ -31,7 +32,7 @@ type PostgresContainer struct {
ConnectionString string
}

// helper method to run for each test //todo please don't start a new container for each test
// helper method to run for each test //TODO: please don't start a new container for each test
func setupTest() (*BookclubServer, error) {
container, err := CreatePostgresContainer()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion make
Original file line number Diff line number Diff line change
@@ -1 +1 @@
# todo include "swag init" to make
# TODO: include "swag init" to make

0 comments on commit bdac325

Please sign in to comment.