mirror of
https://github.com/kevin-DL/services.git
synced 2026-01-14 03:54:47 +00:00
Multitenant users api (#75)
This commit is contained in:
@@ -2,10 +2,12 @@ package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/micro/micro/v3/service/auth"
|
||||
"github.com/micro/micro/v3/service/errors"
|
||||
"github.com/micro/micro/v3/service/logger"
|
||||
pb "github.com/micro/services/users/proto"
|
||||
@@ -14,6 +16,11 @@ import (
|
||||
|
||||
// Create a user
|
||||
func (u *Users) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.CreateResponse) error {
|
||||
_, ok := auth.AccountFromContext(ctx)
|
||||
if !ok {
|
||||
errors.Unauthorized("UNAUTHORIZED", "Unauthorized")
|
||||
}
|
||||
|
||||
// validate the request
|
||||
if len(req.FirstName) == 0 {
|
||||
return ErrMissingFirstName
|
||||
@@ -34,11 +41,15 @@ func (u *Users) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.Creat
|
||||
// hash and salt the password using bcrypt
|
||||
phash, err := hashAndSalt(req.Password)
|
||||
if err != nil {
|
||||
logger.Errorf("Error hasing and salting password: %v", err)
|
||||
logger.Errorf("Error hashing and salting password: %v", err)
|
||||
return errors.InternalServerError("HASHING_ERROR", "Error hashing password")
|
||||
}
|
||||
|
||||
return u.DB.Transaction(func(tx *gorm.DB) error {
|
||||
db, err := u.getDBConn(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf("Error connecting to DB: %v", err)
|
||||
return errors.InternalServerError("DB_ERROR", "Error connecting to DB")
|
||||
}
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
// write the user to the database
|
||||
user := &User{
|
||||
ID: uuid.New().String(),
|
||||
@@ -47,10 +58,12 @@ func (u *Users) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.Creat
|
||||
Email: strings.ToLower(req.Email),
|
||||
Password: phash,
|
||||
}
|
||||
err = u.DB.Create(user).Error
|
||||
if err != nil && strings.Contains(err.Error(), "idx_users_email") {
|
||||
return ErrDuplicateEmail
|
||||
} else if err != nil {
|
||||
err = tx.Create(user).Error
|
||||
|
||||
if err != nil {
|
||||
if match, _ := regexp.MatchString(`idx_[\S]+_users_email`, err.Error()); match {
|
||||
return ErrDuplicateEmail
|
||||
}
|
||||
logger.Errorf("Error writing to the database: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user