You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

oauth2.go 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package auth
  4. import (
  5. "context"
  6. "crypto/sha256"
  7. "encoding/base32"
  8. "encoding/base64"
  9. "fmt"
  10. "net"
  11. "net/url"
  12. "strings"
  13. "code.gitea.io/gitea/models/db"
  14. "code.gitea.io/gitea/modules/container"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "code.gitea.io/gitea/modules/util"
  18. uuid "github.com/google/uuid"
  19. "golang.org/x/crypto/bcrypt"
  20. "xorm.io/builder"
  21. "xorm.io/xorm"
  22. )
  23. // OAuth2Application represents an OAuth2 client (RFC 6749)
  24. type OAuth2Application struct {
  25. ID int64 `xorm:"pk autoincr"`
  26. UID int64 `xorm:"INDEX"`
  27. Name string
  28. ClientID string `xorm:"unique"`
  29. ClientSecret string
  30. // OAuth defines both Confidential and Public client types
  31. // https://datatracker.ietf.org/doc/html/rfc6749#section-2.1
  32. // "Authorization servers MUST record the client type in the client registration details"
  33. // https://datatracker.ietf.org/doc/html/rfc8252#section-8.4
  34. ConfidentialClient bool `xorm:"NOT NULL DEFAULT TRUE"`
  35. RedirectURIs []string `xorm:"redirect_uris JSON TEXT"`
  36. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  37. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  38. }
  39. func init() {
  40. db.RegisterModel(new(OAuth2Application))
  41. db.RegisterModel(new(OAuth2AuthorizationCode))
  42. db.RegisterModel(new(OAuth2Grant))
  43. }
  44. type BuiltinOAuth2Application struct {
  45. ConfigName string
  46. DisplayName string
  47. RedirectURIs []string
  48. }
  49. func BuiltinApplications() map[string]*BuiltinOAuth2Application {
  50. m := make(map[string]*BuiltinOAuth2Application)
  51. m["a4792ccc-144e-407e-86c9-5e7d8d9c3269"] = &BuiltinOAuth2Application{
  52. ConfigName: "git-credential-oauth",
  53. DisplayName: "git-credential-oauth",
  54. RedirectURIs: []string{"http://127.0.0.1", "https://127.0.0.1"},
  55. }
  56. m["e90ee53c-94e2-48ac-9358-a874fb9e0662"] = &BuiltinOAuth2Application{
  57. ConfigName: "git-credential-manager",
  58. DisplayName: "Git Credential Manager",
  59. RedirectURIs: []string{"http://127.0.0.1", "https://127.0.0.1"},
  60. }
  61. m["d57cb8c4-630c-4168-8324-ec79935e18d4"] = &BuiltinOAuth2Application{
  62. ConfigName: "tea",
  63. DisplayName: "tea",
  64. RedirectURIs: []string{"http://127.0.0.1", "https://127.0.0.1"},
  65. }
  66. return m
  67. }
  68. func Init(ctx context.Context) error {
  69. builtinApps := BuiltinApplications()
  70. var builtinAllClientIDs []string
  71. for clientID := range builtinApps {
  72. builtinAllClientIDs = append(builtinAllClientIDs, clientID)
  73. }
  74. var registeredApps []*OAuth2Application
  75. if err := db.GetEngine(ctx).In("client_id", builtinAllClientIDs).Find(&registeredApps); err != nil {
  76. return err
  77. }
  78. clientIDsToAdd := container.Set[string]{}
  79. for _, configName := range setting.OAuth2.DefaultApplications {
  80. found := false
  81. for clientID, builtinApp := range builtinApps {
  82. if builtinApp.ConfigName == configName {
  83. clientIDsToAdd.Add(clientID) // add all user-configured apps to the "add" list
  84. found = true
  85. }
  86. }
  87. if !found {
  88. return fmt.Errorf("unknown oauth2 application: %q", configName)
  89. }
  90. }
  91. clientIDsToDelete := container.Set[string]{}
  92. for _, app := range registeredApps {
  93. if !clientIDsToAdd.Contains(app.ClientID) {
  94. clientIDsToDelete.Add(app.ClientID) // if a registered app is not in the "add" list, it should be deleted
  95. }
  96. }
  97. for _, app := range registeredApps {
  98. clientIDsToAdd.Remove(app.ClientID) // no need to re-add existing (registered) apps, so remove them from the set
  99. }
  100. for _, app := range registeredApps {
  101. if clientIDsToDelete.Contains(app.ClientID) {
  102. if err := deleteOAuth2Application(ctx, app.ID, 0); err != nil {
  103. return err
  104. }
  105. }
  106. }
  107. for clientID := range clientIDsToAdd {
  108. builtinApp := builtinApps[clientID]
  109. if err := db.Insert(ctx, &OAuth2Application{
  110. Name: builtinApp.DisplayName,
  111. ClientID: clientID,
  112. RedirectURIs: builtinApp.RedirectURIs,
  113. }); err != nil {
  114. return err
  115. }
  116. }
  117. return nil
  118. }
  119. // TableName sets the table name to `oauth2_application`
  120. func (app *OAuth2Application) TableName() string {
  121. return "oauth2_application"
  122. }
  123. // ContainsRedirectURI checks if redirectURI is allowed for app
  124. func (app *OAuth2Application) ContainsRedirectURI(redirectURI string) bool {
  125. contains := func(s string) bool {
  126. s = strings.TrimSuffix(strings.ToLower(s), "/")
  127. for _, u := range app.RedirectURIs {
  128. if strings.TrimSuffix(strings.ToLower(u), "/") == s {
  129. return true
  130. }
  131. }
  132. return false
  133. }
  134. if !app.ConfidentialClient {
  135. uri, err := url.Parse(redirectURI)
  136. // ignore port for http loopback uris following https://datatracker.ietf.org/doc/html/rfc8252#section-7.3
  137. if err == nil && uri.Scheme == "http" && uri.Port() != "" {
  138. ip := net.ParseIP(uri.Hostname())
  139. if ip != nil && ip.IsLoopback() {
  140. // strip port
  141. uri.Host = uri.Hostname()
  142. if contains(uri.String()) {
  143. return true
  144. }
  145. }
  146. }
  147. }
  148. return contains(redirectURI)
  149. }
  150. // Base32 characters, but lowercased.
  151. const lowerBase32Chars = "abcdefghijklmnopqrstuvwxyz234567"
  152. // base32 encoder that uses lowered characters without padding.
  153. var base32Lower = base32.NewEncoding(lowerBase32Chars).WithPadding(base32.NoPadding)
  154. // GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database
  155. func (app *OAuth2Application) GenerateClientSecret(ctx context.Context) (string, error) {
  156. rBytes, err := util.CryptoRandomBytes(32)
  157. if err != nil {
  158. return "", err
  159. }
  160. // Add a prefix to the base32, this is in order to make it easier
  161. // for code scanners to grab sensitive tokens.
  162. clientSecret := "gto_" + base32Lower.EncodeToString(rBytes)
  163. hashedSecret, err := bcrypt.GenerateFromPassword([]byte(clientSecret), bcrypt.DefaultCost)
  164. if err != nil {
  165. return "", err
  166. }
  167. app.ClientSecret = string(hashedSecret)
  168. if _, err := db.GetEngine(ctx).ID(app.ID).Cols("client_secret").Update(app); err != nil {
  169. return "", err
  170. }
  171. return clientSecret, nil
  172. }
  173. // ValidateClientSecret validates the given secret by the hash saved in database
  174. func (app *OAuth2Application) ValidateClientSecret(secret []byte) bool {
  175. return bcrypt.CompareHashAndPassword([]byte(app.ClientSecret), secret) == nil
  176. }
  177. // GetGrantByUserID returns a OAuth2Grant by its user and application ID
  178. func (app *OAuth2Application) GetGrantByUserID(ctx context.Context, userID int64) (grant *OAuth2Grant, err error) {
  179. grant = new(OAuth2Grant)
  180. if has, err := db.GetEngine(ctx).Where("user_id = ? AND application_id = ?", userID, app.ID).Get(grant); err != nil {
  181. return nil, err
  182. } else if !has {
  183. return nil, nil
  184. }
  185. return grant, nil
  186. }
  187. // CreateGrant generates a grant for an user
  188. func (app *OAuth2Application) CreateGrant(ctx context.Context, userID int64, scope string) (*OAuth2Grant, error) {
  189. grant := &OAuth2Grant{
  190. ApplicationID: app.ID,
  191. UserID: userID,
  192. Scope: scope,
  193. }
  194. err := db.Insert(ctx, grant)
  195. if err != nil {
  196. return nil, err
  197. }
  198. return grant, nil
  199. }
  200. // GetOAuth2ApplicationByClientID returns the oauth2 application with the given client_id. Returns an error if not found.
  201. func GetOAuth2ApplicationByClientID(ctx context.Context, clientID string) (app *OAuth2Application, err error) {
  202. app = new(OAuth2Application)
  203. has, err := db.GetEngine(ctx).Where("client_id = ?", clientID).Get(app)
  204. if !has {
  205. return nil, ErrOAuthClientIDInvalid{ClientID: clientID}
  206. }
  207. return app, err
  208. }
  209. // GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found.
  210. func GetOAuth2ApplicationByID(ctx context.Context, id int64) (app *OAuth2Application, err error) {
  211. app = new(OAuth2Application)
  212. has, err := db.GetEngine(ctx).ID(id).Get(app)
  213. if err != nil {
  214. return nil, err
  215. }
  216. if !has {
  217. return nil, ErrOAuthApplicationNotFound{ID: id}
  218. }
  219. return app, nil
  220. }
  221. // CreateOAuth2ApplicationOptions holds options to create an oauth2 application
  222. type CreateOAuth2ApplicationOptions struct {
  223. Name string
  224. UserID int64
  225. ConfidentialClient bool
  226. RedirectURIs []string
  227. }
  228. // CreateOAuth2Application inserts a new oauth2 application
  229. func CreateOAuth2Application(ctx context.Context, opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
  230. clientID := uuid.New().String()
  231. app := &OAuth2Application{
  232. UID: opts.UserID,
  233. Name: opts.Name,
  234. ClientID: clientID,
  235. RedirectURIs: opts.RedirectURIs,
  236. ConfidentialClient: opts.ConfidentialClient,
  237. }
  238. if err := db.Insert(ctx, app); err != nil {
  239. return nil, err
  240. }
  241. return app, nil
  242. }
  243. // UpdateOAuth2ApplicationOptions holds options to update an oauth2 application
  244. type UpdateOAuth2ApplicationOptions struct {
  245. ID int64
  246. Name string
  247. UserID int64
  248. ConfidentialClient bool
  249. RedirectURIs []string
  250. }
  251. // UpdateOAuth2Application updates an oauth2 application
  252. func UpdateOAuth2Application(ctx context.Context, opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) {
  253. ctx, committer, err := db.TxContext(ctx)
  254. if err != nil {
  255. return nil, err
  256. }
  257. defer committer.Close()
  258. app, err := GetOAuth2ApplicationByID(ctx, opts.ID)
  259. if err != nil {
  260. return nil, err
  261. }
  262. if app.UID != opts.UserID {
  263. return nil, fmt.Errorf("UID mismatch")
  264. }
  265. builtinApps := BuiltinApplications()
  266. if _, builtin := builtinApps[app.ClientID]; builtin {
  267. return nil, fmt.Errorf("failed to edit OAuth2 application: application is locked: %s", app.ClientID)
  268. }
  269. app.Name = opts.Name
  270. app.RedirectURIs = opts.RedirectURIs
  271. app.ConfidentialClient = opts.ConfidentialClient
  272. if err = updateOAuth2Application(ctx, app); err != nil {
  273. return nil, err
  274. }
  275. app.ClientSecret = ""
  276. return app, committer.Commit()
  277. }
  278. func updateOAuth2Application(ctx context.Context, app *OAuth2Application) error {
  279. if _, err := db.GetEngine(ctx).ID(app.ID).UseBool("confidential_client").Update(app); err != nil {
  280. return err
  281. }
  282. return nil
  283. }
  284. func deleteOAuth2Application(ctx context.Context, id, userid int64) error {
  285. sess := db.GetEngine(ctx)
  286. // the userid could be 0 if the app is instance-wide
  287. if deleted, err := sess.Where(builder.Eq{"id": id, "uid": userid}).Delete(&OAuth2Application{}); err != nil {
  288. return err
  289. } else if deleted == 0 {
  290. return ErrOAuthApplicationNotFound{ID: id}
  291. }
  292. codes := make([]*OAuth2AuthorizationCode, 0)
  293. // delete correlating auth codes
  294. if err := sess.Join("INNER", "oauth2_grant",
  295. "oauth2_authorization_code.grant_id = oauth2_grant.id AND oauth2_grant.application_id = ?", id).Find(&codes); err != nil {
  296. return err
  297. }
  298. codeIDs := make([]int64, 0, len(codes))
  299. for _, grant := range codes {
  300. codeIDs = append(codeIDs, grant.ID)
  301. }
  302. if _, err := sess.In("id", codeIDs).Delete(new(OAuth2AuthorizationCode)); err != nil {
  303. return err
  304. }
  305. if _, err := sess.Where("application_id = ?", id).Delete(new(OAuth2Grant)); err != nil {
  306. return err
  307. }
  308. return nil
  309. }
  310. // DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app.
  311. func DeleteOAuth2Application(ctx context.Context, id, userid int64) error {
  312. ctx, committer, err := db.TxContext(ctx)
  313. if err != nil {
  314. return err
  315. }
  316. defer committer.Close()
  317. app, err := GetOAuth2ApplicationByID(ctx, id)
  318. if err != nil {
  319. return err
  320. }
  321. builtinApps := BuiltinApplications()
  322. if _, builtin := builtinApps[app.ClientID]; builtin {
  323. return fmt.Errorf("failed to delete OAuth2 application: application is locked: %s", app.ClientID)
  324. }
  325. if err := deleteOAuth2Application(ctx, id, userid); err != nil {
  326. return err
  327. }
  328. return committer.Commit()
  329. }
  330. //////////////////////////////////////////////////////
  331. // OAuth2AuthorizationCode is a code to obtain an access token in combination with the client secret once. It has a limited lifetime.
  332. type OAuth2AuthorizationCode struct {
  333. ID int64 `xorm:"pk autoincr"`
  334. Grant *OAuth2Grant `xorm:"-"`
  335. GrantID int64
  336. Code string `xorm:"INDEX unique"`
  337. CodeChallenge string
  338. CodeChallengeMethod string
  339. RedirectURI string
  340. ValidUntil timeutil.TimeStamp `xorm:"index"`
  341. }
  342. // TableName sets the table name to `oauth2_authorization_code`
  343. func (code *OAuth2AuthorizationCode) TableName() string {
  344. return "oauth2_authorization_code"
  345. }
  346. // GenerateRedirectURI generates a redirect URI for a successful authorization request. State will be used if not empty.
  347. func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (*url.URL, error) {
  348. redirect, err := url.Parse(code.RedirectURI)
  349. if err != nil {
  350. return nil, err
  351. }
  352. q := redirect.Query()
  353. if state != "" {
  354. q.Set("state", state)
  355. }
  356. q.Set("code", code.Code)
  357. redirect.RawQuery = q.Encode()
  358. return redirect, err
  359. }
  360. // Invalidate deletes the auth code from the database to invalidate this code
  361. func (code *OAuth2AuthorizationCode) Invalidate(ctx context.Context) error {
  362. _, err := db.GetEngine(ctx).ID(code.ID).NoAutoCondition().Delete(code)
  363. return err
  364. }
  365. // ValidateCodeChallenge validates the given verifier against the saved code challenge. This is part of the PKCE implementation.
  366. func (code *OAuth2AuthorizationCode) ValidateCodeChallenge(verifier string) bool {
  367. switch code.CodeChallengeMethod {
  368. case "S256":
  369. // base64url(SHA256(verifier)) see https://tools.ietf.org/html/rfc7636#section-4.6
  370. h := sha256.Sum256([]byte(verifier))
  371. hashedVerifier := base64.RawURLEncoding.EncodeToString(h[:])
  372. return hashedVerifier == code.CodeChallenge
  373. case "plain":
  374. return verifier == code.CodeChallenge
  375. case "":
  376. return true
  377. default:
  378. // unsupported method -> return false
  379. return false
  380. }
  381. }
  382. // GetOAuth2AuthorizationByCode returns an authorization by its code
  383. func GetOAuth2AuthorizationByCode(ctx context.Context, code string) (auth *OAuth2AuthorizationCode, err error) {
  384. auth = new(OAuth2AuthorizationCode)
  385. if has, err := db.GetEngine(ctx).Where("code = ?", code).Get(auth); err != nil {
  386. return nil, err
  387. } else if !has {
  388. return nil, nil
  389. }
  390. auth.Grant = new(OAuth2Grant)
  391. if has, err := db.GetEngine(ctx).ID(auth.GrantID).Get(auth.Grant); err != nil {
  392. return nil, err
  393. } else if !has {
  394. return nil, nil
  395. }
  396. return auth, nil
  397. }
  398. //////////////////////////////////////////////////////
  399. // OAuth2Grant represents the permission of an user for a specific application to access resources
  400. type OAuth2Grant struct {
  401. ID int64 `xorm:"pk autoincr"`
  402. UserID int64 `xorm:"INDEX unique(user_application)"`
  403. Application *OAuth2Application `xorm:"-"`
  404. ApplicationID int64 `xorm:"INDEX unique(user_application)"`
  405. Counter int64 `xorm:"NOT NULL DEFAULT 1"`
  406. Scope string `xorm:"TEXT"`
  407. Nonce string `xorm:"TEXT"`
  408. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  409. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  410. }
  411. // TableName sets the table name to `oauth2_grant`
  412. func (grant *OAuth2Grant) TableName() string {
  413. return "oauth2_grant"
  414. }
  415. // GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the database
  416. func (grant *OAuth2Grant) GenerateNewAuthorizationCode(ctx context.Context, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) {
  417. rBytes, err := util.CryptoRandomBytes(32)
  418. if err != nil {
  419. return &OAuth2AuthorizationCode{}, err
  420. }
  421. // Add a prefix to the base32, this is in order to make it easier
  422. // for code scanners to grab sensitive tokens.
  423. codeSecret := "gta_" + base32Lower.EncodeToString(rBytes)
  424. code = &OAuth2AuthorizationCode{
  425. Grant: grant,
  426. GrantID: grant.ID,
  427. RedirectURI: redirectURI,
  428. Code: codeSecret,
  429. CodeChallenge: codeChallenge,
  430. CodeChallengeMethod: codeChallengeMethod,
  431. }
  432. if err := db.Insert(ctx, code); err != nil {
  433. return nil, err
  434. }
  435. return code, nil
  436. }
  437. // IncreaseCounter increases the counter and updates the grant
  438. func (grant *OAuth2Grant) IncreaseCounter(ctx context.Context) error {
  439. _, err := db.GetEngine(ctx).ID(grant.ID).Incr("counter").Update(new(OAuth2Grant))
  440. if err != nil {
  441. return err
  442. }
  443. updatedGrant, err := GetOAuth2GrantByID(ctx, grant.ID)
  444. if err != nil {
  445. return err
  446. }
  447. grant.Counter = updatedGrant.Counter
  448. return nil
  449. }
  450. // ScopeContains returns true if the grant scope contains the specified scope
  451. func (grant *OAuth2Grant) ScopeContains(scope string) bool {
  452. for _, currentScope := range strings.Split(grant.Scope, " ") {
  453. if scope == currentScope {
  454. return true
  455. }
  456. }
  457. return false
  458. }
  459. // SetNonce updates the current nonce value of a grant
  460. func (grant *OAuth2Grant) SetNonce(ctx context.Context, nonce string) error {
  461. grant.Nonce = nonce
  462. _, err := db.GetEngine(ctx).ID(grant.ID).Cols("nonce").Update(grant)
  463. if err != nil {
  464. return err
  465. }
  466. return nil
  467. }
  468. // GetOAuth2GrantByID returns the grant with the given ID
  469. func GetOAuth2GrantByID(ctx context.Context, id int64) (grant *OAuth2Grant, err error) {
  470. grant = new(OAuth2Grant)
  471. if has, err := db.GetEngine(ctx).ID(id).Get(grant); err != nil {
  472. return nil, err
  473. } else if !has {
  474. return nil, nil
  475. }
  476. return grant, err
  477. }
  478. // GetOAuth2GrantsByUserID lists all grants of a certain user
  479. func GetOAuth2GrantsByUserID(ctx context.Context, uid int64) ([]*OAuth2Grant, error) {
  480. type joinedOAuth2Grant struct {
  481. Grant *OAuth2Grant `xorm:"extends"`
  482. Application *OAuth2Application `xorm:"extends"`
  483. }
  484. var results *xorm.Rows
  485. var err error
  486. if results, err = db.GetEngine(ctx).
  487. Table("oauth2_grant").
  488. Where("user_id = ?", uid).
  489. Join("INNER", "oauth2_application", "application_id = oauth2_application.id").
  490. Rows(new(joinedOAuth2Grant)); err != nil {
  491. return nil, err
  492. }
  493. defer results.Close()
  494. grants := make([]*OAuth2Grant, 0)
  495. for results.Next() {
  496. joinedGrant := new(joinedOAuth2Grant)
  497. if err := results.Scan(joinedGrant); err != nil {
  498. return nil, err
  499. }
  500. joinedGrant.Grant.Application = joinedGrant.Application
  501. grants = append(grants, joinedGrant.Grant)
  502. }
  503. return grants, nil
  504. }
  505. // RevokeOAuth2Grant deletes the grant with grantID and userID
  506. func RevokeOAuth2Grant(ctx context.Context, grantID, userID int64) error {
  507. _, err := db.GetEngine(ctx).Where(builder.Eq{"id": grantID, "user_id": userID}).Delete(&OAuth2Grant{})
  508. return err
  509. }
  510. // ErrOAuthClientIDInvalid will be thrown if client id cannot be found
  511. type ErrOAuthClientIDInvalid struct {
  512. ClientID string
  513. }
  514. // IsErrOauthClientIDInvalid checks if an error is a ErrOAuthClientIDInvalid.
  515. func IsErrOauthClientIDInvalid(err error) bool {
  516. _, ok := err.(ErrOAuthClientIDInvalid)
  517. return ok
  518. }
  519. // Error returns the error message
  520. func (err ErrOAuthClientIDInvalid) Error() string {
  521. return fmt.Sprintf("Client ID invalid [Client ID: %s]", err.ClientID)
  522. }
  523. // Unwrap unwraps this as a ErrNotExist err
  524. func (err ErrOAuthClientIDInvalid) Unwrap() error {
  525. return util.ErrNotExist
  526. }
  527. // ErrOAuthApplicationNotFound will be thrown if id cannot be found
  528. type ErrOAuthApplicationNotFound struct {
  529. ID int64
  530. }
  531. // IsErrOAuthApplicationNotFound checks if an error is a ErrReviewNotExist.
  532. func IsErrOAuthApplicationNotFound(err error) bool {
  533. _, ok := err.(ErrOAuthApplicationNotFound)
  534. return ok
  535. }
  536. // Error returns the error message
  537. func (err ErrOAuthApplicationNotFound) Error() string {
  538. return fmt.Sprintf("OAuth application not found [ID: %d]", err.ID)
  539. }
  540. // Unwrap unwraps this as a ErrNotExist err
  541. func (err ErrOAuthApplicationNotFound) Unwrap() error {
  542. return util.ErrNotExist
  543. }
  544. // GetActiveOAuth2SourceByName returns a OAuth2 AuthSource based on the given name
  545. func GetActiveOAuth2SourceByName(ctx context.Context, name string) (*Source, error) {
  546. authSource := new(Source)
  547. has, err := db.GetEngine(ctx).Where("name = ? and type = ? and is_active = ?", name, OAuth2, true).Get(authSource)
  548. if err != nil {
  549. return nil, err
  550. }
  551. if !has {
  552. return nil, fmt.Errorf("oauth2 source not found, name: %q", name)
  553. }
  554. return authSource, nil
  555. }
  556. func DeleteOAuth2RelictsByUserID(ctx context.Context, userID int64) error {
  557. deleteCond := builder.Select("id").From("oauth2_grant").Where(builder.Eq{"oauth2_grant.user_id": userID})
  558. if _, err := db.GetEngine(ctx).In("grant_id", deleteCond).
  559. Delete(&OAuth2AuthorizationCode{}); err != nil {
  560. return err
  561. }
  562. if err := db.DeleteBeans(ctx,
  563. &OAuth2Application{UID: userID},
  564. &OAuth2Grant{UserID: userID},
  565. ); err != nil {
  566. return fmt.Errorf("DeleteBeans: %w", err)
  567. }
  568. return nil
  569. }