Add projects

This commit is contained in:
Kasper Juul Hermansen 2022-02-14 01:25:36 +01:00
parent 3e843d429a
commit cb0917d916
Signed by: kjuulh
GPG Key ID: 0F95C140730F2F23
14 changed files with 262 additions and 23 deletions

58
main.go
View File

@ -14,9 +14,10 @@ import (
"io/ioutil"
"net/http"
"os"
"serverctl/pkg/application/projects"
"serverctl/pkg/application/users"
"serverctl/pkg/db"
"serverctl/pkg/db/postgres"
"serverctl/pkg/users"
"time"
)
@ -76,7 +77,7 @@ func BasicAuthMiddleware(l *zap.Logger, us *users.Service) gin.HandlerFunc {
c.Next()
}
}
func setupApi(l *zap.Logger, cc *cache.Cache, us *users.Service) {
func setupApi(l *zap.Logger, cc *cache.Cache, us *users.Service, ps *projects.Service) {
l.Info("Setting up serverctl setupApi (using gin)")
r := gin.Default()
@ -100,6 +101,53 @@ func setupApi(l *zap.Logger, cc *cache.Cache, us *users.Service) {
c.JSON(http.StatusCreated, gin.H{"message": "user has been registered", "userId": createUser})
})
projectsApi := r.Group("/projects", BasicAuthMiddleware(l, us))
projectsApi.POST("/", func(c *gin.Context) {
type CreateProjectRequest struct {
Name string `json:"name" binding:"required"`
}
var createProjectRequest CreateProjectRequest
if err := c.BindJSON(&createProjectRequest); err != nil {
return
}
userId, _ := c.Get("userId")
createProjectId, err := ps.CreateProject(c.Request.Context(), userId.(int), createProjectRequest.Name)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "you have provided invalid input"})
return
}
c.JSON(http.StatusCreated, gin.H{"message": "project has been created", "projectId": createProjectId})
})
projectsApi.GET("/", func(c *gin.Context) {
userId, _ := c.Get("userId")
projectsArr, err := ps.Get(c.Request.Context(), userId.(int))
if err != nil {
l.Warn(err.Error())
return
}
type GetProject struct {
Id int `json:"id" binding:"required"`
Name string `json:"name" binding:"required"`
MemberIds []int `json:"memberIds" binding:"required"`
AdminIds []int `json:"adminIds" binding:"required"`
}
getProject := make([]GetProject, 0)
for _, p := range projectsArr {
getProject = append(getProject, GetProject{
Id: p.Id,
Name: p.Name,
MemberIds: p.MemberIds,
AdminIds: p.AdminIds,
})
}
c.JSON(http.StatusOK, getProject)
})
containers := r.Group("/containers", BasicAuthMiddleware(l, us))
containers.GET("/", func(c *gin.Context) {
type container struct {
@ -141,7 +189,7 @@ func setupCache(l *zap.Logger) *cache.Cache {
l.Info("Setting up cache")
ristrettoCache, err := ristretto.NewCache(&ristretto.Config{
NumCounters: 1000,
MaxCost: 100,
MaxCost: 100_000_000,
BufferItems: 64,
})
if err != nil {
@ -188,6 +236,8 @@ func main() {
database := db.NewClient(logger)
usersRepository := postgres.NewUsersRepository(database)
usersService := users.NewService(logger, usersRepository, cacheM)
projectsRepository := postgres.NewProjectsRepository(database)
projectsService := projects.NewService(logger, projectsRepository, cacheM)
setupApi(logger, cacheM, usersService)
setupApi(logger, cacheM, usersService, projectsService)
}

View File

@ -1,9 +1,10 @@
create table users(
id serial primary key,
email varchar(320) not null,
password_hash varchar(256) not null
create table sctl_user
(
id int GENERATED BY DEFAULT AS IDENTITY primary key,
email varchar(320) not null,
password_hash varchar(256) not null
);
---- create above / drop below ----
drop table users;
drop table sctl_user;

View File

@ -1,10 +1,10 @@
-- Write your migrate up statements here
create unique index users_unique_index
on users(email);
create unique index user_email_unique_index
on sctl_user(email);
---- create above / drop below ----
drop index users_unique_index;
drop index user_email_unique_index;
-- Write your migrate down statements here. If this migration is irreversible
-- Then delete the separator line above.

View File

@ -0,0 +1,14 @@
-- Write your migrate up statements here
create table sctl_project
(
id int GENERATED BY DEFAULT AS IDENTITY primary key,
data jsonb NOT NULL
);
---- create above / drop below ----
drop table sctl_project;
-- Write your migrate down statements here. If this migration is irreversible
-- Then delete the separator line above.

View File

@ -31,4 +31,4 @@ sslmode = prefer
[data]
# Any fields in the data section are available in migration templates
# prefix = foo
prefix = serverctl

View File

@ -0,0 +1,31 @@
package projects
type Project struct {
Id int
Name string
MemberIds []int
AdminIds []int
}
func NewProject(id int, name string, memberIds []int, adminIds []int) *Project {
return &Project{
Id: id,
Name: name,
MemberIds: memberIds,
AdminIds: adminIds,
}
}
type CreateProject struct {
Name string
MemberIds []int
AdminIds []int
}
func NewCreateProject(name string, userId int) *CreateProject {
return &CreateProject{
Name: name,
MemberIds: []int{userId},
AdminIds: []int{userId},
}
}

View File

@ -0,0 +1,8 @@
package projects
import "context"
type Repository interface {
Create(ctx context.Context, project *CreateProject) (int, error)
GetForMemberId(ctx context.Context, memberId int) ([]*Project, error)
}

View File

@ -0,0 +1,59 @@
package projects
import (
"context"
"fmt"
"github.com/eko/gocache/cache"
"go.uber.org/zap"
)
type Service struct {
projectsRepository Repository
logger *zap.Logger
cache *cache.Cache
}
func NewService(logger *zap.Logger, projectsRepository Repository, cache *cache.Cache) *Service {
return &Service{
logger: logger,
projectsRepository: projectsRepository,
cache: cache}
}
func (s *Service) CreateProject(ctx context.Context, userId int, name string) (int, error) {
s.logger.Debug("creating project",
zap.String("name", name),
zap.Int("creatorId", userId))
projectId, err := s.projectsRepository.Create(ctx, NewCreateProject(name, userId))
if err != nil {
s.logger.Warn(err.Error())
return -1, err
}
_ = s.cache.Delete(fmt.Sprintf("projects_userId_%d", userId))
return projectId, nil
}
func (s *Service) Get(ctx context.Context, userId int) ([]*Project, error) {
s.logger.Debug("getting projects",
zap.Int("userId", userId))
loadFunc := func(key interface{}) (interface{}, error) {
s.logger.Debug("getting projects from repository",
zap.Int("userId", userId))
return s.projectsRepository.GetForMemberId(ctx, userId)
}
cacheEntry := cache.NewLoadable(
loadFunc,
s.cache)
entry, err := cacheEntry.Get(fmt.Sprintf("projects_userId_%d", userId))
if err != nil {
return nil, err
}
return entry.([]*Project), nil
}

View File

@ -2,6 +2,7 @@ package users
import (
"context"
"fmt"
"github.com/eko/gocache/cache"
"go.uber.org/zap"
)
@ -39,6 +40,15 @@ func (s *Service) Create(email string, password string) (int, error) {
}
func (s *Service) Authenticate(ctx context.Context, email string, password string) (*User, error) {
user, err := s.repository.GetByEmail(ctx, email, s.passwordHasher.HashPassword(password))
return user, err
loadFunc := func(key interface{}) (interface{}, error) {
s.logger.Debug("getting user from cache", zap.String("email", email))
return s.repository.GetByEmail(ctx, email, s.passwordHasher.HashPassword(password))
}
get, err := cache.NewLoadable(loadFunc, s.cache).Get(fmt.Sprintf("user_email_%s", email))
if err != nil {
return nil, err
}
return get.(*User), nil
}

View File

@ -0,0 +1,66 @@
package postgres
import (
"context"
"serverctl/pkg/application/projects"
"serverctl/pkg/db"
)
var _ projects.Repository = &ProjectsRepository{}
type ProjectsRepository struct {
db *db.Client
}
func NewProjectsRepository(db *db.Client) projects.Repository {
return &ProjectsRepository{db: db}
}
type projectData struct {
Name string `json:"name"`
MemberIds []int `json:"memberIds"`
AdminIds []int `json:"adminIds"`
}
func NewProjectData(project *projects.CreateProject) projectData {
return projectData{
Name: project.Name,
AdminIds: project.AdminIds,
MemberIds: project.MemberIds,
}
}
func (p ProjectsRepository) Create(ctx context.Context, project *projects.CreateProject) (int, error) {
conn := p.db.GetConn(ctx)
defer conn.Release()
var projectId int
err := conn.QueryRow(ctx, "insert into sctl_project(data) values ($1) returning id", NewProjectData(project)).Scan(&projectId)
if err != nil {
return -1, err
}
return projectId, nil
}
func (p ProjectsRepository) GetForMemberId(ctx context.Context, memberId int) ([]*projects.Project, error) {
conn := p.db.GetConn(ctx)
defer conn.Release()
rows, _ := conn.Query(ctx, "select id, data from sctl_project")
projectsArr := make([]*projects.Project, 0)
for rows.Next() {
var (
id int
data projectData
)
err := rows.Scan(&id, &data)
if err != nil {
return nil, err
}
projectsArr = append(projectsArr, projects.NewProject(id, data.Name, data.MemberIds, data.AdminIds))
}
return projectsArr, nil
}

View File

@ -3,26 +3,26 @@ package postgres
import (
"context"
"errors"
users2 "serverctl/pkg/application/users"
"serverctl/pkg/db"
"serverctl/pkg/users"
)
var _ users.Repository = &usersRepository{}
var _ users2.Repository = &usersRepository{}
type usersRepository struct {
databasePool *db.Client
}
func NewUsersRepository(db *db.Client) users.Repository {
func NewUsersRepository(db *db.Client) users2.Repository {
return &usersRepository{db}
}
func (u *usersRepository) Create(ctx context.Context, user *users.CreateUser) (int, error) {
func (u *usersRepository) Create(ctx context.Context, user *users2.CreateUser) (int, error) {
var userId int
conn := u.databasePool.GetConn(ctx)
defer conn.Release()
conn.QueryRow(ctx, "INSERT INTO users(email, password_hash) values ($1, $2) RETURNING id", user.Email, user.PasswordHash).Scan(&userId)
conn.QueryRow(ctx, "INSERT INTO sctl_user(email, password_hash) values ($1, $2) RETURNING id", user.Email, user.PasswordHash).Scan(&userId)
if userId == 0 {
return -1, errors.New("could not insert data into users table")
@ -31,12 +31,12 @@ func (u *usersRepository) Create(ctx context.Context, user *users.CreateUser) (i
return userId, nil
}
func (u *usersRepository) GetByEmail(ctx context.Context, email string, passwordHash string) (*users.User, error) {
func (u *usersRepository) GetByEmail(ctx context.Context, email string, passwordHash string) (*users2.User, error) {
conn := u.databasePool.GetConn(ctx)
defer conn.Release()
var id int
err := conn.QueryRow(ctx, "select id from users where email = $1 and password_hash = $2", email, passwordHash).Scan(&id)
err := conn.QueryRow(ctx, "select id from sctl_user where email = $1 and password_hash = $2", email, passwordHash).Scan(&id)
if err != nil {
return nil, err
}
@ -45,5 +45,5 @@ func (u *usersRepository) GetByEmail(ctx context.Context, email string, password
return nil, errors.New("user with that password doesn't exist")
}
return users.NewUser(id, email), nil
return users2.NewUser(id, email), nil
}