init server
This commit is contained in:
37
internal/account/database.go
Normal file
37
internal/account/database.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"nos-comptes/internal/storage/dao/postgresql"
|
||||
)
|
||||
|
||||
type Database struct {
|
||||
*postgresql.DatabasePostgreSQL
|
||||
}
|
||||
|
||||
func (db *Database) GetAllAccountOfUser(id string) ([]*Account, error) {
|
||||
q := `
|
||||
SELECT a.id, a.user_id, a.name, a.provider, a.created_at, a.updated_at
|
||||
FROM public.account a
|
||||
WHERE a.id = $1
|
||||
`
|
||||
rows, err := db.Session.Query(q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
as := make([]*Account, 0)
|
||||
for rows.Next() {
|
||||
a := Account{}
|
||||
err := rows.Scan(&a.ID, &a.userId, &a.name, &a.provider, &a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
as = append(as, &a)
|
||||
}
|
||||
return as, nil
|
||||
}
|
||||
|
||||
func NewDatabase(db *postgresql.DatabasePostgreSQL) *Database {
|
||||
return &Database{db}
|
||||
}
|
||||
76
internal/account/handler.go
Normal file
76
internal/account/handler.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"nos-comptes/handler"
|
||||
"nos-comptes/internal/storage/dao/postgresql"
|
||||
"nos-comptes/internal/storage/model"
|
||||
"nos-comptes/internal/storage/validators"
|
||||
"nos-comptes/internal/user"
|
||||
"nos-comptes/internal/utils"
|
||||
utils2 "nos-comptes/internal/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
service *Service
|
||||
db *Database
|
||||
userService *user.Service
|
||||
*handler.Context
|
||||
}
|
||||
|
||||
func (c *Context) GetAllAccountOfUser(gc *gin.Context) {
|
||||
userId := gc.Param("userId")
|
||||
err := c.Validator.VarCtx(gc, userId, "uuid4")
|
||||
if err != nil {
|
||||
utils2.JSONError(gc.Writer, validators.NewDataValidationAPIError(err))
|
||||
return
|
||||
}
|
||||
|
||||
_, err = c.userService.GetUserById(userId)
|
||||
if e, ok := err.(*model.APIError); ok {
|
||||
utils.GetLoggerFromCtx(gc).WithError(err).WithField("type", e.Type).Error("error GetUser: get user error")
|
||||
utils.JSONErrorWithMessage(gc.Writer, *e, e.Description)
|
||||
} else if err != nil {
|
||||
utils.GetLoggerFromCtx(gc).WithError(err).Error("error while get user")
|
||||
utils.JSONError(gc.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
accounts, err := c.service.GetAllAccountOfUser(userId)
|
||||
if e, ok := err.(*model.APIError); ok {
|
||||
utils.GetLoggerFromCtx(gc).WithError(err).WithField("type", e.Type).Error("error GetAllAccounts: get accounts")
|
||||
utils.JSONErrorWithMessage(gc.Writer, *e, e.Description)
|
||||
} else if err != nil {
|
||||
utils.GetLoggerFromCtx(gc).WithError(err).Error("error while get accounts")
|
||||
utils.JSONError(gc.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
if len(accounts) == 0 {
|
||||
utils.JSON(gc.Writer, http.StatusNoContent, nil)
|
||||
} else {
|
||||
utils.JSON(gc.Writer, http.StatusOK, accounts)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (c *Context) CreateAccountOfUser(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func (c *Context) DeleteAccountOfUser(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func (c *Context) GetSpecificAccountOfUser(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func NewHandler(ctx *handler.Context, db *postgresql.DatabasePostgreSQL) *Context {
|
||||
database := NewDatabase(db)
|
||||
service := NewService(database)
|
||||
userService := user.NewService(user.NewDatabase(db))
|
||||
return &Context{service: service, db: database, userService: userService, Context: ctx}
|
||||
}
|
||||
16
internal/account/model.go
Normal file
16
internal/account/model.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package account
|
||||
|
||||
import "time"
|
||||
|
||||
type Account struct {
|
||||
AccountEditable
|
||||
userId string `json:"userId"`
|
||||
}
|
||||
|
||||
type AccountEditable struct {
|
||||
ID string `json:"id"`
|
||||
name string `json:"name"`
|
||||
provider string `json:"provider"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt *time.Time `json:"updatedAt"`
|
||||
}
|
||||
33
internal/account/service.go
Normal file
33
internal/account/service.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"nos-comptes/internal/storage/dao"
|
||||
"nos-comptes/internal/storage/model"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
db *Database
|
||||
}
|
||||
|
||||
func (s *Service) GetAllAccountOfUser(userId string) ([]*Account, error) {
|
||||
accounts, err := s.db.GetAllAccountOfUser(userId)
|
||||
if e, ok := err.(*dao.Error); ok {
|
||||
switch {
|
||||
case e.Type == dao.ErrTypeNotFound:
|
||||
return nil, &model.ErrNotFound
|
||||
default:
|
||||
return nil, &model.ErrInternalServer
|
||||
}
|
||||
} else if err != nil {
|
||||
return nil, &model.ErrInternalServer
|
||||
}
|
||||
|
||||
if accounts == nil {
|
||||
return nil, &model.ErrNotFound
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
func NewService(database *Database) *Service {
|
||||
return &Service{db: database}
|
||||
}
|
||||
11
internal/expense/database.go
Normal file
11
internal/expense/database.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package expense
|
||||
|
||||
import "nos-comptes/internal/storage/dao/postgresql"
|
||||
|
||||
type Database struct {
|
||||
*postgresql.DatabasePostgreSQL
|
||||
}
|
||||
|
||||
func NewDatabase(db *postgresql.DatabasePostgreSQL) *Database {
|
||||
return &Database{db}
|
||||
}
|
||||
36
internal/expense/handler.go
Normal file
36
internal/expense/handler.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package expense
|
||||
|
||||
import (
|
||||
"nos-comptes/handler"
|
||||
"nos-comptes/internal/storage/dao/postgresql"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
service *Service
|
||||
db *Database
|
||||
*handler.Context
|
||||
}
|
||||
|
||||
func (c *Context) CreateAnExpense(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func (c *Context) DeleteExpense(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func (c *Context) GetAllExpenses(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func (c *Context) GetAnExpenses(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func NewHandler(ctx *handler.Context, db *postgresql.DatabasePostgreSQL) *Context {
|
||||
database := NewDatabase(db)
|
||||
service := NewService(database)
|
||||
return &Context{service: service, db: database, Context: ctx}
|
||||
}
|
||||
4
internal/expense/model.go
Normal file
4
internal/expense/model.go
Normal file
@@ -0,0 +1,4 @@
|
||||
package expense
|
||||
|
||||
type Account struct {
|
||||
}
|
||||
9
internal/expense/service.go
Normal file
9
internal/expense/service.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package expense
|
||||
|
||||
type Service struct {
|
||||
Db *Database
|
||||
}
|
||||
|
||||
func NewService(database *Database) *Service {
|
||||
return &Service{Db: database}
|
||||
}
|
||||
11
internal/shared-account/database.go
Normal file
11
internal/shared-account/database.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package sharedaccount
|
||||
|
||||
import "nos-comptes/internal/storage/dao/postgresql"
|
||||
|
||||
type Database struct {
|
||||
*postgresql.DatabasePostgreSQL
|
||||
}
|
||||
|
||||
func NewDatabase(db *postgresql.DatabasePostgreSQL) *Database {
|
||||
return &Database{db}
|
||||
}
|
||||
37
internal/shared-account/handler.go
Normal file
37
internal/shared-account/handler.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package sharedaccount
|
||||
|
||||
import (
|
||||
"nos-comptes/handler"
|
||||
"nos-comptes/internal/storage/dao/postgresql"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
service *Service
|
||||
db *Database
|
||||
*handler.Context
|
||||
}
|
||||
|
||||
func (c *Context) ShareAnAccount(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func (c *Context) DeleteSharedAccount(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func (c *Context) GetAllSharedAccountOfUser(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func (c *Context) GetSpecificSharedAccountOfUser(context *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
func NewHandler(ctx *handler.Context, db *postgresql.DatabasePostgreSQL) *Context {
|
||||
database := NewDatabase(db)
|
||||
service := NewService(database)
|
||||
return &Context{service: service, db: database, Context: ctx}
|
||||
|
||||
}
|
||||
4
internal/shared-account/model.go
Normal file
4
internal/shared-account/model.go
Normal file
@@ -0,0 +1,4 @@
|
||||
package sharedaccount
|
||||
|
||||
type SharedAccount struct {
|
||||
}
|
||||
9
internal/shared-account/service.go
Normal file
9
internal/shared-account/service.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package sharedaccount
|
||||
|
||||
type Service struct {
|
||||
Db *Database
|
||||
}
|
||||
|
||||
func NewService(database *Database) *Service {
|
||||
return &Service{Db: database}
|
||||
}
|
||||
32
internal/storage/dao/database_error.go
Executable file
32
internal/storage/dao/database_error.go
Executable file
@@ -0,0 +1,32 @@
|
||||
package dao
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Type int
|
||||
|
||||
const (
|
||||
ErrTypeNotFound Type = iota
|
||||
ErrTypeDuplicate
|
||||
ErrTypeForeignKeyViolation
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
Cause error
|
||||
Type Type
|
||||
}
|
||||
|
||||
func NewDAOError(t Type, cause error) error {
|
||||
return &Error{
|
||||
Type: t,
|
||||
Cause: cause,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
if e.Cause != nil {
|
||||
return fmt.Sprintf("Type %d: %s", e.Type, e.Cause.Error())
|
||||
}
|
||||
return fmt.Sprintf("Type %d: no cause given", e.Type)
|
||||
}
|
||||
43
internal/storage/dao/postgresql/database_postgresql.go
Executable file
43
internal/storage/dao/postgresql/database_postgresql.go
Executable file
@@ -0,0 +1,43 @@
|
||||
package postgresql
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"nos-comptes/internal/storage/dao"
|
||||
"nos-comptes/internal/utils"
|
||||
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
const (
|
||||
pgCodeUniqueViolation = "23505"
|
||||
pgCodeForeingKeyViolation = "23503"
|
||||
)
|
||||
|
||||
func HandlePgError(e *pq.Error) error {
|
||||
if e.Code == pgCodeUniqueViolation {
|
||||
return dao.NewDAOError(dao.ErrTypeDuplicate, e)
|
||||
}
|
||||
|
||||
if e.Code == pgCodeForeingKeyViolation {
|
||||
return dao.NewDAOError(dao.ErrTypeForeignKeyViolation, e)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
type DatabasePostgreSQL struct {
|
||||
Session *sql.DB
|
||||
}
|
||||
|
||||
func NewDatabasePostgreSQL(connectionURI string) *DatabasePostgreSQL {
|
||||
db, err := sql.Open("postgres", connectionURI)
|
||||
if err != nil {
|
||||
utils.GetLogger().WithError(err).Fatal("Unable to get a connection to the postgres db")
|
||||
}
|
||||
err = db.Ping()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
utils.GetLogger().WithError(err).Fatal("Unable to ping the postgres db")
|
||||
}
|
||||
return &DatabasePostgreSQL{Session: db}
|
||||
}
|
||||
68
internal/storage/model/error.go
Normal file
68
internal/storage/model/error.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
var (
|
||||
// 400
|
||||
ErrBadRequestFormat = APIError{
|
||||
Type: "bad_format",
|
||||
HTTPCode: http.StatusBadRequest,
|
||||
Description: "unable to read request body, please check that the json is valid",
|
||||
}
|
||||
ErrDataValidation = APIError{
|
||||
Type: "data_validation",
|
||||
HTTPCode: http.StatusBadRequest,
|
||||
Description: "the data are not valid",
|
||||
}
|
||||
|
||||
// 404
|
||||
ErrNotFound = APIError{
|
||||
Type: "not_found",
|
||||
HTTPCode: http.StatusNotFound,
|
||||
}
|
||||
|
||||
// 40x
|
||||
ErrAlreadyExists = APIError{
|
||||
Type: "already_exists",
|
||||
HTTPCode: http.StatusConflict,
|
||||
}
|
||||
|
||||
// 50x
|
||||
ErrInternalServer = APIError{
|
||||
Type: "internal_server_error",
|
||||
HTTPCode: http.StatusInternalServerError,
|
||||
}
|
||||
)
|
||||
|
||||
type APIError struct {
|
||||
HTTPCode int `json:"-"`
|
||||
Type string `json:"error"`
|
||||
Description string `json:"error_description"`
|
||||
Details []FieldError `json:"error_details,omitempty"`
|
||||
Headers map[string][]string `json:"-"`
|
||||
}
|
||||
|
||||
type FieldError struct {
|
||||
Field string `json:"field"`
|
||||
Constraint string `json:"constraint"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string {
|
||||
return fmt.Sprintf("error : %d, %s, %s, %v", e.HTTPCode, e.Type, e.Description, e.Details)
|
||||
}
|
||||
|
||||
func FromPostgresError(err *pq.Error) *APIError {
|
||||
return &APIError{
|
||||
HTTPCode: 0,
|
||||
Type: "",
|
||||
Description: "",
|
||||
Details: nil,
|
||||
Headers: nil,
|
||||
}
|
||||
}
|
||||
44
internal/storage/validators/error.go
Executable file
44
internal/storage/validators/error.go
Executable file
@@ -0,0 +1,44 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"nos-comptes/internal/storage/model"
|
||||
"nos-comptes/internal/utils"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/go-playground/validator.v9"
|
||||
)
|
||||
|
||||
var regexpValidatorNamespacePrefix = regexp.MustCompile(`^\w+\.`)
|
||||
|
||||
func NewDataValidationAPIError(err error) model.APIError {
|
||||
apiErr := model.ErrDataValidation
|
||||
if err != nil {
|
||||
if _, ok := err.(*validator.InvalidValidationError); ok {
|
||||
utils.GetLogger().WithError(err).WithField("templateAPIErr", apiErr).Error("InvalidValidationError")
|
||||
} else {
|
||||
for _, e := range err.(validator.ValidationErrors) {
|
||||
reason := e.Tag()
|
||||
if _, ok := CustomValidators[e.Tag()]; ok {
|
||||
reason = truncatingSprintf(CustomValidators[e.Tag()].Message, e.Param())
|
||||
}
|
||||
|
||||
namespaceWithoutStructName := regexpValidatorNamespacePrefix.ReplaceAllString(e.Namespace(), "")
|
||||
fe := model.FieldError{
|
||||
Field: namespaceWithoutStructName,
|
||||
Constraint: e.Tag(),
|
||||
Description: reason,
|
||||
}
|
||||
apiErr.Details = append(apiErr.Details, fe)
|
||||
}
|
||||
}
|
||||
}
|
||||
return apiErr
|
||||
}
|
||||
|
||||
// truncatingSprintf is used as fmt.Sprintf but allow to truncate the additional parameters given when there is more parameters than %v in str
|
||||
func truncatingSprintf(str string, args ...interface{}) string {
|
||||
n := strings.Count(str, "%v")
|
||||
return fmt.Sprintf(str, args[:n]...)
|
||||
}
|
||||
34
internal/storage/validators/validators.go
Executable file
34
internal/storage/validators/validators.go
Executable file
@@ -0,0 +1,34 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/go-playground/validator.v9"
|
||||
)
|
||||
|
||||
var (
|
||||
CustomValidators = map[string]customValidator{
|
||||
"enum": {
|
||||
Message: "This field should be in: %v",
|
||||
Validator: validateEnum,
|
||||
},
|
||||
"required": {
|
||||
Message: "This field is required and cannot be empty",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
type customValidator struct {
|
||||
Message string
|
||||
Validator validator.FuncCtx
|
||||
}
|
||||
|
||||
func validateEnum(ctx context.Context, fl validator.FieldLevel) bool {
|
||||
for _, v := range strings.Split(fl.Param(), " ") {
|
||||
if v == fl.Field().String() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
113
internal/user/database.go
Executable file
113
internal/user/database.go
Executable file
@@ -0,0 +1,113 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"nos-comptes/internal/storage/dao"
|
||||
"nos-comptes/internal/storage/dao/postgresql"
|
||||
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
type Database struct {
|
||||
*postgresql.DatabasePostgreSQL
|
||||
}
|
||||
|
||||
func NewDatabase(db *postgresql.DatabasePostgreSQL) *Database {
|
||||
return &Database{db}
|
||||
}
|
||||
|
||||
func (db *Database) GetAllUsers() ([]*User, error) {
|
||||
q := `
|
||||
SELECT u.id, u.created_at, u.updated_at, u.email
|
||||
FROM public.user u
|
||||
`
|
||||
rows, err := db.Session.Query(q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
us := make([]*User, 0)
|
||||
for rows.Next() {
|
||||
u := User{}
|
||||
err := rows.Scan(&u.ID, &u.CreatedAt, &u.UpdatedAt, &u.Email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
us = append(us, &u)
|
||||
}
|
||||
return us, nil
|
||||
}
|
||||
|
||||
func (db *Database) GetUsersByID(id string) (*User, error) {
|
||||
q := `
|
||||
SELECT u.id, u.created_at, u.updated_at, u.email
|
||||
FROM public.user u
|
||||
WHERE u.id = $1
|
||||
`
|
||||
row := db.Session.QueryRow(q, id)
|
||||
|
||||
u := User{}
|
||||
err := row.Scan(&u.ID, &u.CreatedAt, &u.UpdatedAt, &u.Email)
|
||||
if errPq, ok := err.(*pq.Error); ok {
|
||||
return nil, postgresql.HandlePgError(errPq)
|
||||
}
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, dao.NewDAOError(dao.ErrTypeNotFound, err)
|
||||
}
|
||||
return &u, err
|
||||
}
|
||||
|
||||
func (db *Database) CreateUser(user *User) error {
|
||||
q := `
|
||||
INSERT INTO public.user
|
||||
(email, google_id)
|
||||
VALUES
|
||||
($1, $2)
|
||||
RETURNING id, created_at
|
||||
`
|
||||
|
||||
err := db.Session.
|
||||
QueryRow(q, user.Email, user.GoogleID).
|
||||
Scan(&user.ID, &user.CreatedAt)
|
||||
if errPq, ok := err.(*pq.Error); ok {
|
||||
return postgresql.HandlePgError(errPq)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (db *Database) DeleteUser(id string) error {
|
||||
q := `
|
||||
DELETE FROM public.user
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
_, err := db.Session.Exec(q, id)
|
||||
if errPq, ok := err.(*pq.Error); ok {
|
||||
return postgresql.HandlePgError(errPq)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (db *Database) UpdateUser(user *User) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db *Database) GetUsersByGoogleID(id string) (*User, error) {
|
||||
q := `
|
||||
SELECT u.id, u.created_at, u.updated_at, u.email, u.google_id
|
||||
FROM public.user u
|
||||
WHERE u.google_id = $1
|
||||
`
|
||||
row := db.Session.QueryRow(q, id)
|
||||
|
||||
u := User{}
|
||||
err := row.Scan(&u.ID, &u.CreatedAt, &u.UpdatedAt, &u.Email, &u.GoogleID)
|
||||
if errPq, ok := err.(*pq.Error); ok {
|
||||
return nil, postgresql.HandlePgError(errPq)
|
||||
}
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, dao.NewDAOError(dao.ErrTypeNotFound, err)
|
||||
}
|
||||
return &u, err
|
||||
}
|
||||
156
internal/user/handler.go
Executable file
156
internal/user/handler.go
Executable file
@@ -0,0 +1,156 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"nos-comptes/handler"
|
||||
"nos-comptes/internal/storage/dao/postgresql"
|
||||
"nos-comptes/internal/storage/model"
|
||||
"nos-comptes/internal/storage/validators"
|
||||
"nos-comptes/internal/utils"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"google.golang.org/api/oauth2/v2"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
service *Service
|
||||
db *Database
|
||||
*handler.Context
|
||||
}
|
||||
|
||||
func NewHandler(ctx *handler.Context, db *postgresql.DatabasePostgreSQL) *Context {
|
||||
database := NewDatabase(db)
|
||||
service := NewService(database)
|
||||
return &Context{service: service, db: database, Context: ctx}
|
||||
}
|
||||
|
||||
func (uc *Context) GetAllUsers(c *gin.Context) {
|
||||
users, err := uc.db.GetAllUsers()
|
||||
if err != nil {
|
||||
utils.GetLoggerFromCtx(c).WithError(err).Error("error while getting users")
|
||||
utils.JSONErrorWithMessage(c.Writer, model.ErrInternalServer, "Error while getting users")
|
||||
return
|
||||
}
|
||||
utils.JSON(c.Writer, http.StatusOK, users)
|
||||
}
|
||||
|
||||
func (hc *Context) ConnectUser(c *gin.Context) {
|
||||
authorizationHeader := c.GetHeader("Authorization")
|
||||
authorizationHeaderSplitted := strings.Split(authorizationHeader, " ")
|
||||
if len(authorizationHeaderSplitted) != 2 {
|
||||
utils.JSONError(c.Writer, model.ErrBadRequestFormat)
|
||||
return
|
||||
}
|
||||
|
||||
oauth2Service, err := oauth2.New(&http.Client{})
|
||||
if oauth2Service == nil {
|
||||
fmt.Println(err)
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
tokenInfoCall := oauth2Service.Tokeninfo()
|
||||
tokenInfoCall.IdToken(authorizationHeaderSplitted[1])
|
||||
tokenInfo, err := tokenInfoCall.Do()
|
||||
if err != nil {
|
||||
utils.GetLogger().WithError(err).Error(err)
|
||||
utils.JSONError(c.Writer, model.ErrBadRequestFormat)
|
||||
return
|
||||
}
|
||||
user, err := hc.service.GetUserFromGoogleID(tokenInfo.UserId)
|
||||
if err != nil {
|
||||
utils.GetLogger().WithError(err).Error(err)
|
||||
if castedError, ok := err.(*model.APIError); ok {
|
||||
if castedError.Type == model.ErrNotFound.Type {
|
||||
user, err := hc.service.CreateUserFromGoogleToken(tokenInfo.UserId, tokenInfo.Email)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
utils.JSON(c.Writer, 200, user)
|
||||
return
|
||||
}
|
||||
utils.JSONError(c.Writer, *castedError)
|
||||
return
|
||||
}
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
fmt.Println("Found the user " + user.Email)
|
||||
fmt.Println("Return 200")
|
||||
utils.JSON(c.Writer, 200, user)
|
||||
}
|
||||
|
||||
func (hc *Context) CreateUser(c *gin.Context) {
|
||||
authorizationHeader := c.GetHeader("Authorization")
|
||||
authorizationHeaderSplitted := strings.Split(authorizationHeader, " ")
|
||||
if len(authorizationHeaderSplitted) != 2 {
|
||||
utils.JSONError(c.Writer, model.ErrBadRequestFormat)
|
||||
return
|
||||
}
|
||||
|
||||
oauth2Service, err := oauth2.New(&http.Client{})
|
||||
if oauth2Service == nil {
|
||||
fmt.Println(err)
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
tokenInfoCall := oauth2Service.Tokeninfo()
|
||||
tokenInfoCall.IdToken(authorizationHeaderSplitted[1])
|
||||
tokenInfo, err := tokenInfoCall.Do()
|
||||
if err != nil {
|
||||
utils.GetLogger().WithError(err).Error(err)
|
||||
utils.JSONError(c.Writer, model.ErrBadRequestFormat)
|
||||
return
|
||||
}
|
||||
user, err := hc.service.GetUserFromGoogleID(tokenInfo.UserId)
|
||||
if err != nil {
|
||||
utils.GetLogger().WithError(err).Error(err)
|
||||
if castedError, ok := err.(*model.APIError); ok {
|
||||
if castedError.Type == model.ErrNotFound.Type {
|
||||
user, err := hc.service.CreateUserFromGoogleToken(tokenInfo.UserId, tokenInfo.Email)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
utils.JSON(c.Writer, http.StatusCreated, user)
|
||||
return
|
||||
}
|
||||
utils.JSONError(c.Writer, *castedError)
|
||||
return
|
||||
}
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
utils.JSON(c.Writer, http.StatusOK, user)
|
||||
}
|
||||
|
||||
func (hc *Context) GetUser(c *gin.Context) {
|
||||
userID := c.Param("userId")
|
||||
|
||||
err := hc.Validator.VarCtx(c, userID, "uuid4")
|
||||
if err != nil {
|
||||
utils.JSONError(c.Writer, validators.NewDataValidationAPIError(err))
|
||||
return
|
||||
}
|
||||
|
||||
user, err := hc.service.GetUserById(userID)
|
||||
if e, ok := err.(*model.APIError); ok {
|
||||
utils.GetLoggerFromCtx(c).WithError(err).WithField("type", e.Type).Error("error GetUser: get user error")
|
||||
utils.JSONErrorWithMessage(c.Writer, *e, e.Description)
|
||||
} else if err != nil {
|
||||
utils.GetLoggerFromCtx(c).WithError(err).Error("error while get user")
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
if user == nil {
|
||||
utils.JSONErrorWithMessage(c.Writer, model.ErrNotFound, "User not found")
|
||||
return
|
||||
}
|
||||
|
||||
utils.JSON(c.Writer, http.StatusOK, user)
|
||||
}
|
||||
17
internal/user/model.go
Executable file
17
internal/user/model.go
Executable file
@@ -0,0 +1,17 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
UserEditable
|
||||
ID string `json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt *time.Time `json:"updatedAt"`
|
||||
GoogleID string `json:"-"`
|
||||
}
|
||||
|
||||
type UserEditable struct {
|
||||
Email string `json:"email" validate:"required"`
|
||||
}
|
||||
55
internal/user/service.go
Normal file
55
internal/user/service.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"nos-comptes/internal/storage/dao"
|
||||
"nos-comptes/internal/storage/model"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
db *Database
|
||||
}
|
||||
|
||||
func NewService(database *Database) *Service {
|
||||
return &Service{db: database}
|
||||
}
|
||||
|
||||
func (s *Service) GetUserById(userId string) (*User, error) {
|
||||
user, err := s.db.GetUsersByID(userId)
|
||||
if e, ok := err.(*dao.Error); ok {
|
||||
switch {
|
||||
case e.Type == dao.ErrTypeNotFound:
|
||||
return nil, &model.ErrNotFound
|
||||
default:
|
||||
return nil, &model.ErrInternalServer
|
||||
}
|
||||
} else if err != nil {
|
||||
return nil, &model.ErrInternalServer
|
||||
}
|
||||
|
||||
if user == nil {
|
||||
return nil, &model.ErrNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (us *Service) GetUserFromGoogleID(googleUserID string) (*User, error) {
|
||||
user, err := us.db.GetUsersByGoogleID(googleUserID)
|
||||
if err != nil {
|
||||
if castedError, ok := err.(*dao.Error); ok {
|
||||
switch castedError.Type {
|
||||
case dao.ErrTypeNotFound:
|
||||
return nil, &model.ErrNotFound
|
||||
default:
|
||||
return nil, &model.ErrInternalServer
|
||||
}
|
||||
}
|
||||
return nil, &model.ErrInternalServer
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (us *Service) CreateUserFromGoogleToken(id string, email string) (*User, error) {
|
||||
user := &User{UserEditable: UserEditable{Email: email}, GoogleID: id}
|
||||
err := us.db.CreateUser(user)
|
||||
return user, err
|
||||
}
|
||||
8
internal/utils/headers.go
Executable file
8
internal/utils/headers.go
Executable file
@@ -0,0 +1,8 @@
|
||||
package utils
|
||||
|
||||
const (
|
||||
HeaderNameContentType = "content-type"
|
||||
HeaderNameCorrelationID = "correlationID"
|
||||
|
||||
HeaderValueApplicationJSONUTF8 = "application/json; charset=UTF-8"
|
||||
)
|
||||
74
internal/utils/logger.go
Executable file
74
internal/utils/logger.go
Executable file
@@ -0,0 +1,74 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
LogFormatText = "text"
|
||||
LogFormatJSON = "json"
|
||||
|
||||
ContextKeyLogger = "logger"
|
||||
)
|
||||
|
||||
var (
|
||||
logLevel = logrus.DebugLevel
|
||||
logFormat logrus.Formatter = &logrus.TextFormatter{}
|
||||
logOut io.Writer
|
||||
)
|
||||
|
||||
func InitLogger(ll, lf string) {
|
||||
logLevel = parseLogrusLevel(ll)
|
||||
logrus.SetLevel(logLevel)
|
||||
|
||||
logFormat = parseLogrusFormat(lf)
|
||||
logrus.SetFormatter(logFormat)
|
||||
|
||||
logOut = os.Stdout
|
||||
logrus.SetOutput(logOut)
|
||||
}
|
||||
|
||||
func GetLoggerFromCtx(c *gin.Context) *logrus.Entry {
|
||||
if logger, ok := c.Get(ContextKeyLogger); ok {
|
||||
logEntry, assertionOk := logger.(*logrus.Entry)
|
||||
if assertionOk {
|
||||
return logEntry
|
||||
}
|
||||
}
|
||||
return logrus.NewEntry(GetLogger())
|
||||
}
|
||||
|
||||
func GetLogger() *logrus.Logger {
|
||||
logger := logrus.New()
|
||||
logger.Formatter = logFormat
|
||||
logger.Level = logLevel
|
||||
logger.Out = logOut
|
||||
return logger
|
||||
}
|
||||
|
||||
func parseLogrusLevel(logLevelStr string) logrus.Level {
|
||||
logLevel, err := logrus.ParseLevel(logLevelStr)
|
||||
if err != nil {
|
||||
logrus.WithError(err).Errorf("error while parsing log level. %v is set as default.", logLevel)
|
||||
logLevel = logrus.DebugLevel
|
||||
}
|
||||
return logLevel
|
||||
}
|
||||
|
||||
func parseLogrusFormat(logFormatStr string) logrus.Formatter {
|
||||
var formatter logrus.Formatter
|
||||
switch logFormatStr {
|
||||
case LogFormatText:
|
||||
formatter = &logrus.TextFormatter{ForceColors: true, FullTimestamp: true}
|
||||
case LogFormatJSON:
|
||||
formatter = &logrus.JSONFormatter{}
|
||||
default:
|
||||
logrus.Errorf("error while parsing log format. %v is set as default.", formatter)
|
||||
formatter = &logrus.TextFormatter{ForceColors: true, FullTimestamp: true}
|
||||
}
|
||||
return formatter
|
||||
}
|
||||
45
internal/utils/randomizer/rand.go
Normal file
45
internal/utils/randomizer/rand.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package randomizer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
type Random interface {
|
||||
Int() int
|
||||
}
|
||||
|
||||
func init() {}
|
||||
|
||||
type rndGenerator func(n int) int
|
||||
|
||||
type Randomizer struct {
|
||||
fn rndGenerator
|
||||
}
|
||||
|
||||
func NewRandomizer(fn rndGenerator) *Randomizer {
|
||||
return &Randomizer{fn: fn}
|
||||
}
|
||||
|
||||
func (r *Randomizer) Int(n int) int {
|
||||
return r.fn(n)
|
||||
}
|
||||
|
||||
func Rand(rand int) int {
|
||||
return randGen(rand)
|
||||
}
|
||||
func realRand(n int) int { return int(rand.Intn(n)) }
|
||||
func fakeRand(n int) func(numb int) int {
|
||||
return func(numb int) int {
|
||||
if n >= numb {
|
||||
panic(fmt.Sprintf("%d Should not be superior of %d", n, numb))
|
||||
}
|
||||
return n
|
||||
}
|
||||
}
|
||||
|
||||
var randGen = NewRandomizer(realRand).Int
|
||||
|
||||
func FakeRandomizer(n int) {
|
||||
randGen = NewRandomizer(fakeRand(n)).Int
|
||||
}
|
||||
31
internal/utils/responses.go
Executable file
31
internal/utils/responses.go
Executable file
@@ -0,0 +1,31 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"nos-comptes/internal/storage/model"
|
||||
)
|
||||
|
||||
func JSON(w http.ResponseWriter, status int, data interface{}) {
|
||||
w.Header().Set(HeaderNameContentType, HeaderValueApplicationJSONUTF8)
|
||||
w.WriteHeader(status)
|
||||
if data != nil {
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
}
|
||||
|
||||
func JSONError(w http.ResponseWriter, e model.APIError) {
|
||||
if e.Headers != nil {
|
||||
for k, headers := range e.Headers {
|
||||
for _, headerValue := range headers {
|
||||
w.Header().Add(k, headerValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
JSON(w, e.HTTPCode, e)
|
||||
}
|
||||
|
||||
func JSONErrorWithMessage(w http.ResponseWriter, e model.APIError, message string) {
|
||||
e.Description = message
|
||||
JSONError(w, e)
|
||||
}
|
||||
Reference in New Issue
Block a user