github.com/haalcala/mattermost-server-change-repo/v5@v5.33.2/store/sqlstore/oauth_store.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package sqlstore
     5  
     6  import (
     7  	"database/sql"
     8  	"fmt"
     9  
    10  	"github.com/mattermost/gorp"
    11  	"github.com/pkg/errors"
    12  
    13  	"github.com/mattermost/mattermost-server/v5/model"
    14  	"github.com/mattermost/mattermost-server/v5/store"
    15  )
    16  
    17  type SqlOAuthStore struct {
    18  	*SqlStore
    19  }
    20  
    21  func newSqlOAuthStore(sqlStore *SqlStore) store.OAuthStore {
    22  	as := &SqlOAuthStore{sqlStore}
    23  
    24  	for _, db := range sqlStore.GetAllConns() {
    25  		table := db.AddTableWithName(model.OAuthApp{}, "OAuthApps").SetKeys(false, "Id")
    26  		table.ColMap("Id").SetMaxSize(26)
    27  		table.ColMap("CreatorId").SetMaxSize(26)
    28  		table.ColMap("ClientSecret").SetMaxSize(128)
    29  		table.ColMap("Name").SetMaxSize(64)
    30  		table.ColMap("Description").SetMaxSize(512)
    31  		table.ColMap("CallbackUrls").SetMaxSize(1024)
    32  		table.ColMap("Homepage").SetMaxSize(256)
    33  		table.ColMap("IconURL").SetMaxSize(512)
    34  
    35  		tableAuth := db.AddTableWithName(model.AuthData{}, "OAuthAuthData").SetKeys(false, "Code")
    36  		tableAuth.ColMap("UserId").SetMaxSize(26)
    37  		tableAuth.ColMap("ClientId").SetMaxSize(26)
    38  		tableAuth.ColMap("Code").SetMaxSize(128)
    39  		tableAuth.ColMap("RedirectUri").SetMaxSize(256)
    40  		tableAuth.ColMap("State").SetMaxSize(1024)
    41  		tableAuth.ColMap("Scope").SetMaxSize(128)
    42  
    43  		tableAccess := db.AddTableWithName(model.AccessData{}, "OAuthAccessData").SetKeys(false, "Token")
    44  		tableAccess.ColMap("ClientId").SetMaxSize(26)
    45  		tableAccess.ColMap("UserId").SetMaxSize(26)
    46  		tableAccess.ColMap("Token").SetMaxSize(26)
    47  		tableAccess.ColMap("RefreshToken").SetMaxSize(26)
    48  		tableAccess.ColMap("RedirectUri").SetMaxSize(256)
    49  		tableAccess.ColMap("Scope").SetMaxSize(128)
    50  		tableAccess.SetUniqueTogether("ClientId", "UserId")
    51  	}
    52  
    53  	return as
    54  }
    55  
    56  func (as SqlOAuthStore) createIndexesIfNotExists() {
    57  	as.CreateIndexIfNotExists("idx_oauthapps_creator_id", "OAuthApps", "CreatorId")
    58  	as.CreateIndexIfNotExists("idx_oauthaccessdata_client_id", "OAuthAccessData", "ClientId")
    59  	as.CreateIndexIfNotExists("idx_oauthaccessdata_user_id", "OAuthAccessData", "UserId")
    60  	as.CreateIndexIfNotExists("idx_oauthaccessdata_refresh_token", "OAuthAccessData", "RefreshToken")
    61  	as.CreateIndexIfNotExists("idx_oauthauthdata_client_id", "OAuthAuthData", "Code")
    62  }
    63  
    64  func (as SqlOAuthStore) SaveApp(app *model.OAuthApp) (*model.OAuthApp, error) {
    65  	if app.Id != "" {
    66  		return nil, store.NewErrInvalidInput("OAuthApp", "Id", app.Id)
    67  	}
    68  
    69  	app.PreSave()
    70  	if err := app.IsValid(); err != nil {
    71  		return nil, err
    72  	}
    73  
    74  	if err := as.GetMaster().Insert(app); err != nil {
    75  		return nil, errors.Wrap(err, "failed to save OAuthApp")
    76  	}
    77  	return app, nil
    78  }
    79  
    80  func (as SqlOAuthStore) UpdateApp(app *model.OAuthApp) (*model.OAuthApp, error) {
    81  	app.PreUpdate()
    82  
    83  	if err := app.IsValid(); err != nil {
    84  		return nil, err
    85  	}
    86  
    87  	oldAppResult, err := as.GetMaster().Get(model.OAuthApp{}, app.Id)
    88  	if err != nil {
    89  		return nil, errors.Wrapf(err, "failed to get OAuthApp with id=%s", app.Id)
    90  	}
    91  	if oldAppResult == nil {
    92  		return nil, store.NewErrInvalidInput("OAuthApp", "Id", app.Id)
    93  	}
    94  
    95  	oldApp := oldAppResult.(*model.OAuthApp)
    96  	app.CreateAt = oldApp.CreateAt
    97  	app.CreatorId = oldApp.CreatorId
    98  
    99  	count, err := as.GetMaster().Update(app)
   100  	if err != nil {
   101  		return nil, errors.Wrapf(err, "failed to update OAuthApp with id=%s", app.Id)
   102  	}
   103  	if count > 1 {
   104  		return nil, store.NewErrInvalidInput("OAuthApp", "Id", app.Id)
   105  	}
   106  	return app, nil
   107  }
   108  
   109  func (as SqlOAuthStore) GetApp(id string) (*model.OAuthApp, error) {
   110  	obj, err := as.GetReplica().Get(model.OAuthApp{}, id)
   111  	if err != nil {
   112  		return nil, errors.Wrapf(err, "failed to get OAuthApp with id=%s", id)
   113  	}
   114  	if obj == nil {
   115  		return nil, store.NewErrNotFound("OAuthApp", id)
   116  	}
   117  	return obj.(*model.OAuthApp), nil
   118  }
   119  
   120  func (as SqlOAuthStore) GetAppByUser(userId string, offset, limit int) ([]*model.OAuthApp, error) {
   121  	var apps []*model.OAuthApp
   122  
   123  	if _, err := as.GetReplica().Select(&apps, "SELECT * FROM OAuthApps WHERE CreatorId = :UserId LIMIT :Limit OFFSET :Offset", map[string]interface{}{"UserId": userId, "Offset": offset, "Limit": limit}); err != nil {
   124  		return nil, errors.Wrapf(err, "failed to find OAuthApps with userId=%s", userId)
   125  	}
   126  
   127  	return apps, nil
   128  }
   129  
   130  func (as SqlOAuthStore) GetApps(offset, limit int) ([]*model.OAuthApp, error) {
   131  	var apps []*model.OAuthApp
   132  
   133  	if _, err := as.GetReplica().Select(&apps, "SELECT * FROM OAuthApps LIMIT :Limit OFFSET :Offset", map[string]interface{}{"Offset": offset, "Limit": limit}); err != nil {
   134  		return nil, errors.Wrap(err, "failed to find OAuthApps")
   135  	}
   136  
   137  	return apps, nil
   138  }
   139  
   140  func (as SqlOAuthStore) GetAuthorizedApps(userId string, offset, limit int) ([]*model.OAuthApp, error) {
   141  	var apps []*model.OAuthApp
   142  
   143  	if _, err := as.GetReplica().Select(&apps,
   144  		`SELECT o.* FROM OAuthApps AS o INNER JOIN
   145  			Preferences AS p ON p.Name=o.Id AND p.UserId=:UserId LIMIT :Limit OFFSET :Offset`, map[string]interface{}{"UserId": userId, "Offset": offset, "Limit": limit}); err != nil {
   146  		return nil, errors.Wrapf(err, "failed to find OAuthApps with userId=%s", userId)
   147  	}
   148  
   149  	return apps, nil
   150  }
   151  
   152  func (as SqlOAuthStore) DeleteApp(id string) error {
   153  	// wrap in a transaction so that if one fails, everything fails
   154  	transaction, err := as.GetMaster().Begin()
   155  	if err != nil {
   156  		return errors.Wrap(err, "begin_transaction")
   157  	}
   158  	defer finalizeTransaction(transaction)
   159  
   160  	if err := as.deleteApp(transaction, id); err != nil {
   161  		return err
   162  	}
   163  
   164  	if err := transaction.Commit(); err != nil {
   165  		// don't need to rollback here since the transaction is already closed
   166  		return errors.Wrap(err, "commit_transaction")
   167  	}
   168  	return nil
   169  }
   170  
   171  func (as SqlOAuthStore) SaveAccessData(accessData *model.AccessData) (*model.AccessData, error) {
   172  	if err := accessData.IsValid(); err != nil {
   173  		return nil, err
   174  	}
   175  
   176  	if err := as.GetMaster().Insert(accessData); err != nil {
   177  		return nil, errors.Wrap(err, "failed to save AccessData")
   178  	}
   179  	return accessData, nil
   180  }
   181  
   182  func (as SqlOAuthStore) GetAccessData(token string) (*model.AccessData, error) {
   183  	accessData := model.AccessData{}
   184  
   185  	if err := as.GetReplica().SelectOne(&accessData, "SELECT * FROM OAuthAccessData WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil {
   186  		return nil, errors.Wrapf(err, "failed to get OAuthAccessData with token=%s", token)
   187  	}
   188  	return &accessData, nil
   189  }
   190  
   191  func (as SqlOAuthStore) GetAccessDataByUserForApp(userId, clientId string) ([]*model.AccessData, error) {
   192  	var accessData []*model.AccessData
   193  
   194  	if _, err := as.GetReplica().Select(&accessData,
   195  		"SELECT * FROM OAuthAccessData WHERE UserId = :UserId AND ClientId = :ClientId",
   196  		map[string]interface{}{"UserId": userId, "ClientId": clientId}); err != nil {
   197  		return nil, errors.Wrapf(err, "failed to delete OAuthAccessData with userId=%s and clientId=%s", userId, clientId)
   198  	}
   199  	return accessData, nil
   200  }
   201  
   202  func (as SqlOAuthStore) GetAccessDataByRefreshToken(token string) (*model.AccessData, error) {
   203  	accessData := model.AccessData{}
   204  
   205  	if err := as.GetReplica().SelectOne(&accessData, "SELECT * FROM OAuthAccessData WHERE RefreshToken = :Token", map[string]interface{}{"Token": token}); err != nil {
   206  		return nil, errors.Wrapf(err, "failed to find OAuthAccessData with refreshToken=%s", token)
   207  	}
   208  	return &accessData, nil
   209  }
   210  
   211  func (as SqlOAuthStore) GetPreviousAccessData(userId, clientId string) (*model.AccessData, error) {
   212  	accessData := model.AccessData{}
   213  
   214  	if err := as.GetReplica().SelectOne(&accessData, "SELECT * FROM OAuthAccessData WHERE ClientId = :ClientId AND UserId = :UserId",
   215  		map[string]interface{}{"ClientId": clientId, "UserId": userId}); err != nil {
   216  		if err == sql.ErrNoRows {
   217  			return nil, nil
   218  		}
   219  
   220  		return nil, errors.Wrapf(err, "failed to get AccessData with clientId=%s and userId=%s", clientId, userId)
   221  	}
   222  	return &accessData, nil
   223  }
   224  
   225  func (as SqlOAuthStore) UpdateAccessData(accessData *model.AccessData) (*model.AccessData, error) {
   226  	if err := accessData.IsValid(); err != nil {
   227  		return nil, err
   228  	}
   229  
   230  	if _, err := as.GetMaster().Exec("UPDATE OAuthAccessData SET Token = :Token, ExpiresAt = :ExpiresAt, RefreshToken = :RefreshToken WHERE ClientId = :ClientId AND UserID = :UserId",
   231  		map[string]interface{}{"Token": accessData.Token, "ExpiresAt": accessData.ExpiresAt, "RefreshToken": accessData.RefreshToken, "ClientId": accessData.ClientId, "UserId": accessData.UserId}); err != nil {
   232  		return nil, errors.Wrapf(err, "failed to update OAuthAccessData with userId=%s and clientId=%s", accessData.UserId, accessData.ClientId)
   233  	}
   234  	return accessData, nil
   235  }
   236  
   237  func (as SqlOAuthStore) RemoveAccessData(token string) error {
   238  	if _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil {
   239  		return errors.Wrapf(err, "failed to delete OAuthAccessData with token=%s", token)
   240  	}
   241  	return nil
   242  }
   243  
   244  func (as SqlOAuthStore) RemoveAllAccessData() error {
   245  	if _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData", map[string]interface{}{}); err != nil {
   246  		return errors.Wrap(err, "failed to delete OAuthAccessData")
   247  	}
   248  	return nil
   249  }
   250  
   251  func (as SqlOAuthStore) SaveAuthData(authData *model.AuthData) (*model.AuthData, error) {
   252  	authData.PreSave()
   253  	if err := authData.IsValid(); err != nil {
   254  		return nil, err
   255  	}
   256  
   257  	if err := as.GetMaster().Insert(authData); err != nil {
   258  		return nil, errors.Wrap(err, "failed to save AuthData")
   259  	}
   260  	return authData, nil
   261  }
   262  
   263  func (as SqlOAuthStore) GetAuthData(code string) (*model.AuthData, error) {
   264  	obj, err := as.GetReplica().Get(model.AuthData{}, code)
   265  	if err != nil {
   266  		return nil, errors.Wrapf(err, "failed to get AuthData with code=%s", code)
   267  	}
   268  	if obj == nil {
   269  		return nil, store.NewErrNotFound("AuthData", fmt.Sprintf("code=%s", code))
   270  	}
   271  	return obj.(*model.AuthData), nil
   272  }
   273  
   274  func (as SqlOAuthStore) RemoveAuthData(code string) error {
   275  	_, err := as.GetMaster().Exec("DELETE FROM OAuthAuthData WHERE Code = :Code", map[string]interface{}{"Code": code})
   276  	if err != nil {
   277  		return errors.Wrapf(err, "failed to delete AuthData with code=%s", code)
   278  	}
   279  	return nil
   280  }
   281  
   282  func (as SqlOAuthStore) PermanentDeleteAuthDataByUser(userId string) error {
   283  	_, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
   284  	if err != nil {
   285  		return errors.Wrapf(err, "failed to delete OAuthAccessData with userId=%s", userId)
   286  	}
   287  	return nil
   288  }
   289  
   290  func (as SqlOAuthStore) deleteApp(transaction *gorp.Transaction, clientId string) error {
   291  	if _, err := transaction.Exec("DELETE FROM OAuthApps WHERE Id = :Id", map[string]interface{}{"Id": clientId}); err != nil {
   292  		return errors.Wrapf(err, "failed to delete OAuthApp with id=%s", clientId)
   293  	}
   294  
   295  	return as.deleteOAuthAppSessions(transaction, clientId)
   296  }
   297  
   298  func (as SqlOAuthStore) deleteOAuthAppSessions(transaction *gorp.Transaction, clientId string) error {
   299  
   300  	query := ""
   301  	if as.DriverName() == model.DATABASE_DRIVER_POSTGRES {
   302  		query = "DELETE FROM Sessions s USING OAuthAccessData o WHERE o.Token = s.Token AND o.ClientId = :Id"
   303  	} else if as.DriverName() == model.DATABASE_DRIVER_MYSQL {
   304  		query = "DELETE s.* FROM Sessions s INNER JOIN OAuthAccessData o ON o.Token = s.Token WHERE o.ClientId = :Id"
   305  	}
   306  
   307  	if _, err := transaction.Exec(query, map[string]interface{}{"Id": clientId}); err != nil {
   308  		return errors.Wrapf(err, "failed to delete Session with OAuthAccessData.Id=%s", clientId)
   309  	}
   310  
   311  	return as.deleteOAuthTokens(transaction, clientId)
   312  }
   313  
   314  func (as SqlOAuthStore) deleteOAuthTokens(transaction *gorp.Transaction, clientId string) error {
   315  	if _, err := transaction.Exec("DELETE FROM OAuthAccessData WHERE ClientId = :Id", map[string]interface{}{"Id": clientId}); err != nil {
   316  		return errors.Wrapf(err, "failed to delete OAuthAccessData with id=%s", clientId)
   317  	}
   318  
   319  	return as.deleteAppExtras(transaction, clientId)
   320  }
   321  
   322  func (as SqlOAuthStore) deleteAppExtras(transaction *gorp.Transaction, clientId string) error {
   323  	if _, err := transaction.Exec(
   324  		`DELETE FROM
   325  			Preferences
   326  		WHERE
   327  			Category = :Category
   328  			AND Name = :Name`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, "Name": clientId}); err != nil {
   329  		return errors.Wrapf(err, "failed to delete Preferences with name=%s", clientId)
   330  	}
   331  
   332  	return nil
   333  }