github.com/vnforks/kid/v5@v5.22.1-0.20200408055009-b89d99c65676/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  	"net/http"
     8  	"strings"
     9  
    10  	"github.com/mattermost/gorp"
    11  	"github.com/vnforks/kid/v5/model"
    12  	"github.com/vnforks/kid/v5/store"
    13  )
    14  
    15  type SqlOAuthStore struct {
    16  	SqlStore
    17  }
    18  
    19  func newSqlOAuthStore(sqlStore SqlStore) store.OAuthStore {
    20  	as := &SqlOAuthStore{sqlStore}
    21  
    22  	for _, db := range sqlStore.GetAllConns() {
    23  		table := db.AddTableWithName(model.OAuthApp{}, "OAuthApps").SetKeys(false, "Id")
    24  		table.ColMap("Id").SetMaxSize(26)
    25  		table.ColMap("CreatorId").SetMaxSize(26)
    26  		table.ColMap("ClientSecret").SetMaxSize(128)
    27  		table.ColMap("Name").SetMaxSize(64)
    28  		table.ColMap("Description").SetMaxSize(512)
    29  		table.ColMap("CallbackUrls").SetMaxSize(1024)
    30  		table.ColMap("Homepage").SetMaxSize(256)
    31  		table.ColMap("IconURL").SetMaxSize(512)
    32  
    33  		tableAuth := db.AddTableWithName(model.AuthData{}, "OAuthAuthData").SetKeys(false, "Code")
    34  		tableAuth.ColMap("UserId").SetMaxSize(26)
    35  		tableAuth.ColMap("ClientId").SetMaxSize(26)
    36  		tableAuth.ColMap("Code").SetMaxSize(128)
    37  		tableAuth.ColMap("RedirectUri").SetMaxSize(256)
    38  		tableAuth.ColMap("State").SetMaxSize(1024)
    39  		tableAuth.ColMap("Scope").SetMaxSize(128)
    40  
    41  		tableAccess := db.AddTableWithName(model.AccessData{}, "OAuthAccessData").SetKeys(false, "Token")
    42  		tableAccess.ColMap("ClientId").SetMaxSize(26)
    43  		tableAccess.ColMap("UserId").SetMaxSize(26)
    44  		tableAccess.ColMap("Token").SetMaxSize(26)
    45  		tableAccess.ColMap("RefreshToken").SetMaxSize(26)
    46  		tableAccess.ColMap("RedirectUri").SetMaxSize(256)
    47  		tableAccess.ColMap("Scope").SetMaxSize(128)
    48  		tableAccess.SetUniqueTogether("ClientId", "UserId")
    49  	}
    50  
    51  	return as
    52  }
    53  
    54  func (as SqlOAuthStore) createIndexesIfNotExists() {
    55  	as.CreateIndexIfNotExists("idx_oauthapps_creator_id", "OAuthApps", "CreatorId")
    56  	as.CreateIndexIfNotExists("idx_oauthaccessdata_client_id", "OAuthAccessData", "ClientId")
    57  	as.CreateIndexIfNotExists("idx_oauthaccessdata_user_id", "OAuthAccessData", "UserId")
    58  	as.CreateIndexIfNotExists("idx_oauthaccessdata_refresh_token", "OAuthAccessData", "RefreshToken")
    59  	as.CreateIndexIfNotExists("idx_oauthauthdata_client_id", "OAuthAuthData", "Code")
    60  }
    61  
    62  func (as SqlOAuthStore) SaveApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) {
    63  	if len(app.Id) > 0 {
    64  		return nil, model.NewAppError("SqlOAuthStore.SaveApp", "store.sql_oauth.save_app.existing.app_error", nil, "app_id="+app.Id, http.StatusBadRequest)
    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, model.NewAppError("SqlOAuthStore.SaveApp", "store.sql_oauth.save_app.save.app_error", nil, "app_id="+app.Id+", "+err.Error(), http.StatusInternalServerError)
    74  	}
    75  	return app, nil
    76  }
    77  
    78  func (as SqlOAuthStore) UpdateApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) {
    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, model.NewAppError("SqlOAuthStore.UpdateApp", "store.sql_oauth.update_app.finding.app_error", nil, "app_id="+app.Id+", "+err.Error(), http.StatusInternalServerError)
    88  	}
    89  	if oldAppResult == nil {
    90  		return nil, model.NewAppError("SqlOAuthStore.UpdateApp", "store.sql_oauth.update_app.find.app_error", nil, "app_id="+app.Id, http.StatusBadRequest)
    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, model.NewAppError("SqlOAuthStore.UpdateApp", "store.sql_oauth.update_app.updating.app_error", nil, "app_id="+app.Id+", "+err.Error(), http.StatusInternalServerError)
   100  	}
   101  	if count != 1 {
   102  		return nil, model.NewAppError("SqlOAuthStore.UpdateApp", "store.sql_oauth.update_app.update.app_error", nil, "app_id="+app.Id, http.StatusBadRequest)
   103  	}
   104  	return app, nil
   105  }
   106  
   107  func (as SqlOAuthStore) GetApp(id string) (*model.OAuthApp, *model.AppError) {
   108  	obj, err := as.GetReplica().Get(model.OAuthApp{}, id)
   109  	if err != nil {
   110  		return nil, model.NewAppError("SqlOAuthStore.GetApp", "store.sql_oauth.get_app.finding.app_error", nil, "app_id="+id+", "+err.Error(), http.StatusInternalServerError)
   111  	}
   112  	if obj == nil {
   113  		return nil, model.NewAppError("SqlOAuthStore.GetApp", "store.sql_oauth.get_app.find.app_error", nil, "app_id="+id, http.StatusNotFound)
   114  	}
   115  	return obj.(*model.OAuthApp), nil
   116  }
   117  
   118  func (as SqlOAuthStore) GetAppByUser(userId string, offset, limit int) ([]*model.OAuthApp, *model.AppError) {
   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, model.NewAppError("SqlOAuthStore.GetAppByUser", "store.sql_oauth.get_app_by_user.find.app_error", nil, "user_id="+userId+", "+err.Error(), http.StatusInternalServerError)
   123  	}
   124  
   125  	return apps, nil
   126  }
   127  
   128  func (as SqlOAuthStore) GetApps(offset, limit int) ([]*model.OAuthApp, *model.AppError) {
   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, model.NewAppError("SqlOAuthStore.GetAppByUser", "store.sql_oauth.get_apps.find.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   133  	}
   134  
   135  	return apps, nil
   136  }
   137  
   138  func (as SqlOAuthStore) GetAuthorizedApps(userId string, offset, limit int) ([]*model.OAuthApp, *model.AppError) {
   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, model.NewAppError("SqlOAuthStore.GetAuthorizedApps", "store.sql_oauth.get_apps.find.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   145  	}
   146  
   147  	return apps, nil
   148  }
   149  
   150  func (as SqlOAuthStore) DeleteApp(id string) *model.AppError {
   151  	// wrap in a transaction so that if one fails, everything fails
   152  	transaction, err := as.GetMaster().Begin()
   153  	if err != nil {
   154  		return model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete.open_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
   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 model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete.commit_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
   165  	}
   166  	return nil
   167  }
   168  
   169  func (as SqlOAuthStore) SaveAccessData(accessData *model.AccessData) (*model.AccessData, *model.AppError) {
   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, model.NewAppError("SqlOAuthStore.SaveAccessData", "store.sql_oauth.save_access_data.app_error", nil, err.Error(), http.StatusInternalServerError)
   176  	}
   177  	return accessData, nil
   178  }
   179  
   180  func (as SqlOAuthStore) GetAccessData(token string) (*model.AccessData, *model.AppError) {
   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, model.NewAppError("SqlOAuthStore.GetAccessData", "store.sql_oauth.get_access_data.app_error", nil, err.Error(), http.StatusInternalServerError)
   185  	}
   186  	return &accessData, nil
   187  }
   188  
   189  func (as SqlOAuthStore) GetAccessDataByUserForApp(userId, clientId string) ([]*model.AccessData, *model.AppError) {
   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, model.NewAppError("SqlOAuthStore.GetAccessDataByUserForApp", "store.sql_oauth.get_access_data_by_user_for_app.app_error", nil, "user_id="+userId+" client_id="+clientId, http.StatusInternalServerError)
   196  	}
   197  	return accessData, nil
   198  }
   199  
   200  func (as SqlOAuthStore) GetAccessDataByRefreshToken(token string) (*model.AccessData, *model.AppError) {
   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, model.NewAppError("SqlOAuthStore.GetAccessData", "store.sql_oauth.get_access_data.app_error", nil, err.Error(), http.StatusInternalServerError)
   205  	}
   206  	return &accessData, nil
   207  }
   208  
   209  func (as SqlOAuthStore) GetPreviousAccessData(userId, clientId string) (*model.AccessData, *model.AppError) {
   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 strings.Contains(err.Error(), "no rows") {
   215  			return nil, nil
   216  		}
   217  		return nil, model.NewAppError("SqlOAuthStore.GetPreviousAccessData", "store.sql_oauth.get_previous_access_data.app_error", nil, err.Error(), http.StatusNotFound)
   218  	}
   219  	return &accessData, nil
   220  }
   221  
   222  func (as SqlOAuthStore) UpdateAccessData(accessData *model.AccessData) (*model.AccessData, *model.AppError) {
   223  	if err := accessData.IsValid(); err != nil {
   224  		return nil, err
   225  	}
   226  
   227  	if _, err := as.GetMaster().Exec("UPDATE OAuthAccessData SET Token = :Token, ExpiresAt = :ExpiresAt, RefreshToken = :RefreshToken WHERE ClientId = :ClientId AND UserID = :UserId",
   228  		map[string]interface{}{"Token": accessData.Token, "ExpiresAt": accessData.ExpiresAt, "RefreshToken": accessData.RefreshToken, "ClientId": accessData.ClientId, "UserId": accessData.UserId}); err != nil {
   229  		return nil, model.NewAppError("SqlOAuthStore.Update", "store.sql_oauth.update_access_data.app_error", nil,
   230  			"clientId="+accessData.ClientId+",userId="+accessData.UserId+", "+err.Error(), http.StatusInternalServerError)
   231  	}
   232  	return accessData, nil
   233  }
   234  
   235  func (as SqlOAuthStore) RemoveAccessData(token string) *model.AppError {
   236  	if _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil {
   237  		return model.NewAppError("SqlOAuthStore.RemoveAccessData", "store.sql_oauth.remove_access_data.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   238  	}
   239  	return nil
   240  }
   241  
   242  func (as SqlOAuthStore) RemoveAllAccessData() *model.AppError {
   243  	if _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData", map[string]interface{}{}); err != nil {
   244  		return model.NewAppError("SqlOAuthStore.RemoveAccessData", "store.sql_oauth.remove_access_data.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   245  	}
   246  	return nil
   247  }
   248  
   249  func (as SqlOAuthStore) SaveAuthData(authData *model.AuthData) (*model.AuthData, *model.AppError) {
   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, model.NewAppError("SqlOAuthStore.SaveAuthData", "store.sql_oauth.save_auth_data.app_error", nil, err.Error(), http.StatusInternalServerError)
   257  	}
   258  	return authData, nil
   259  }
   260  
   261  func (as SqlOAuthStore) GetAuthData(code string) (*model.AuthData, *model.AppError) {
   262  	obj, err := as.GetReplica().Get(model.AuthData{}, code)
   263  	if err != nil {
   264  		return nil, model.NewAppError("SqlOAuthStore.GetAuthData", "store.sql_oauth.get_auth_data.finding.app_error", nil, err.Error(), http.StatusInternalServerError)
   265  	}
   266  	if obj == nil {
   267  		return nil, model.NewAppError("SqlOAuthStore.GetAuthData", "store.sql_oauth.get_auth_data.find.app_error", nil, "", http.StatusNotFound)
   268  	}
   269  	return obj.(*model.AuthData), nil
   270  }
   271  
   272  func (as SqlOAuthStore) RemoveAuthData(code string) *model.AppError {
   273  	_, err := as.GetMaster().Exec("DELETE FROM OAuthAuthData WHERE Code = :Code", map[string]interface{}{"Code": code})
   274  	if err != nil {
   275  		return model.NewAppError("SqlOAuthStore.RemoveAuthData", "store.sql_oauth.remove_auth_data.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   276  	}
   277  	return nil
   278  }
   279  
   280  func (as SqlOAuthStore) PermanentDeleteAuthDataByUser(userId string) *model.AppError {
   281  	_, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
   282  	if err != nil {
   283  		return model.NewAppError("SqlOAuthStore.RemoveAuthDataByUserId", "store.sql_oauth.permanent_delete_auth_data_by_user.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   284  	}
   285  	return nil
   286  }
   287  
   288  func (as SqlOAuthStore) deleteApp(transaction *gorp.Transaction, clientId string) *model.AppError {
   289  	if _, err := transaction.Exec("DELETE FROM OAuthApps WHERE Id = :Id", map[string]interface{}{"Id": clientId}); err != nil {
   290  		return model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError)
   291  	}
   292  
   293  	return as.deleteOAuthAppSessions(transaction, clientId)
   294  }
   295  
   296  func (as SqlOAuthStore) deleteOAuthAppSessions(transaction *gorp.Transaction, clientId string) *model.AppError {
   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 model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError)
   307  	}
   308  
   309  	return as.deleteOAuthTokens(transaction, clientId)
   310  }
   311  
   312  func (as SqlOAuthStore) deleteOAuthTokens(transaction *gorp.Transaction, clientId string) *model.AppError {
   313  	if _, err := transaction.Exec("DELETE FROM OAuthAccessData WHERE ClientId = :Id", map[string]interface{}{"Id": clientId}); err != nil {
   314  		return model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError)
   315  	}
   316  
   317  	return as.deleteAppExtras(transaction, clientId)
   318  }
   319  
   320  func (as SqlOAuthStore) deleteAppExtras(transaction *gorp.Transaction, clientId string) *model.AppError {
   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 model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_preference.delete.app_error", nil, err.Error(), http.StatusInternalServerError)
   328  	}
   329  
   330  	return nil
   331  }