Skip to content

Commit

Permalink
One org + email auto confirmation
Browse files Browse the repository at this point in the history
  • Loading branch information
Ardem committed Oct 17, 2024
1 parent a2404e6 commit 09ad9c5
Show file tree
Hide file tree
Showing 8 changed files with 191 additions and 151 deletions.
1 change: 1 addition & 0 deletions backend/integrations/api/CreateEmailIntegration.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ func CreateEmailIntegration(w http.ResponseWriter, r *http.Request) {
UserUpdatedAt: time.Now().Format(helpers.DB_TIME_TIMESTAMP),
},
Code: helpers.CreateRandomNumericString(6),
IsConfirmed: true,
RequestedAt: time.Now(),
}

Expand Down
2 changes: 1 addition & 1 deletion backend/integrations/repositories/EmailRepository.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func CreateEmailIntegration(db *sql.DB, EmailIntegration *entities.Email) error
EmailIntegration.Integration.Status = entities.IntegrationStatusNew
EmailIntegration.Integration.Type = entities.IntegrationTypeEmail
EmailIntegration.Integration.IoType = entities.IntegrationIoTypeWrite
EmailIntegration.IsConfirmed = false
EmailIntegration.IsConfirmed = true

{
Query := `INSERT INTO integrations
Expand Down
88 changes: 51 additions & 37 deletions backend/users/api/ExternalAuthCallback.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,57 +60,71 @@ func (auth *AuthMiddleware) ExternalAuthCallback(w http.ResponseWriter, r *http
return
}

organizationName := strings.Join(strings.Split(externalUser.Email, "@")[1:], "")
orgExists := repositories.DoesOrganizationExist(db, organizationName, "")
org, orgEx := repositories.GetOrganization(db)

srv := services.CreateSignUpSrv(db, r.Context())
if !orgEx {
organizationName := strings.Join(strings.Split(externalUser.Email, "@")[1:], "")
orgExists := repositories.DoesOrganizationExist(db, organizationName, "")

if orgExists {
isGenericEmailProvider := services.IsGenericEmailProvider(organizationName)
if isGenericEmailProvider {
organizationName = fmt.Sprintf("%s-%s", organizationName, helpers.CreateRandomNumericString(10))
}

if orgExists {
isGenericEmailProvider := services.IsGenericEmailProvider(organizationName)
if isGenericEmailProvider {
organizationName = fmt.Sprintf("%s-%s", organizationName, helpers.CreateRandomNumericString(10))
orgExists = repositories.DoesOrganizationExist(db, organizationName, "")
}

orgExists = repositories.DoesOrganizationExist(db, organizationName, "")
}
if orgExists {
rp, _ := json.Marshal(map[string]string{"error": "Organization " + organizationName + " already exist. Please contact your organization admin."})
w.WriteHeader(http.StatusBadRequest)
_, err = w.Write(rp)
if err != nil {
log.Error(err)
}

if orgExists {
rp, _ := json.Marshal(map[string]string{"error": "Organization " + organizationName + " already exist. Please contact your organization admin."})
w.WriteHeader(http.StatusBadRequest)
_, err = w.Write(rp)
if err != nil {
log.Error(err)
return
}

return
}

localExternalUser, err = srv.SignUpExternalUser(externalUser, organizationName, entities.SourceGoogle, id)
if err != nil {
log.Error(err)
localExternalUser, err = srv.SignUpExternalUser(externalUser, organizationName, entities.SourceGoogle, id, 0)
if err != nil {
log.Error(err)

helpers.HttpReturnErrorInternal(w)
return
}
helpers.HttpReturnErrorInternal(w)
return
}

organization, ok := repositories.GetOrganizationByUserUuid(db, localExternalUser.Uuid)
if !ok {
helpers.HttpReturnErrorForbidden(w)
return
}
organization, ok := repositories.GetOrganizationByUserUuid(db, localExternalUser.Uuid)
if !ok {
helpers.HttpReturnErrorForbidden(w)
return
}

tokenString := externalAuthCreateJWT(w, *localExternalUser, auth)
tokenString := externalAuthCreateJWT(w, *localExternalUser, auth)

log.Tracef("create default email destination")
dUuid, ok := services.CreateDefaultEmailDestination(organization.Uuid, localExternalUser.Email, localExternalUser.FirstName, tokenString)
log.Tracef("create default email destination")
dUuid, ok := services.CreateDefaultEmailDestination(organization.Uuid, localExternalUser.Email, localExternalUser.FirstName, tokenString)

if ok {
log.Tracef("create trial db data source")
sUuid, ok := services.CreateTrialDBDataSource(organization.Uuid, tokenString)
if ok {
log.Tracef("create trial pipelines")
services.TestTrialDBDataSource(sUuid, tokenString)
_ = services.CreateTrialPipelines(organization.Uuid, dUuid, sUuid, tokenString)
log.Tracef("create trial db data source")
sUuid, ok := services.CreateTrialDBDataSource(organization.Uuid, tokenString)
if ok {
log.Tracef("create trial pipelines")
services.TestTrialDBDataSource(sUuid, tokenString)
_ = services.CreateTrialPipelines(organization.Uuid, dUuid, sUuid, tokenString)
}
}
} else {
localExternalUser, err = srv.SignUpExternalUser(externalUser, "", entities.SourceGoogle, id, int64(org.Id))
if err != nil {
log.Error(err)

helpers.HttpReturnErrorInternal(w)
return
}

externalAuthCreateJWT(w, *localExternalUser, auth)
}
}

Expand Down
169 changes: 91 additions & 78 deletions backend/users/api/PostUser.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (auth *AuthMiddleware) PostUser(w http.ResponseWriter, r *http.Request) {
db := helpers.DbConn()
defer db.Close()

if repositories.DoesOrganizationExist(db, user.OrganizationName, "") {
/*if repositories.DoesOrganizationExist(db, user.OrganizationName, "") {
rp, _ := json.Marshal(map[string]string{"error": "Organization already exist", "fields": "organization_exists"})
w.WriteHeader(http.StatusBadRequest)
Expand All @@ -63,7 +63,7 @@ func (auth *AuthMiddleware) PostUser(w http.ResponseWriter, r *http.Request) {
}
return
}
}*/

if repositories.DoesUserExist(db, user.Email, "") {
rp, _ := json.Marshal(map[string]string{"error": "Invalid Email", "fields": "email"})
Expand Down Expand Up @@ -212,45 +212,52 @@ func SaveOrganizationAndUserWithContext(ctx context.Context, db *sql.DB, user se

defer tx.Rollback() //nolint:all

/* Creating organization */
org, orgEx := repositories.GetOrganization(db)
roles, _ := json.Marshal([]string{entities.ROLE_ORGANIZATION_ADMIN})
orgUuid := uuid.NewString()
if !orgEx {

insertOrgQuery := `INSERT INTO organizations
(name, data_key, uuid)
VALUES (?, ?, ?)
`
/* Creating organization */
insertOrgQuery := `INSERT INTO organizations
(name, data_key, uuid)
VALUES (?, ?, ?)
`

dataKey, err := kms.IssueDataKeyWithContext(ctx)
dataKey, err := kms.IssueDataKeyWithContext(ctx)

if err != nil {
_ = tx.Rollback()
log.Error(err.Error())
return false, nil
}
if err != nil {
_ = tx.Rollback()
log.Error(err.Error())
return false, nil
}

insertStatement, err := tx.Prepare(insertOrgQuery)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, nil
}
defer insertStatement.Close()
insertStatement, err := tx.Prepare(insertOrgQuery)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, nil
}
defer insertStatement.Close()

orgUuid := uuid.NewString()
_, err = insertStatement.Exec(user.OrganizationName, dataKey, orgUuid)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, nil
_, err = insertStatement.Exec("My organization", dataKey, orgUuid)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, nil
}
} else {
roles, _ = json.Marshal([]string{entities.ROLE_TEAM_MEMBER})
orgUuid = org.Uuid
}

/* Creating user */

insertUserQuery := `INSERT INTO users
(first_name, last_name, email, phone, uuid, password, roles, email_confirmation_token)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
(first_name, last_name, email, phone, uuid, password, roles, email_confirmation_token, is_email_confirmed)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`

insertStatement, err = tx.Prepare(insertUserQuery)
insertStatement, err := tx.Prepare(insertUserQuery)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
Expand All @@ -259,23 +266,21 @@ func SaveOrganizationAndUserWithContext(ctx context.Context, db *sql.DB, user se
defer insertStatement.Close()

hash, _ := HashPassword(user.Password)
roles, _ := json.Marshal([]string{entities.ROLE_ORGANIZATION_ADMIN})
userUuid := uuid.NewString()
emailConfirmationToken := helpers.CreateRandomNumericString(emailConfirmationTokenLength)
_, err = insertStatement.Exec(user.FirstName, user.LastName, user.Email, user.Phone, userUuid, hash, roles, emailConfirmationToken)
_, err = insertStatement.Exec(user.FirstName, user.LastName, user.Email, user.Phone, userUuid, hash, roles, emailConfirmationToken, 1)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, nil
}

/* Getting organization and user IDs */

var orgId int
var usr entities.User
UserQuery := `SELECT id, first_name, last_name, email, phone, uuid, roles
FROM users
WHERE uuid = ?
`
FROM users
WHERE uuid = ?
`
stmt, _ := tx.Prepare(UserQuery)
err = stmt.QueryRow(userUuid).Scan(&usr.Id, &usr.FirstName, &usr.LastName, &usr.Email, &usr.Phone, &usr.Uuid, &usr.Roles)

Expand All @@ -285,40 +290,46 @@ func SaveOrganizationAndUserWithContext(ctx context.Context, db *sql.DB, user se
return false, nil
}

var organization entities.Organization
OrganizationQuery := `SELECT id, name
FROM organizations
WHERE uuid = ?
`
stmt, _ = tx.Prepare(OrganizationQuery)
err = stmt.QueryRow(orgUuid).Scan(&organization.Id, &organization.Name)
if !orgEx {
var organization entities.Organization
OrganizationQuery := `SELECT id, name
FROM organizations
WHERE uuid = ?
`
stmt, _ = tx.Prepare(OrganizationQuery)
err = stmt.QueryRow(orgUuid).Scan(&organization.Id, &organization.Name)

if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, nil
}
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, nil
}

