github.com/qichengzx/mattermost-server@v4.5.1-0.20180604164826-2c75247c97d0+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  
    15  	"github.com/mattermost/mattermost-server/model"
    16  	"github.com/mattermost/mattermost-server/store"
    17  )
    18  
    19  type Role struct {
    20  	Id            string
    21  	Name          string
    22  	DisplayName   string
    23  	Description   string
    24  	CreateAt      int64
    25  	UpdateAt      int64
    26  	DeleteAt      int64
    27  	Permissions   string
    28  	SchemeManaged bool
    29  	BuiltIn       bool
    30  }
    31  
    32  func NewRoleFromModel(role *model.Role) *Role {
    33  	permissionsMap := make(map[string]bool)
    34  	permissions := ""
    35  
    36  	for _, permission := range role.Permissions {
    37  		if !permissionsMap[permission] {
    38  			permissions += fmt.Sprintf(" %v", permission)
    39  			permissionsMap[permission] = true
    40  		}
    41  	}
    42  
    43  	return &Role{
    44  		Id:            role.Id,
    45  		Name:          role.Name,
    46  		DisplayName:   role.DisplayName,
    47  		Description:   role.Description,
    48  		CreateAt:      role.CreateAt,
    49  		UpdateAt:      role.UpdateAt,
    50  		DeleteAt:      role.DeleteAt,
    51  		Permissions:   permissions,
    52  		SchemeManaged: role.SchemeManaged,
    53  		BuiltIn:       role.BuiltIn,
    54  	}
    55  }
    56  
    57  func (role Role) ToModel() *model.Role {
    58  	return &model.Role{
    59  		Id:            role.Id,
    60  		Name:          role.Name,
    61  		DisplayName:   role.DisplayName,
    62  		Description:   role.Description,
    63  		CreateAt:      role.CreateAt,
    64  		UpdateAt:      role.UpdateAt,
    65  		DeleteAt:      role.DeleteAt,
    66  		Permissions:   strings.Fields(role.Permissions),
    67  		SchemeManaged: role.SchemeManaged,
    68  		BuiltIn:       role.BuiltIn,
    69  	}
    70  }
    71  
    72  func initSqlSupplierRoles(sqlStore SqlStore) {
    73  	for _, db := range sqlStore.GetAllConns() {
    74  		table := db.AddTableWithName(Role{}, "Roles").SetKeys(false, "Id")
    75  		table.ColMap("Id").SetMaxSize(26)
    76  		table.ColMap("Name").SetMaxSize(64).SetUnique(true)
    77  		table.ColMap("DisplayName").SetMaxSize(128)
    78  		table.ColMap("Description").SetMaxSize(1024)
    79  		table.ColMap("Permissions").SetMaxSize(4096)
    80  	}
    81  }
    82  
    83  func (s *SqlSupplier) RoleSave(ctx context.Context, role *model.Role, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
    84  	result := store.NewSupplierResult()
    85  
    86  	// Check the role is valid before proceeding.
    87  	if !role.IsValidWithoutId() {
    88  		result.Err = model.NewAppError("SqlRoleStore.Save", "store.sql_role.save.invalid_role.app_error", nil, "", http.StatusBadRequest)
    89  		return result
    90  	}
    91  
    92  	if len(role.Id) == 0 {
    93  		if transaction, err := s.GetMaster().Begin(); err != nil {
    94  			result.Err = model.NewAppError("SqlRoleStore.RoleSave", "store.sql_role.save.open_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
    95  			return result
    96  		} else {
    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) RoleGetByName(ctx context.Context, name string, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   164  	result := store.NewSupplierResult()
   165  
   166  	var dbRole Role
   167  
   168  	if err := s.GetReplica().SelectOne(&dbRole, "SELECT * from Roles WHERE Name = :Name", map[string]interface{}{"Name": name}); err != nil {
   169  		if err == sql.ErrNoRows {
   170  			result.Err = model.NewAppError("SqlRoleStore.GetByName", "store.sql_role.get_by_name.app_error", nil, "name="+name+",err="+err.Error(), http.StatusNotFound)
   171  		} else {
   172  			result.Err = model.NewAppError("SqlRoleStore.GetByName", "store.sql_role.get_by_name.app_error", nil, "name="+name+",err="+err.Error(), http.StatusInternalServerError)
   173  		}
   174  	}
   175  
   176  	result.Data = dbRole.ToModel()
   177  
   178  	return result
   179  }
   180  
   181  func (s *SqlSupplier) RoleGetByNames(ctx context.Context, names []string, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   182  	result := store.NewSupplierResult()
   183  
   184  	var dbRoles []*Role
   185  
   186  	if len(names) == 0 {
   187  		result.Data = []*model.Role{}
   188  		return result
   189  	}
   190  
   191  	var searchPlaceholders []string
   192  	var parameters = map[string]interface{}{}
   193  	for i, value := range names {
   194  		searchPlaceholders = append(searchPlaceholders, fmt.Sprintf(":Name%d", i))
   195  		parameters[fmt.Sprintf("Name%d", i)] = value
   196  	}
   197  
   198  	searchTerm := "Name IN (" + strings.Join(searchPlaceholders, ", ") + ")"
   199  
   200  	if _, err := s.GetReplica().Select(&dbRoles, "SELECT * from Roles WHERE "+searchTerm, parameters); err != nil {
   201  		result.Err = model.NewAppError("SqlRoleStore.GetByNames", "store.sql_role.get_by_names.app_error", nil, err.Error(), http.StatusInternalServerError)
   202  	}
   203  
   204  	var roles []*model.Role
   205  	for _, dbRole := range dbRoles {
   206  		roles = append(roles, dbRole.ToModel())
   207  	}
   208  
   209  	result.Data = roles
   210  
   211  	return result
   212  }
   213  
   214  func (s *SqlSupplier) RoleDelete(ctx context.Context, roleId string, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   215  	result := store.NewSupplierResult()
   216  
   217  	// Get the role.
   218  	var role *Role
   219  	if err := s.GetReplica().SelectOne(&role, "SELECT * from Roles WHERE Id = :Id", map[string]interface{}{"Id": roleId}); err != nil {
   220  		if err == sql.ErrNoRows {
   221  			result.Err = model.NewAppError("SqlRoleStore.Delete", "store.sql_role.get.app_error", nil, "Id="+roleId+", "+err.Error(), http.StatusNotFound)
   222  		} else {
   223  			result.Err = model.NewAppError("SqlRoleStore.Delete", "store.sql_role.get.app_error", nil, err.Error(), http.StatusInternalServerError)
   224  		}
   225  
   226  		return result
   227  	}
   228  
   229  	time := model.GetMillis()
   230  	role.DeleteAt = time
   231  	role.UpdateAt = time
   232  
   233  	if rowsChanged, err := s.GetMaster().Update(role); err != nil {
   234  		result.Err = model.NewAppError("SqlRoleStore.Delete", "store.sql_role.delete.update.app_error", nil, err.Error(), http.StatusInternalServerError)
   235  	} else if rowsChanged != 1 {
   236  		result.Err = model.NewAppError("SqlRoleStore.Delete", "store.sql_role.delete.update.app_error", nil, "no record to update", http.StatusInternalServerError)
   237  	} else {
   238  		result.Data = role.ToModel()
   239  	}
   240  
   241  	return result
   242  }
   243  
   244  func (s *SqlSupplier) RolePermanentDeleteAll(ctx context.Context, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
   245  	result := store.NewSupplierResult()
   246  
   247  	if _, err := s.GetMaster().Exec("DELETE FROM Roles"); err != nil {
   248  		result.Err = model.NewAppError("SqlRoleStore.PermanentDeleteAll", "store.sql_role.permanent_delete_all.app_error", nil, err.Error(), http.StatusInternalServerError)
   249  	}
   250  
   251  	return result
   252  }