/ web / web.go
web.go
 1  package web
 2  
 3  import (
 4  	// "log"
 5  	"context"
 6  
 7  	"github.com/gofiber/fiber/v2"
 8  	"github.com/mrusme/journalist/ent"
 9  	"github.com/mrusme/journalist/ent/token"
10  	"github.com/mrusme/journalist/ent/user"
11  	"github.com/mrusme/journalist/lib"
12  	"github.com/mrusme/journalist/web/actions"
13  	"github.com/mrusme/journalist/web/subscriptions"
14  )
15  
16  func Register(
17  	jctx *lib.JournalistContext,
18  	fiberApp *fiber.App,
19  ) {
20  	web := fiberApp.Group("/web")
21  	web.Use(authorizer(jctx.EntClient))
22  
23  	actions.Register(
24  		jctx,
25  		&web,
26  	)
27  
28  	subscriptions.Register(
29  		jctx,
30  		&web,
31  	)
32  }
33  
34  // TODO: Move to `middlewares`
35  func authorizer(entClient *ent.Client) fiber.Handler {
36  	return func(ctx *fiber.Ctx) error {
37  		qat := ctx.Query("qat")
38  		if qat == "" {
39  			return ctx.SendStatus(fiber.StatusUnauthorized)
40  		}
41  
42  		u, err := entClient.User.
43  			Query().
44  			WithTokens().
45  			Where(
46  				user.HasTokensWith(
47  					token.Token(qat),
48  				),
49  			).
50  			Only(context.Background())
51  		if err != nil {
52  			return ctx.SendStatus(fiber.StatusUnauthorized)
53  		}
54  
55  		if u == nil {
56  			return ctx.SendStatus(fiber.StatusUnauthorized)
57  		}
58  
59  		ctx.Locals("user_id", u.ID.String())
60  		ctx.Locals("username", u.Username)
61  		// ctx.Locals("password", u.Password)
62  		ctx.Locals("role", u.Role)
63  		return ctx.Next()
64  	}
65  }