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 21KB

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