github.com/qichengzx/mattermost-server@v4.5.1-0.20180604164826-2c75247c97d0+incompatible/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/mattermost/mattermost-server/model"
    12  	"github.com/mattermost/mattermost-server/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) store.StoreChannel {
    63  	return store.Do(func(result *store.StoreResult) {
    64  		if len(app.Id) > 0 {
    65  			result.Err = model.NewAppError("SqlOAuthStore.SaveApp", "store.sql_oauth.save_app.existing.app_error", nil, "app_id="+app.Id, http.StatusBadRequest)
    66  			return
    67  		}
    68  
    69  		app.PreSave()
    70  		if result.Err = app.IsValid(); result.Err != nil {
    71  			return
    72  		}
    73  
    74  		if err := as.GetMaster().Insert(app); err != nil {
    75  			result.Err = model.NewAppError("SqlOAuthStore.SaveApp", "store.sql_oauth.save_app.save.app_error", nil, "app_id="+app.Id+", "+err.Error(), http.StatusInternalServerError)
    76  		} else {
    77  			result.Data = app
    78  		}
    79  	})
    80  }
    81  
    82  func (as SqlOAuthStore) UpdateApp(app *model.OAuthApp) store.StoreChannel {
    83  	return store.Do(func(result *store.StoreResult) {
    84  		app.PreUpdate()
    85  
    86  		if result.Err = app.IsValid(); result.Err != nil {
    87  			return
    88  		}
    89  
    90  		if oldAppResult, err := as.GetMaster().Get(model.OAuthApp{}, app.Id); err != nil {
    91  			result.Err = model.NewAppError("SqlOAuthStore.UpdateApp", "store.sql_oauth.update_app.finding.app_error", nil, "app_id="+app.Id+", "+err.Error(), http.StatusInternalServerError)
    92  		} else if oldAppResult == nil {
    93  			result.Err = model.NewAppError("SqlOAuthStore.UpdateApp", "store.sql_oauth.update_app.find.app_error", nil, "app_id="+app.Id, http.StatusBadRequest)
    94  		} else {
    95  			oldApp := oldAppResult.(*model.OAuthApp)
    96  			app.CreateAt = oldApp.CreateAt
    97  			app.CreatorId = oldApp.CreatorId
    98  
    99  			if count, err := as.GetMaster().Update(app); err != nil {
   100  				result.Err = model.NewAppError("SqlOAuthStore.UpdateApp", "store.sql_oauth.update_app.updating.app_error", nil, "app_id="+app.Id+", "+err.Error(), http.StatusInternalServerError)
   101  			} else if count != 1 {
   102  				result.Err = model.NewAppError("SqlOAuthStore.UpdateApp", "store.sql_oauth.update_app.update.app_error", nil, "app_id="+app.Id, http.StatusBadRequest)
   103  			} else {
   104  				result.Data = [2]*model.OAuthApp{app, oldApp}
   105  			}
   106  		}
   107  	})
   108  }
   109  
   110  func (as SqlOAuthStore) GetApp(id string) store.StoreChannel {
   111  	return store.Do(func(result *store.StoreResult) {
   112  		if obj, err := as.GetReplica().Get(model.OAuthApp{}, id); err != nil {
   113  			result.Err = model.NewAppError("SqlOAuthStore.GetApp", "store.sql_oauth.get_app.finding.app_error", nil, "app_id="+id+", "+err.Error(), http.StatusInternalServerError)
   114  		} else if obj == nil {
   115  			result.Err = model.NewAppError("SqlOAuthStore.GetApp", "store.sql_oauth.get_app.find.app_error", nil, "app_id="+id, http.StatusNotFound)
   116  		} else {
   117  			result.Data = obj.(*model.OAuthApp)
   118  		}
   119  	})
   120  }
   121  
   122  func (as SqlOAuthStore) GetAppByUser(userId string, offset, limit int) store.StoreChannel {
   123  	return store.Do(func(result *store.StoreResult) {
   124  		var apps []*model.OAuthApp
   125  
   126  		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 {
   127  			result.Err = model.NewAppError("SqlOAuthStore.GetAppByUser", "store.sql_oauth.get_app_by_user.find.app_error", nil, "user_id="+userId+", "+err.Error(), http.StatusInternalServerError)
   128  		}
   129  
   130  		result.Data = apps
   131  	})
   132  }
   133  
   134  func (as SqlOAuthStore) GetApps(offset, limit int) store.StoreChannel {
   135  	return store.Do(func(result *store.StoreResult) {
   136  		var apps []*model.OAuthApp
   137  
   138  		if _, err := as.GetReplica().Select(&apps, "SELECT * FROM OAuthApps LIMIT :Limit OFFSET :Offset", map[string]interface{}{"Offset": offset, "Limit": limit}); err != nil {
   139  			result.Err = model.NewAppError("SqlOAuthStore.GetAppByUser", "store.sql_oauth.get_apps.find.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   140  		}
   141  
   142  		result.Data = apps
   143  	})
   144  }
   145  
   146  func (as SqlOAuthStore) GetAuthorizedApps(userId string, offset, limit int) store.StoreChannel {
   147  	return store.Do(func(result *store.StoreResult) {
   148  		var apps []*model.OAuthApp
   149  
   150  		if _, err := as.GetReplica().Select(&apps,
   151  			`SELECT o.* FROM OAuthApps AS o INNER JOIN
   152  			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 {
   153  			result.Err = model.NewAppError("SqlOAuthStore.GetAuthorizedApps", "store.sql_oauth.get_apps.find.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   154  		}
   155  
   156  		result.Data = apps
   157  	})
   158  }
   159  
   160  func (as SqlOAuthStore) DeleteApp(id string) store.StoreChannel {
   161  	return store.Do(func(result *store.StoreResult) {
   162  		// wrap in a transaction so that if one fails, everything fails
   163  		transaction, err := as.GetMaster().Begin()
   164  		if err != nil {
   165  			result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete.open_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
   166  		} else {
   167  			if extrasResult := as.deleteApp(transaction, id); extrasResult.Err != nil {
   168  				*result = extrasResult
   169  			}
   170  
   171  			if result.Err == nil {
   172  				if err := transaction.Commit(); err != nil {
   173  					// don't need to rollback here since the transaction is already closed
   174  					result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete.commit_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
   175  				}
   176  			} else {
   177  				if err := transaction.Rollback(); err != nil {
   178  					result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete.rollback_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
   179  				}
   180  			}
   181  		}
   182  	})
   183  }
   184  
   185  func (as SqlOAuthStore) SaveAccessData(accessData *model.AccessData) store.StoreChannel {
   186  	return store.Do(func(result *store.StoreResult) {
   187  		if result.Err = accessData.IsValid(); result.Err != nil {
   188  			return
   189  		}
   190  
   191  		if err := as.GetMaster().Insert(accessData); err != nil {
   192  			result.Err = model.NewAppError("SqlOAuthStore.SaveAccessData", "store.sql_oauth.save_access_data.app_error", nil, err.Error(), http.StatusInternalServerError)
   193  		} else {
   194  			result.Data = accessData
   195  		}
   196  	})
   197  }
   198  
   199  func (as SqlOAuthStore) GetAccessData(token string) store.StoreChannel {
   200  	return store.Do(func(result *store.StoreResult) {
   201  		accessData := model.AccessData{}
   202  
   203  		if err := as.GetReplica().SelectOne(&accessData, "SELECT * FROM OAuthAccessData WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil {
   204  			result.Err = model.NewAppError("SqlOAuthStore.GetAccessData", "store.sql_oauth.get_access_data.app_error", nil, err.Error(), http.StatusInternalServerError)
   205  		} else {
   206  			result.Data = &accessData
   207  		}
   208  	})
   209  }
   210  
   211  func (as SqlOAuthStore) GetAccessDataByUserForApp(userId, clientId string) store.StoreChannel {
   212  	return store.Do(func(result *store.StoreResult) {
   213  		var accessData []*model.AccessData
   214  
   215  		if _, err := as.GetReplica().Select(&accessData,
   216  			"SELECT * FROM OAuthAccessData WHERE UserId = :UserId AND ClientId = :ClientId",
   217  			map[string]interface{}{"UserId": userId, "ClientId": clientId}); err != nil {
   218  			result.Err = 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)
   219  		} else {
   220  			result.Data = accessData
   221  		}
   222  	})
   223  }
   224  
   225  func (as SqlOAuthStore) GetAccessDataByRefreshToken(token string) store.StoreChannel {
   226  	return store.Do(func(result *store.StoreResult) {
   227  		accessData := model.AccessData{}
   228  
   229  		if err := as.GetReplica().SelectOne(&accessData, "SELECT * FROM OAuthAccessData WHERE RefreshToken = :Token", map[string]interface{}{"Token": token}); err != nil {
   230  			result.Err = model.NewAppError("SqlOAuthStore.GetAccessData", "store.sql_oauth.get_access_data.app_error", nil, err.Error(), http.StatusInternalServerError)
   231  		} else {
   232  			result.Data = &accessData
   233  		}
   234  	})
   235  }
   236  
   237  func (as SqlOAuthStore) GetPreviousAccessData(userId, clientId string) store.StoreChannel {
   238  	return store.Do(func(result *store.StoreResult) {
   239  		accessData := model.AccessData{}
   240  
   241  		if err := as.GetReplica().SelectOne(&accessData, "SELECT * FROM OAuthAccessData WHERE ClientId = :ClientId AND UserId = :UserId",
   242  			map[string]interface{}{"ClientId": clientId, "UserId": userId}); err != nil {
   243  			if strings.Contains(err.Error(), "no rows") {
   244  				result.Data = nil
   245  			} else {
   246  				result.Err = model.NewAppError("SqlOAuthStore.GetPreviousAccessData", "store.sql_oauth.get_previous_access_data.app_error", nil, err.Error(), http.StatusNotFound)
   247  			}
   248  		} else {
   249  			result.Data = &accessData
   250  		}
   251  	})
   252  }
   253  
   254  func (as SqlOAuthStore) UpdateAccessData(accessData *model.AccessData) store.StoreChannel {
   255  	return store.Do(func(result *store.StoreResult) {
   256  		if result.Err = accessData.IsValid(); result.Err != nil {
   257  			return
   258  		}
   259  
   260  		if _, err := as.GetMaster().Exec("UPDATE OAuthAccessData SET Token = :Token, ExpiresAt = :ExpiresAt, RefreshToken = :RefreshToken WHERE ClientId = :ClientId AND UserID = :UserId",
   261  			map[string]interface{}{"Token": accessData.Token, "ExpiresAt": accessData.ExpiresAt, "RefreshToken": accessData.RefreshToken, "ClientId": accessData.ClientId, "UserId": accessData.UserId}); err != nil {
   262  			result.Err = model.NewAppError("SqlOAuthStore.Update", "store.sql_oauth.update_access_data.app_error", nil,
   263  				"clientId="+accessData.ClientId+",userId="+accessData.UserId+", "+err.Error(), http.StatusInternalServerError)
   264  		} else {
   265  			result.Data = accessData
   266  		}
   267  	})
   268  }
   269  
   270  func (as SqlOAuthStore) RemoveAccessData(token string) store.StoreChannel {
   271  	return store.Do(func(result *store.StoreResult) {
   272  		if _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil {
   273  			result.Err = model.NewAppError("SqlOAuthStore.RemoveAccessData", "store.sql_oauth.remove_access_data.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   274  		}
   275  	})
   276  }
   277  
   278  func (as SqlOAuthStore) SaveAuthData(authData *model.AuthData) store.StoreChannel {
   279  	return store.Do(func(result *store.StoreResult) {
   280  		authData.PreSave()
   281  		if result.Err = authData.IsValid(); result.Err != nil {
   282  			return
   283  		}
   284  
   285  		if err := as.GetMaster().Insert(authData); err != nil {
   286  			result.Err = model.NewAppError("SqlOAuthStore.SaveAuthData", "store.sql_oauth.save_auth_data.app_error", nil, err.Error(), http.StatusInternalServerError)
   287  		} else {
   288  			result.Data = authData
   289  		}
   290  	})
   291  }
   292  
   293  func (as SqlOAuthStore) GetAuthData(code string) store.StoreChannel {
   294  	return store.Do(func(result *store.StoreResult) {
   295  		if obj, err := as.GetReplica().Get(model.AuthData{}, code); err != nil {
   296  			result.Err = model.NewAppError("SqlOAuthStore.GetAuthData", "store.sql_oauth.get_auth_data.finding.app_error", nil, err.Error(), http.StatusInternalServerError)
   297  		} else if obj == nil {
   298  			result.Err = model.NewAppError("SqlOAuthStore.GetAuthData", "store.sql_oauth.get_auth_data.find.app_error", nil, "", http.StatusNotFound)
   299  		} else {
   300  			result.Data = obj.(*model.AuthData)
   301  		}
   302  	})
   303  }
   304  
   305  func (as SqlOAuthStore) RemoveAuthData(code string) store.StoreChannel {
   306  	return store.Do(func(result *store.StoreResult) {
   307  		_, err := as.GetMaster().Exec("DELETE FROM OAuthAuthData WHERE Code = :Code", map[string]interface{}{"Code": code})
   308  		if err != nil {
   309  			result.Err = model.NewAppError("SqlOAuthStore.RemoveAuthData", "store.sql_oauth.remove_auth_data.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   310  		}
   311  	})
   312  }
   313  
   314  func (as SqlOAuthStore) PermanentDeleteAuthDataByUser(userId string) store.StoreChannel {
   315  	return store.Do(func(result *store.StoreResult) {
   316  		_, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
   317  		if err != nil {
   318  			result.Err = model.NewAppError("SqlOAuthStore.RemoveAuthDataByUserId", "store.sql_oauth.permanent_delete_auth_data_by_user.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
   319  		}
   320  	})
   321  }
   322  
   323  func (as SqlOAuthStore) deleteApp(transaction *gorp.Transaction, clientId string) store.StoreResult {
   324  	result := store.StoreResult{}
   325  
   326  	if _, err := transaction.Exec("DELETE FROM OAuthApps WHERE Id = :Id", map[string]interface{}{"Id": clientId}); err != nil {
   327  		result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError)
   328  		return result
   329  	}
   330  
   331  	return as.deleteOAuthAppSessions(transaction, clientId)
   332  }
   333  
   334  func (as SqlOAuthStore) deleteOAuthAppSessions(transaction *gorp.Transaction, clientId string) store.StoreResult {
   335  	result := store.StoreResult{}
   336  
   337  	query := ""
   338  	if as.DriverName() == model.DATABASE_DRIVER_POSTGRES {
   339  		query = "DELETE FROM Sessions s USING OAuthAccessData o WHERE o.Token = s.Token AND o.ClientId = :Id"
   340  	} else if as.DriverName() == model.DATABASE_DRIVER_MYSQL {
   341  		query = "DELETE s.* FROM Sessions s INNER JOIN OAuthAccessData o ON o.Token = s.Token WHERE o.ClientId = :Id"
   342  	}
   343  
   344  	if _, err := transaction.Exec(query, map[string]interface{}{"Id": clientId}); err != nil {
   345  		result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError)
   346  		return result
   347  	}
   348  
   349  	return as.deleteOAuthTokens(transaction, clientId)
   350  }
   351  
   352  func (as SqlOAuthStore) deleteOAuthTokens(transaction *gorp.Transaction, clientId string) store.StoreResult {
   353  	result := store.StoreResult{}
   354  
   355  	if _, err := transaction.Exec("DELETE FROM OAuthAccessData WHERE ClientId = :Id", map[string]interface{}{"Id": clientId}); err != nil {
   356  		result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError)
   357  		return result
   358  	}
   359  
   360  	return as.deleteAppExtras(transaction, clientId)
   361  }
   362  
   363  func (as SqlOAuthStore) deleteAppExtras(transaction *gorp.Transaction, clientId string) store.StoreResult {
   364  	result := store.StoreResult{}
   365  
   366  	if _, err := transaction.Exec(
   367  		`DELETE FROM
   368  			Preferences
   369  		WHERE
   370  			Category = :Category
   371  			AND Name = :Name`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, "Name": clientId}); err != nil {
   372  		result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_preference.delete.app_error", nil, err.Error(), http.StatusInternalServerError)
   373  		return result
   374  	}
   375  
   376  	return result
   377  }