github.com/mad-app/mattermost-server@v5.11.1+incompatible/store/sqlstore/role_supplier.go (about)

     1  // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package sqlstore
     5  
     6  import (
     7  	"context"
     8  	"database/sql"
     9  	"fmt"
    10  	"net/http"
    11  	"strings"
    12  
    13  	"github.com/mattermost/gorp"
    14  	"github.com/mattermost/mattermost-server/model"
    15  	"github.com/mattermost/mattermost-server/store"
    16  )
    17  
    18  type Role struct {
    19  	Id            string
    20  	Name          string
    21  	DisplayName   string
    22  	Description   string
    23  	CreateAt      int64
    24  	UpdateAt      int64
    25  	DeleteAt      int64
    26  	Permissions   string
    27  	SchemeManaged bool
    28  	BuiltIn       bool
    29  }
    30  
    31  func NewRoleFromModel(role *model.Role) *Role {
    32  	permissionsMap := make(map[string]bool)
    33  	permissions := ""
    34  
    35  	for _, permission := range role.Permissions {
    36  		if !permissionsMap[permission] {
    37  			permissions += fmt.Sprintf(" %v", permission)
    38  			permissionsMap[permission] = true
    39  		}
    40  	}
    41  
    42  	return &Role{
    43  		Id:            role.Id,
    44  		Name:          role.Name,
    45  		DisplayName:   role.DisplayName,
    46  		Description:   role.Description,
    47  		CreateAt:      role.CreateAt,
    48  		UpdateAt:      role.UpdateAt,
    49  		DeleteAt:      role.DeleteAt,
    50  		Permissions:   permissions,
    51  		SchemeManaged: role.SchemeManaged,
    52  		BuiltIn:       role.BuiltIn,
    53  	}
    54  }
    55  
    56  func (role Role) ToModel() *model.Role {
    57  	return &model.Role{
    58  		Id:            role.Id,
    59  		Name:          role.Name,
    60  		DisplayName:   role.DisplayName,
    61  		Description:   role.Description,
    62  		CreateAt:      role.CreateAt,
    63  		UpdateAt:      role.UpdateAt,
    64  		DeleteAt:      role.DeleteAt,
    65  		Permissions:   strings.Fields(role.Permissions),
    66  		SchemeManaged: role.SchemeManaged,
    67  		BuiltIn:       role.BuiltIn,
    68  	}
    69  }
    70  
    71  func initSqlSupplierRoles(sqlStore SqlStore) {
    72  	for _, db := range sqlStore.GetAllConns() {
    73  		table := db.AddTableWithName(Role{}, "Roles").SetKeys(false, "Id")
    74  		table.ColMap("Id").SetMaxSize(26)
    75  		table.ColMap("Name").SetMaxSize(64).SetUnique(true)
    76  		table.ColMap("DisplayName").SetMaxSize(128)
    77  		table.ColMap("Description").SetMaxSize(1024)
    78  		table.ColMap("Permissions").SetMaxSize(4096)
    79  	}
    80  }
    81  
    82  func (s *SqlSupplier) RoleSave(ctx context.Context, role *model.Role, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
    83  	result := store.NewSupplierResult()
    84  
    85  	// Check the role is valid before proceeding.
    86  	if !role.IsValidWithoutId() {
    87  		result.Err = model.NewAppError("SqlRoleStore.Save", "store.sql_role.save.invalid_role.app_error", nil, "", http.StatusBadRequest)
    88  		return result
    89  	}
    90  
    91  	if len(role.Id) == 0 {
    92  		if transaction, err := s.GetMaster().Begin(); err != nil {
    93  			result.Err = model.NewAppError("SqlRoleStore.RoleSave", "store.sql_role.save.open_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
    94  			return result
    95  		} else {
    96  			defer finalizeTransaction(transaction)
    97  			result = s.createRole(ctx, role, transaction, hints...)
    98  
    99  			if result.Err != nil {
   100  				transaction.Rollback()
   101  			} else if err := transaction.Commit(); err != nil {
   102  				result.Err = model.NewAppError("SqlRoleStore.RoleSave", "store.sql_role.save_role.commit_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
   103  			}
   104  		}
   105  	} else {
   106  		dbRole := NewRoleFromModel(role)
   107  
   108  		dbRole.UpdateAt = model.GetMillis()
   109  		if rowsChanged, err := s.GetMaster().Update(dbRole); err != nil {
   110  			result.Err = model.NewAppError("SqlRoleStore.Save", "store.sql_role.save.update.app_error", nil, err.Error(), http.StatusInternalServerError)
   111  		} else if rowsChanged != 1 {
   112  			result.Err = model.NewAppError("SqlRoleStore.Save", "store.sql_role.save.update.app_error", nil, "no record to update", http.StatusInternalServerError)
   113  		}
   114  
   115  		result.Data = dbRole.ToModel()
   116  	}
   117  
   118  	return result
   119  }
   120  
   121  func (s *SqlSupplier) createRole(ctx context.Context, role *model.Role, transaction *gorp.Transaction, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   122  	result := store.NewSupplierResult()
   123  
   124  	// Check the role is valid before proceeding.
   125  	if !role.IsValidWithoutId() {
   126  		result.Err = model.NewAppError("SqlRoleStore.Save", "store.sql_role.save.invalid_role.app_error", nil, "", http.StatusBadRequest)
   127  		return result
   128  	}
   129  
   130  	dbRole := NewRoleFromModel(role)
   131  
   132  	dbRole.Id = model.NewId()
   133  	dbRole.CreateAt = model.GetMillis()
   134  	dbRole.UpdateAt = dbRole.CreateAt
   135  
   136  	if err := transaction.Insert(dbRole); err != nil {
   137  		result.Err = model.NewAppError("SqlRoleStore.Save", "store.sql_role.save.insert.app_error", nil, err.Error(), http.StatusInternalServerError)
   138  	}
   139  
   140  	result.Data = dbRole.ToModel()
   141  
   142  	return result
   143  }
   144  
   145  func (s *SqlSupplier) RoleGet(ctx context.Context, roleId string, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   146  	result := store.NewSupplierResult()
   147  
   148  	var dbRole Role
   149  
   150  	if err := s.GetReplica().SelectOne(&dbRole, "SELECT * from Roles WHERE Id = :Id", map[string]interface{}{"Id": roleId}); err != nil {
   151  		if err == sql.ErrNoRows {
   152  			result.Err = model.NewAppError("SqlRoleStore.Get", "store.sql_role.get.app_error", nil, "Id="+roleId+", "+err.Error(), http.StatusNotFound)
   153  		} else {
   154  			result.Err = model.NewAppError("SqlRoleStore.Get", "store.sql_role.get.app_error", nil, err.Error(), http.StatusInternalServerError)
   155  		}
   156  	}
   157  
   158  	result.Data = dbRole.ToModel()
   159  
   160  	return result
   161  }
   162  
   163  func (s *SqlSupplier) RoleGetAll(ctx context.Context, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   164  	result := store.NewSupplierResult()
   165  
   166  	var dbRoles []Role
   167  
   168  	if _, err := s.GetReplica().Select(&dbRoles, "SELECT * from Roles", map[string]interface{}{}); err != nil {
   169  		if err == sql.ErrNoRows {
   170  			result.Err = model.NewAppError("SqlRoleStore.GetAll", "store.sql_role.get_all.app_error", nil, err.Error(), http.StatusNotFound)
   171  		} else {
   172  			result.Err = model.NewAppError("SqlRoleStore.GetAll", "store.sql_role.get_all.app_error", nil, err.Error(), http.StatusInternalServerError)
   173  		}
   174  	}
   175  
   176  	var roles []*model.Role
   177  	for _, dbRole := range dbRoles {
   178  		roles = append(roles, dbRole.ToModel())
   179  	}
   180  	result.Data = roles
   181  
   182  	return result
   183  }
   184  
   185  func (s *SqlSupplier) RoleGetByName(ctx context.Context, name string, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   186  	result := store.NewSupplierResult()
   187  
   188  	var dbRole Role
   189  
   190  	if err := s.GetReplica().SelectOne(&dbRole, "SELECT * from Roles WHERE Name = :Name", map[string]interface{}{"Name": name}); err != nil {
   191  		if err == sql.ErrNoRows {
   192  			result.Err = model.NewAppError("SqlRoleStore.GetByName", "store.sql_role.get_by_name.app_error", nil, "name="+name+",err="+err.Error(), http.StatusNotFound)
   193  		} else {
   194  			result.Err = model.NewAppError("SqlRoleStore.GetByName", "store.sql_role.get_by_name.app_error", nil, "name="+name+",err="+err.Error(), http.StatusInternalServerError)
   195  		}
   196  	}
   197  
   198  	result.Data = dbRole.ToModel()
   199  
   200  	return result
   201  }
   202  
   203  func (s *SqlSupplier) RoleGetByNames(ctx context.Context, names []string, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   204  	result := store.NewSupplierResult()
   205  
   206  	var dbRoles []*Role
   207  
   208  	if len(names) == 0 {
   209  		result.Data = []*model.Role{}
   210  		return result
   211  	}
   212  
   213  	var searchPlaceholders []string
   214  	var parameters = map[string]interface{}{}
   215  	for i, value := range names {
   216  		searchPlaceholders = append(searchPlaceholders, fmt.Sprintf(":Name%d", i))
   217  		parameters[fmt.Sprintf("Name%d", i)] = value
   218  	}
   219  
   220  	searchTerm := "Name IN (" + strings.Join(searchPlaceholders, ", ") + ")"
   221  
   222  	if _, err := s.GetReplica().Select(&dbRoles, "SELECT * from Roles WHERE "+searchTerm, parameters); err != nil {
   223  		result.Err = model.NewAppError("SqlRoleStore.GetByNames", "store.sql_role.get_by_names.app_error", nil, err.Error(), http.StatusInternalServerError)
   224  	}
   225  
   226  	var roles []*model.Role
   227  	for _, dbRole := range dbRoles {
   228  		roles = append(roles, dbRole.ToModel())
   229  	}
   230  
   231  	result.Data = roles
   232  
   233  	return result
   234  }
   235  
   236  func (s *SqlSupplier) RoleDelete(ctx context.Context, roleId string, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   237  	result := store.NewSupplierResult()
   238  
   239  	// Get the role.
   240  	var role *Role
   241  	if err := s.GetReplica().SelectOne(&role, "SELECT * from Roles WHERE Id = :Id", map[string]interface{}{"Id": roleId}); err != nil {
   242  		if err == sql.ErrNoRows {
   243  			result.Err = model.NewAppError("SqlRoleStore.Delete", "store.sql_role.get.app_error", nil, "Id="+roleId+", "+err.Error(), http.StatusNotFound)
   244  		} else {
   245  			result.Err = model.NewAppError("SqlRoleStore.Delete", "store.sql_role.get.app_error", nil, err.Error(), http.StatusInternalServerError)
   246  		}
   247  
   248  		return result
   249  	}
   250  
   251  	time := model.GetMillis()
   252  	role.DeleteAt = time
   253  	role.UpdateAt = time
   254  
   255  	if rowsChanged, err := s.GetMaster().Update(role); err != nil {
   256  		result.Err = model.NewAppError("SqlRoleStore.Delete", "store.sql_role.delete.update.app_error", nil, err.Error(), http.StatusInternalServerError)
   257  	} else if rowsChanged != 1 {
   258  		result.Err = model.NewAppError("SqlRoleStore.Delete", "store.sql_role.delete.update.app_error", nil, "no record to update", http.StatusInternalServerError)
   259  	} else {
   260  		result.Data = role.ToModel()
   261  	}
   262  
   263  	return result
   264  }
   265  
   266  func (s *SqlSupplier) RolePermanentDeleteAll(ctx context.Context, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   267  	result := store.NewSupplierResult()
   268  
   269  	if _, err := s.GetMaster().Exec("DELETE FROM Roles"); err != nil {
   270  		result.Err = model.NewAppError("SqlRoleStore.PermanentDeleteAll", "store.sql_role.permanent_delete_all.app_error", nil, err.Error(), http.StatusInternalServerError)
   271  	}
   272  
   273  	return result
   274  }