Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wip(GIST-25): merged auth into user package bc cycle import #9

Merged
merged 4 commits into from
Aug 20, 2024
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
tmp
.env
api
33 changes: 19 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ Check the [API documentation](http://localhost:4000) for more information (for n
- Air
- docker compose
- migrate
- Just

### Onboarding script

```bash
docker compose up -d
migrate -path=migrations -database "postgresql://postgres:[email protected]:5432/gists?sslmode=disable" -verbose up
air
just migrate
just dev
```

## Installation
Expand Down Expand Up @@ -52,17 +53,21 @@ MAIL_SMTP="<REDACTED>"
MAIL_PASSWORD="<REDACTED>"
SMTP_PORT="<REDACTED>"
SMTP_HOST="<REDACTED>"
APP_KEY="<REDACTED>"
```

4. Run the server
4. Run the server in development mode

```bash
just dev
# or
air
```

## Configuration

All the configuration is done through env variables :
All the configuration is done through env variables :

- `PORT` : the port on which your web server runs
- `PG_USER` : the postgres user
- `PG_PASSWORD` : the postgres password
Expand All @@ -75,13 +80,20 @@ All the configuration is done through env variables :
- `GOOGLE_SECRET` : your google client secret for OAUTH2
- `GITHUB_KEY` : your github client key for OAUTH2
- `GITHUB_SECRET` : your github client secret for OAUTH2
- `MAIL_SMTP` : your smtp server
- `MAIL_PASSWORD` : your smtp password
- `SMTP_PORT` : your smtp port
- `SMTP_HOST` : your smtp host
- `APP_KEY` : your app key, which is a random string that is used to encrypt access tokens

## Tests

To run tests, execute:

```bash
go test .
just test <your-test-name>
# or to run all tests
just test-all
```

## Migrations
Expand All @@ -96,15 +108,8 @@ migrate create -ext=sql -dir=migrations -seq init

To run the existing migrations locally :

### With bash

```bash
just migrate
# or
migrate -path=migrations -database "postgresql://postgres:[email protected]:5432/gists?sslmode=disable" -verbose up
```

### With go

```bash
go build main.go
./main migrate
```
2 changes: 1 addition & 1 deletion docs/openapi.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions gists/router.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package gists

import (
"github.com/gistapp/api/server"
"github.com/gistapp/api/user"
"github.com/gofiber/fiber/v2"
)

Expand All @@ -10,7 +10,7 @@ type GistRouter struct {
}

func (r *GistRouter) SubscribeRoutes(app *fiber.Router) {
gists_router := (*app).Group("/gists", server.AuthNeededMiddleware)
gists_router := (*app).Group("/gists", user.AuthNeededMiddleware)

gists_router.Post("/", r.Controller.Save())
gists_router.Patch("/:id/name", r.Controller.UpdateName())
Expand Down
14 changes: 14 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
build:
go build -o api -v

test-all:
go test ./tests/ -v

test TEST:
go test ./tests/{{TEST}} -v

migrate: build
./api migrate

dev:
air
16 changes: 10 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"fmt"
"os"

"github.com/gistapp/api/auth"
"github.com/gistapp/api/gists"
"github.com/gistapp/api/organizations"
"github.com/gistapp/api/server"
"github.com/gistapp/api/storage"
"github.com/gistapp/api/user"
"github.com/gistapp/api/utils"
"github.com/gofiber/fiber/v2/log"
)
Expand Down Expand Up @@ -37,19 +37,23 @@ func main() {
Controller: gists.GistController,
}

authRouter := auth.AuthRouter{
Controller: &auth.AuthControllerImpl{
AuthService: &auth.AuthService,
authRouter := user.AuthRouter{
Controller: &user.AuthControllerImpl{
AuthService: &user.AuthService,
},
}

userRouter := user.UserRouter{
Controller: &user.UserControllerImpl{},
}

orgRouter := organizations.OrganizationRouter{
Controller: organizations.OrganizationControllerImpl{},
}

auth.AuthService.RegisterProviders() //register goth providers for authentication
user.AuthService.RegisterProviders() //register goth providers for authentication

// Start the server
s.Setup(&gistRouter, &authRouter, &orgRouter)
s.Setup(&gistRouter, &authRouter, &orgRouter, &userRouter)
s.Ignite()
}
4 changes: 2 additions & 2 deletions organizations/router.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package organizations

import (
"github.com/gistapp/api/server"
"github.com/gistapp/api/user"
"github.com/gofiber/fiber/v2"
)

Expand All @@ -10,7 +10,7 @@ type OrganizationRouter struct {
}

func (r *OrganizationRouter) SubscribeRoutes(app *fiber.Router) {
organizations_router := (*app).Group("/orgs", server.AuthNeededMiddleware)
organizations_router := (*app).Group("/orgs", user.AuthNeededMiddleware)

organizations_router.Post("/", r.Controller.Save())
organizations_router.Get("/", r.Controller.GetAsMember())
Expand Down
4 changes: 2 additions & 2 deletions server/middleware.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package server

import (
"github.com/gistapp/api/auth"
"github.com/gistapp/api/user"
"github.com/gofiber/fiber/v2"
)

Expand All @@ -21,7 +21,7 @@ func AuthNeededMiddleware(ctx *fiber.Ctx) error {
})
}
raw_token := string(ctx.Request().Header.Peek("Authorization")[7:])
claims, err := auth.AuthService.IsAuthenticated(raw_token)
claims, err := user.AuthService.IsAuthenticated(raw_token)
if err != nil {
return ctx.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": "Unauthorized",
Expand Down
10 changes: 5 additions & 5 deletions tests/gists_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import (
"os"
"testing"

"github.com/gistapp/api/auth"
"github.com/gistapp/api/gists"
"github.com/gistapp/api/organizations"
"github.com/gistapp/api/server"
"github.com/gistapp/api/storage"
"github.com/gistapp/api/tests/mock"
"github.com/gistapp/api/user"
"github.com/gistapp/api/utils"
"github.com/gofiber/fiber/v2"
)
Expand All @@ -34,7 +34,7 @@ func InitServerGists() *fiber.App {
Controller: gists.GistController,
}

auth_router := auth.AuthRouter{
auth_router := user.AuthRouter{
Controller: &mock.MockAuthController{
//needs GetUser to fit the auth interface
AuthService: &mock.MockAuthService{},
Expand All @@ -55,7 +55,7 @@ func TestCreateGists(t *testing.T) {
app := InitServerGists()
authToken := GetAuthToken(t, app)

body, req := utils.MakeRequest(t, app, "/gists", map[string]string{
body, req := utils.MakeRequest("POST", t, app, "/gists", map[string]string{
"name": "Test Gist",
"content": "Test content",
}, map[string]string{
Expand All @@ -73,7 +73,7 @@ func TestCreateGists(t *testing.T) {
t.Run("Create a new organization gist", func(t *testing.T) {
app := InitServerGists()
auth_token := GetAuthToken(t, app)
claims, _ := auth.AuthService.IsAuthenticated(auth_token)
claims, _ := user.AuthService.IsAuthenticated(auth_token)

org_mod := organizations.OrganizationSQL{
Name: sql.NullString{
Expand All @@ -93,7 +93,7 @@ func TestCreateGists(t *testing.T) {
"org_id": org.ID,
}

body, req := utils.MakeRequest(t, app, "/gists", payload, map[string]string{
body, req := utils.MakeRequest("POST", t, app, "/gists", payload, map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", auth_token),
})

Expand Down
12 changes: 6 additions & 6 deletions tests/mock/auth_controller.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package mock

import (
"github.com/gistapp/api/auth"
"github.com/gistapp/api/user"
"github.com/gofiber/fiber/v2"
)

type MockAuthController struct{
AuthService auth.IAuthService
type MockAuthController struct {
AuthService user.IAuthService
}

func (a *MockAuthController) Callback() fiber.Handler {
Expand All @@ -23,7 +23,7 @@ func (a *MockAuthController) Authenticate() fiber.Handler {

func (a *MockAuthController) LocalAuth() fiber.Handler {
return func(c *fiber.Ctx) error {
e := new(auth.AuthLocalValidator)
e := new(user.AuthLocalValidator)
if err := c.BodyParser(e); err != nil {
return c.Status(400).SendString("Request must be valid JSON with field email as text")
}
Expand All @@ -39,7 +39,7 @@ func (a *MockAuthController) LocalAuth() fiber.Handler {

func (a *MockAuthController) VerifyAuthToken() fiber.Handler {
return func(c *fiber.Ctx) error {
e := new(auth.AuthLocalVerificationValidator)
e := new(user.AuthLocalVerificationValidator)

if err := c.BodyParser(e); err != nil {
return c.Status(400).SendString("Request must be valid JSON with fields token and email as text")
Expand All @@ -61,4 +61,4 @@ func (a *MockAuthController) VerifyAuthToken() fiber.Handler {
c.Cookie(token_cookie)
return c.Status(200).JSON(fiber.Map{"message": "You are now logged in"})
}
}
}
21 changes: 10 additions & 11 deletions tests/mock/auth_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"errors"
"strings"

"github.com/gistapp/api/auth"
"github.com/gistapp/api/user"
"github.com/gistapp/api/utils"
"github.com/gofiber/fiber/v2"
Expand All @@ -20,12 +19,12 @@ func (m *MockAuthService) Authenticate(c *fiber.Ctx) error {
return nil
}

func (m *MockAuthService) LocalAuth(email string) (auth.TokenSQL, error) {
func (m *MockAuthService) LocalAuth(email string) (user.TokenSQL, error) {
token_val := utils.GenToken(6)
token_model := auth.TokenSQL{
token_model := user.TokenSQL{
Keyword: sql.NullString{String: email, Valid: true},
Value: sql.NullString{String: token_val, Valid: true},
Type: sql.NullString{String: string(auth.LocalAuth), Valid: true},
Type: sql.NullString{String: string(user.LocalAuth), Valid: true},
}

_, err := token_model.Save()
Expand All @@ -35,10 +34,10 @@ func (m *MockAuthService) LocalAuth(email string) (auth.TokenSQL, error) {
}

func (m *MockAuthService) VerifyLocalAuthToken(token string, email string) (string, error) {
token_model := auth.TokenSQL{
token_model := user.TokenSQL{
Value: sql.NullString{String: token, Valid: true},
Keyword: sql.NullString{String: email, Valid: true},
Type: sql.NullString{String: string(auth.LocalAuth), Valid: true},
Type: sql.NullString{String: string(user.LocalAuth), Valid: true},
}
token_data, err := token_model.Get()
if err != nil {
Expand Down Expand Up @@ -80,8 +79,8 @@ func (m *MockAuthService) Callback(c *fiber.Ctx) (string, error) {
return "", nil
}

func (a *MockAuthService) GetUser(auth_user goth.User) (*user.User, *auth.AuthIdentity, error) {
return auth.AuthService.GetUser(auth_user)
func (a *MockAuthService) GetUser(auth_user goth.User) (*user.User, *user.AuthIdentity, error) {
return user.AuthService.GetUser(auth_user)
}

func (m *MockAuthService) Register(auth_user goth.User) (*user.User, error) {
Expand All @@ -103,7 +102,7 @@ func (m *MockAuthService) Register(auth_user goth.User) (*user.User, error) {
return nil, err
}

auth_identity_model := auth.AuthIdentitySQL{
auth_identity_model := user.AuthIdentitySQL{
Data: sql.NullString{String: string(data), Valid: true},
Type: sql.NullString{String: auth_user.Provider, Valid: true},
OwnerID: sql.NullString{String: user_data.ID, Valid: true},
Expand All @@ -114,14 +113,14 @@ func (m *MockAuthService) Register(auth_user goth.User) (*user.User, error) {
return user_data, err
}

func (a *MockAuthService) IsAuthenticated(token string) (*auth.JWTClaim, error) {
func (a *MockAuthService) IsAuthenticated(token string) (*user.JWTClaim, error) {
claims, err := utils.VerifyJWT(token)

if err != nil {
return nil, err
}

jwtClaim := new(auth.JWTClaim)
jwtClaim := new(user.JWTClaim)
jwtClaim.Pub = claims["pub"].(string)
jwtClaim.Email = claims["email"].(string)

Expand Down
8 changes: 3 additions & 5 deletions tests/organization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,16 @@ import (
"strconv"
"testing"

"github.com/gistapp/api/auth"
"github.com/gistapp/api/gists"
"github.com/gistapp/api/organizations"
"github.com/gistapp/api/server"
"github.com/gistapp/api/storage"
"github.com/gistapp/api/tests/mock"
"github.com/gistapp/api/user"
"github.com/gistapp/api/utils"
"github.com/gofiber/fiber/v2"
)

var endpoint = "http://localhost:4000"

func InitServerOrgs() *fiber.App {
// Check for command-line arguments
if len(os.Args) > 1 && os.Args[1] == "migrate" {
Expand All @@ -37,7 +35,7 @@ func InitServerOrgs() *fiber.App {
Controller: gists.GistController,
}

auth_router := auth.AuthRouter{
auth_router := user.AuthRouter{
Controller: &mock.MockAuthController{
AuthService: &mock.MockAuthService{},
},
Expand Down Expand Up @@ -70,7 +68,7 @@ func TestCreateOrganization(t *testing.T) {
}
fmt.Println(org_payload)
//
body, _ := utils.MakeRequest(t, app, "/orgs", org_payload, map[string]string{
body, _ := utils.MakeRequest("POST", t, app, "/orgs", org_payload, map[string]string{
"Authorization": "Bearer " + auth_token,
})
//
Expand Down
Loading
Loading