/* Updating organization */
/* Updating organization */

updateOrgQuery := `UPDATE organizations
SET creator_id = ?
WHERE uuid = ?
`
updateOrgQuery := `UPDATE organizations
SET creator_id = ?
WHERE uuid = ?
`

updateStatement, err := tx.Prepare(updateOrgQuery)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, &usr
}
defer updateStatement.Close()
updateStatement, err := tx.Prepare(updateOrgQuery)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, &usr
}
defer updateStatement.Close()

_, err = updateStatement.Exec(usr.Id, orgUuid)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, &usr
_, err = updateStatement.Exec(usr.Id, orgUuid)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, &usr
}

orgId = organization.Id
} else {
orgId = org.Id
}

/* Updating user */
Expand All @@ -328,15 +339,15 @@ func SaveOrganizationAndUserWithContext(ctx context.Context, db *sql.DB, user se
WHERE uuid = ?
`

updateStatement, err = tx.Prepare(updateUserQuery)
updateStatement, err := tx.Prepare(updateUserQuery)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
return false, &usr
}
defer updateStatement.Close()

_, err = updateStatement.Exec(organization.Id, userUuid)
_, err = updateStatement.Exec(orgId, userUuid)
if err != nil {
_ = tx.Rollback()
log.Println(err.Error())
Expand All @@ -357,17 +368,19 @@ func SaveOrganizationAndUserWithContext(ctx context.Context, db *sql.DB, user se
return false, &usr
}

log.Tracef("create default email destination")
dUuid, ok := services.CreateDefaultEmailDestination(orgUuid, user.Email, user.FirstName, tokenString)
if !orgEx {
log.Tracef("create default email destination")
dUuid, ok := services.CreateDefaultEmailDestination(orgUuid, user.Email, user.FirstName, tokenString)

if ok {
log.Tracef("create trial db data source")
sUuid, ok := services.CreateTrialDBDataSource(orgUuid, tokenString)
if ok {
log.Tracef("test trial database connection")
services.TestTrialDBDataSource(sUuid, tokenString)
log.Tracef("create trial pipelines")
_ = services.CreateTrialPipelines(orgUuid, dUuid, sUuid, tokenString)
log.Tracef("create trial db data source")
sUuid, ok := services.CreateTrialDBDataSource(orgUuid, tokenString)
if ok {
log.Tracef("test trial database connection")
services.TestTrialDBDataSource(sUuid, tokenString)
log.Tracef("create trial pipelines")
_ = services.CreateTrialPipelines(orgUuid, dUuid, sUuid, tokenString)
}
}
}

Expand All @@ -385,10 +398,10 @@ func ValidateHttpUser(user services.HttpUser, w http.ResponseWriter) []string {
errorFields = append(errorFields, "last_name")
}

if user.OrganizationName == "" && user.InvitationKey == "" {
/*if user.OrganizationName == "" && user.InvitationKey == "" {
errorFields = append(errorFields, "organization_name")
errorFields = append(errorFields, "invitation_key")
}
}*/

if user.Email == "" || !govalidator.IsEmail(user.Email) {
errorFields = append(errorFields, "email")
Expand Down
Loading

0 comments on commit 09ad9c5

Please sign in to comment.