github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/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/masterhung0112/hk_server/v5/model"
    14  	"github.com/masterhung0112/hk_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_user_id", "OAuthAccessData", "UserId")
    59  	as.CreateIndexIfNotExists("idx_oauthaccessdata_refresh_token", "OAuthAccessData", "RefreshToken")
    60  }
    61  
    62  func (as SqlOAuthStore) SaveApp(app *model.OAuthApp) (*model.OAuthApp, error) {
    63  	if app.Id != "" {
    64  		return nil, store.NewErrInvalidInput("OAuthApp", "Id", app.Id)
    65  	}
    66  
    67  	app.PreSave()
    68  	if err := app.IsValid(); err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	if err := as.GetMaster().Insert(app); err != nil {
    73  		return nil, errors.Wrap(err, "failed to save OAuthApp")
    74  	}
    75  	return app, nil
    76  }
    77  
    78  func (as SqlOAuthStore) UpdateApp(app *model.OAuthApp) (*model.OAuthApp, error) {
    79  	app.PreUpdate()
    80  
    81  	if err := app.IsValid(); err != nil {
    82  		return nil, err
    83  	}
    84  
    85  	oldAppResult, err := as.GetMaster().Get(model.OAuthApp{}, app.Id)
    86  	if err != nil {
    87  		return nil, errors.Wrapf(err, "failed to get OAuthApp with id=%s", app.Id)
    88  	}
    89  	if oldAppResult == nil {
    90  		return nil, store.NewErrInvalidInput("OAuthApp", "Id", app.Id)
    91  	}
    92  
    93  	oldApp := oldAppResult.(*model.OAuthApp)
    94  	app.CreateAt = oldApp.CreateAt
    95  	app.CreatorId = oldApp.CreatorId
    96  
    97  	count, err := as.GetMaster().Update(app)
    98  	if err != nil {
    99  		return nil, errors.Wrapf(err, "failed to update OAuthApp with id=%s", app.Id)
   100  	}
   101  	if count > 1 {
   102  		return nil, store.NewErrInvalidInput("OAuthApp", "Id", app.Id)
   103  	}
   104  	return app, nil
   105  }
   106  
   107  func (as SqlOAuthStore) GetApp(id string) (*model.OAuthApp, error) {
   108  	obj, err := as.GetReplica().Get(model.OAuthApp{}, id)
   109  	if err != nil {
   110  		return nil, errors.Wrapf(err, "failed to get OAuthApp with id=%s", id)
   111  	}
   112  	if obj == nil {
   113  		return nil, store.NewErrNotFound("OAuthApp", id)
   114  	}
   115  	return obj.(*model.OAuthApp), nil
   116  }
   117  
   118  func (as SqlOAuthStore) GetAppByUser(userId string, offset, limit int) ([]*model.OAuthApp, error) {
   119  	var apps []*model.OAuthApp
   120  
   121  	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 {
   122  		return nil, errors.Wrapf(err, "failed to find OAuthApps with userId=%s", userId)
   123  	}
   124  
   125  	return apps, nil
   126  }
   127  
   128  func (as SqlOAuthStore) GetApps(offset, limit int) ([]*model.OAuthApp, error) {
   129  	var apps []*model.OAuthApp
   130  
   131  	if _, err := as.GetReplica().Select(&apps, "SELECT * FROM OAuthApps LIMIT :Limit OFFSET :Offset", map[string]interface{}{"Offset": offset, "Limit": limit}); err != nil {
   132  		return nil, errors.Wrap(err, "failed to find OAuthApps")
   133  	}
   134  
   135  	return apps, nil
   136  }
   137  
   138  func (as SqlOAuthStore) GetAuthorizedApps(userId string, offset, limit int) ([]*model.OAuthApp, error) {
   139  	var apps []*model.OAuthApp
   140  
   141  	if _, err := as.GetReplica().Select(&apps,
   142  		`SELECT o.* FROM OAuthApps AS o INNER JOIN
   143  			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 {
   144  		return nil, errors.Wrapf(err, "failed to find OAuthApps with userId=%s", userId)
   145  	}
   146  
   147  	return apps, nil
   148  }
   149  
   150  func (as SqlOAuthStore) DeleteApp(id string) error {
   151  	// wrap in a transaction so that if one fails, everything fails
   152  	transaction, err := as.GetMaster().Begin()
   153  	if err != nil {
   154  		return errors.Wrap(err, "begin_transaction")
   155  	}
   156  	defer finalizeTransaction(transaction)
   157  
   158  	if err := as.deleteApp(transaction, id); err != nil {
   159  		return err
   160  	}
   161  
   162  	if err := transaction.Commit(); err != nil {
   163  		// don't need to rollback here since the transaction is already closed
   164  		return errors.Wrap(err, "commit_transaction")
   165  	}
   166  	return nil
   167  }
   168  
   169  func (as SqlOAuthStore) SaveAccessData(accessData *model.AccessData) (*model.AccessData, error) {
   170  	if err := accessData.IsValid(); err != nil {
   171  		return nil, err
   172  	}
   173  
   174  	if err := as.GetMaster().Insert(accessData); err != nil {
   175  		return nil, errors.Wrap(err, "failed to save AccessData")
   176  	}
   177  	return accessData, nil
   178  }
   179  
   180  func (as SqlOAuthStore) GetAccessData(token string) (*model.AccessData, error) {
   181  	accessData := model.AccessData{}
   182  
   183  	if err := as.GetReplica().SelectOne(&accessData, "SELECT * FROM OAuthAccessData WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil {
   184  		return nil, errors.Wrapf(err, "failed to get OAuthAccessData with token=%s", token)
   185  	}
   186  	return &accessData, nil
   187  }
   188  
   189  func (as SqlOAuthStore) GetAccessDataByUserForApp(userId, clientId string) ([]*model.AccessData, error) {
   190  	var accessData []*model.AccessData
   191  
   192  	if _, err := as.GetReplica().Select(&accessData,
   193  		"SELECT * FROM OAuthAccessData WHERE UserId = :UserId AND ClientId = :ClientId",
   194  		map[string]interface{}{"UserId": userId, "ClientId": clientId}); err != nil {
   195  		return nil, errors.Wrapf(err, "failed to delete OAuthAccessData with userId=%s and clientId=%s", userId, clientId)
   196  	}
   197  	return accessData, nil
   198  }
   199  
   200  func (as SqlOAuthStore) GetAccessDataByRefreshToken(token string) (*model.AccessData, error) {
   201  	accessData := model.AccessData{}
   202  
   203  	if err := as.GetReplica().SelectOne(&accessData, "SELECT * FROM OAuthAccessData WHERE RefreshToken = :Token", map[string]interface{}{"Token": token}); err != nil {
   204  		return nil, errors.Wrapf(err, "failed to find OAuthAccessData with refreshToken=%s", token)
   205  	}
   206  	return &accessData, nil
   207  }
   208  
   209  func (as SqlOAuthStore) GetPreviousAccessData(userId, clientId string) (*model.AccessData, error) {
   210  	accessData := model.AccessData{}
   211  
   212  	if err := as.GetReplica().SelectOne(&accessData, "SELECT * FROM OAuthAccessData WHERE ClientId = :ClientId AND UserId = :UserId",
   213  		map[string]interface{}{"ClientId": clientId, "UserId": userId}); err != nil {
   214  		if err == sql.ErrNoRows {
   215  			return nil, nil
   216  		}
   217  
   218  		return nil, errors.Wrapf(err, "failed to get AccessData with clientId=%s and userId=%s", clientId, userId)
   219  	}
   220  	return &accessData, nil
   221  }
   222  
   223  func (as SqlOAuthStore) UpdateAccessData(accessData *model.AccessData) (*model.AccessData, error) {
   224  	if err := accessData.IsValid(); err != nil {
   225  		return nil, err
   226  	}
   227  
   228  	if _, err := as.GetMaster().Exec("UPDATE OAuthAccessData SET Token = :Token, ExpiresAt = :ExpiresAt, RefreshToken = :RefreshToken WHERE ClientId = :ClientId AND UserID = :UserId",
   229  		map[string]interface{}{"Token": accessData.Token, "ExpiresAt": accessData.ExpiresAt, "RefreshToken": accessData.RefreshToken, "ClientId": accessData.ClientId, "UserId": accessData.UserId}); err != nil {
   230  		return nil, errors.Wrapf(err, "failed to update OAuthAccessData with userId=%s and clientId=%s", accessData.UserId, accessData.ClientId)
   231  	}
   232  	return accessData, nil
   233  }
   234  
   235  func (as SqlOAuthStore) RemoveAccessData(token string) error {
   236  	if _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil {
   237  		return errors.Wrapf(err, "failed to delete OAuthAccessData with token=%s", token)
   238  	}
   239  	return nil
   240  }
   241  
   242  func (as SqlOAuthStore) RemoveAllAccessData() error {
   243  	if _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData", map[string]interface{}{}); err != nil {
   244  		return errors.Wrap(err, "failed to delete OAuthAccessData")
   245  	}
   246  	return nil
   247  }
   248  
   249  func (as SqlOAuthStore) SaveAuthData(authData *model.AuthData) (*model.AuthData, error) {
   250  	authData.PreSave()
   251  	if err := authData.IsValid(); err != nil {
   252  		return nil, err
   253  	}
   254  
   255  	if err := as.GetMaster().Insert(authData); err != nil {
   256  		return nil, errors.Wrap(err, "failed to save AuthData")
   257  	}
   258  	return authData, nil
   259  }
   260  
   261  func (as SqlOAuthStore) GetAuthData(code string) (*model.AuthData, error) {
   262  	obj, err := as.GetReplica().Get(model.AuthData{}, code)
   263  	if err != nil {
   264  		return nil, errors.Wrapf(err, "failed to get AuthData with code=%s", code)
   265  	}
   266  	if obj == nil {
   267  		return nil, store.NewErrNotFound("AuthData", fmt.Sprintf("code=%s", code))
   268  	}
   269  	return obj.(*model.AuthData), nil
   270  }
   271  
   272  func (as SqlOAuthStore) RemoveAuthData(code string) error {
   273  	_, err := as.GetMaster().Exec("DELETE FROM OAuthAuthData WHERE Code = :Code", map[string]interface{}{"Code": code})
   274  	if err != nil {
   275  		return errors.Wrapf(err, "failed to delete AuthData with code=%s", code)
   276  	}
   277  	return nil
   278  }
   279  
   280  func (as SqlOAuthStore) PermanentDeleteAuthDataByUser(userId string) error {
   281  	_, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
   282  	if err != nil {
   283  		return errors.Wrapf(err, "failed to delete OAuthAccessData with userId=%s", userId)
   284  	}
   285  	return nil
   286  }
   287  
   288  func (as SqlOAuthStore) deleteApp(transaction *gorp.Transaction, clientId string) error {
   289  	if _, err := transaction.Exec("DELETE FROM OAuthApps WHERE Id = :Id", map[string]interface{}{"Id": clientId}); err != nil {
   290  		return errors.Wrapf(err, "failed to delete OAuthApp with id=%s", clientId)
   291  	}
   292  
   293  	return as.deleteOAuthAppSessions(transaction, clientId)
   294  }
   295  
   296  func (as SqlOAuthStore) deleteOAuthAppSessions(transaction *gorp.Transaction, clientId string) error {
   297  
   298  	query := ""
   299  	if as.DriverName() == model.DATABASE_DRIVER_POSTGRES {
   300  		query = "DELETE FROM Sessions s USING OAuthAccessData o WHERE o.Token = s.Token AND o.ClientId = :Id"
   301  	} else if as.DriverName() == model.DATABASE_DRIVER_MYSQL {
   302  		query = "DELETE s.* FROM Sessions s INNER JOIN OAuthAccessData o ON o.Token = s.Token WHERE o.ClientId = :Id"
   303  	}
   304  
   305  	if _, err := transaction.Exec(query, map[string]interface{}{"Id": clientId}); err != nil {
   306  		return errors.Wrapf(err, "failed to delete Session with OAuthAccessData.Id=%s", clientId)
   307  	}
   308  
   309  	return as.deleteOAuthTokens(transaction, clientId)
   310  }
   311  
   312  func (as SqlOAuthStore) deleteOAuthTokens(transaction *gorp.Transaction, clientId string) error {
   313  	if _, err := transaction.Exec("DELETE FROM OAuthAccessData WHERE ClientId = :Id", map[string]interface{}{"Id": clientId}); err != nil {
   314  		return errors.Wrapf(err, "failed to delete OAuthAccessData with id=%s", clientId)
   315  	}
   316  
   317  	return as.deleteAppExtras(transaction, clientId)
   318  }
   319  
   320  func (as SqlOAuthStore) deleteAppExtras(transaction *gorp.Transaction, clientId string) error {
   321  	if _, err := transaction.Exec(
   322  		`DELETE FROM
   323  			Preferences
   324  		WHERE
   325  			Category = :Category
   326  			AND Name = :Name`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, "Name": clientId}); err != nil {
   327  		return errors.Wrapf(err, "failed to delete Preferences with name=%s", clientId)
   328  	}
   329  
   330  	return nil
   331  }