From af61b2249ab9d0afb7424509112d06c578dca059 Mon Sep 17 00:00:00 2001
From: Gustavo Marin <gustavo.marin@intelygenz.com>
Date: Sat, 29 Feb 2020 07:19:32 +0100
Subject: [PATCH] adds API endpoints to manage OAuth2 Application
 (list/create/delete) (#10437)

* add API endpoint to create OAuth2 Application.

* move endpoint to /user. Add swagger documentations and proper response type.

* change json tags to snake_case. add CreateOAuth2ApplicationOptions to swagger docs.

* change response status to Created (201)

* add methods to list OAuth2 apps and delete an existing OAuth2 app by ID.

* add APIFormat convert method and file header

* fixed header

* hide secret on oauth2 application list

* add Created time to API response

* add API integration tests for create/list/delete OAuth2 applications.

Co-authored-by: techknowlogick <matti@mdranta.net>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
---
 integrations/api_oauth2_apps_test.go |  96 +++++++++++++++++
 models/oauth2_application.go         |  17 +++
 modules/convert/convert.go           |  12 +++
 modules/structs/user_app.go          |  22 ++++
 routers/api/v1/api.go                |   6 ++
 routers/api/v1/swagger/app.go        |  16 +++
 routers/api/v1/swagger/options.go    |   3 +
 routers/api/v1/user/app.go           |  96 +++++++++++++++++
 templates/swagger/v1_json.tmpl       | 154 ++++++++++++++++++++++++++-
 9 files changed, 421 insertions(+), 1 deletion(-)
 create mode 100644 integrations/api_oauth2_apps_test.go
 create mode 100644 routers/api/v1/swagger/app.go

diff --git a/integrations/api_oauth2_apps_test.go b/integrations/api_oauth2_apps_test.go
new file mode 100644
index 0000000000..fe79582308
--- /dev/null
+++ b/integrations/api_oauth2_apps_test.go
@@ -0,0 +1,96 @@
+// Copyright 2020 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.package models
+
+package integrations
+
+import (
+	"fmt"
+	"net/http"
+	"testing"
+
+	"code.gitea.io/gitea/models"
+	api "code.gitea.io/gitea/modules/structs"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestOAuth2Application(t *testing.T) {
+	defer prepareTestEnv(t)()
+	testAPICreateOAuth2Application(t)
+	testAPIListOAuth2Applications(t)
+	testAPIDeleteOAuth2Application(t)
+}
+
+func testAPICreateOAuth2Application(t *testing.T) {
+	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	appBody := api.CreateOAuth2ApplicationOptions{
+		Name: "test-app-1",
+		RedirectURIs: []string{
+			"http://www.google.com",
+		},
+	}
+
+	req := NewRequestWithJSON(t, "POST", "/api/v1/user/applications/oauth2", &appBody)
+	req = AddBasicAuthHeader(req, user.Name)
+	resp := MakeRequest(t, req, http.StatusCreated)
+
+	var createdApp *api.OAuth2Application
+	DecodeJSON(t, resp, &createdApp)
+
+	assert.EqualValues(t, appBody.Name, createdApp.Name)
+	assert.Len(t, createdApp.ClientSecret, 44)
+	assert.Len(t, createdApp.ClientID, 36)
+	assert.NotEmpty(t, createdApp.Created)
+	assert.EqualValues(t, appBody.RedirectURIs[0], createdApp.RedirectURIs[0])
+	models.AssertExistsAndLoadBean(t, &models.OAuth2Application{UID: user.ID, Name: createdApp.Name})
+}
+
+func testAPIListOAuth2Applications(t *testing.T) {
+	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	session := loginUser(t, user.Name)
+	token := getTokenForLoggedInUser(t, session)
+
+	existApp := models.AssertExistsAndLoadBean(t, &models.OAuth2Application{
+		UID:  user.ID,
+		Name: "test-app-1",
+		RedirectURIs: []string{
+			"http://www.google.com",
+		},
+	}).(*models.OAuth2Application)
+
+	urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2?token=%s", token)
+	req := NewRequest(t, "GET", urlStr)
+	resp := session.MakeRequest(t, req, http.StatusOK)
+
+	var appList api.OAuth2ApplicationList
+	DecodeJSON(t, resp, &appList)
+	expectedApp := appList[0]
+
+	assert.EqualValues(t, existApp.Name, expectedApp.Name)
+	assert.EqualValues(t, existApp.ClientID, expectedApp.ClientID)
+	assert.Len(t, expectedApp.ClientID, 36)
+	assert.Empty(t, expectedApp.ClientSecret)
+	assert.EqualValues(t, existApp.RedirectURIs[0], expectedApp.RedirectURIs[0])
+	models.AssertExistsAndLoadBean(t, &models.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name})
+}
+
+func testAPIDeleteOAuth2Application(t *testing.T) {
+	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	session := loginUser(t, user.Name)
+	token := getTokenForLoggedInUser(t, session)
+
+	oldApp := models.AssertExistsAndLoadBean(t, &models.OAuth2Application{
+		UID:  user.ID,
+		Name: "test-app-1",
+		RedirectURIs: []string{
+			"http://www.google.com",
+		},
+	}).(*models.OAuth2Application)
+
+	urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2/%d?token=%s", oldApp.ID, token)
+	req := NewRequest(t, "DELETE", urlStr)
+	session.MakeRequest(t, req, http.StatusNoContent)
+
+	models.AssertNotExistsBean(t, &models.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name})
+}
diff --git a/models/oauth2_application.go b/models/oauth2_application.go
index 4df207ae16..f888cf61b8 100644
--- a/models/oauth2_application.go
+++ b/models/oauth2_application.go
@@ -252,6 +252,23 @@ func DeleteOAuth2Application(id, userid int64) error {
 	return sess.Commit()
 }
 
+// ListOAuth2Applications returns a list of oauth2 applications belongs to given user.
+func ListOAuth2Applications(uid int64, listOptions ListOptions) ([]*OAuth2Application, error) {
+	sess := x.
+		Where("uid=?", uid).
+		Desc("id")
+
+	if listOptions.Page != 0 {
+		sess = listOptions.setSessionPagination(sess)
+
+		apps := make([]*OAuth2Application, 0, listOptions.PageSize)
+		return apps, sess.Find(&apps)
+	}
+
+	apps := make([]*OAuth2Application, 0, 5)
+	return apps, sess.Find(&apps)
+}
+
 //////////////////////////////////////////////////////
 
 // OAuth2AuthorizationCode is a code to obtain an access token in combination with the client secret once. It has a limited lifetime.
diff --git a/modules/convert/convert.go b/modules/convert/convert.go
index 31b46bc7eb..cab2f84bb9 100644
--- a/modules/convert/convert.go
+++ b/modules/convert/convert.go
@@ -388,3 +388,15 @@ func ToTopicResponse(topic *models.Topic) *api.TopicResponse {
 		Updated:   topic.UpdatedUnix.AsTime(),
 	}
 }
+
+// ToOAuth2Application convert from models.OAuth2Application to api.OAuth2Application
+func ToOAuth2Application(app *models.OAuth2Application) *api.OAuth2Application {
+	return &api.OAuth2Application{
+		ID:           app.ID,
+		Name:         app.Name,
+		ClientID:     app.ClientID,
+		ClientSecret: app.ClientSecret,
+		RedirectURIs: app.RedirectURIs,
+		Created:      app.CreatedUnix.AsTime(),
+	}
+}
diff --git a/modules/structs/user_app.go b/modules/structs/user_app.go
index 9340486685..a0b0c3cb70 100644
--- a/modules/structs/user_app.go
+++ b/modules/structs/user_app.go
@@ -7,6 +7,7 @@ package structs
 
 import (
 	"encoding/base64"
+	"time"
 )
 
 // BasicAuthEncode generate base64 of basic auth head
@@ -32,3 +33,24 @@ type AccessTokenList []*AccessToken
 type CreateAccessTokenOption struct {
 	Name string `json:"name" binding:"Required"`
 }
+
+// CreateOAuth2ApplicationOptions holds options to create an oauth2 application
+type CreateOAuth2ApplicationOptions struct {
+	Name         string   `json:"name" binding:"Required"`
+	RedirectURIs []string `json:"redirect_uris" binding:"Required"`
+}
+
+// OAuth2Application represents an OAuth2 application.
+// swagger:response OAuth2Application
+type OAuth2Application struct {
+	ID           int64     `json:"id"`
+	Name         string    `json:"name"`
+	ClientID     string    `json:"client_id"`
+	ClientSecret string    `json:"client_secret"`
+	RedirectURIs []string  `json:"redirect_uris"`
+	Created      time.Time `json:"created"`
+}
+
+// OAuth2ApplicationList represents a list of OAuth2 applications.
+// swagger:response OAuth2ApplicationList
+type OAuth2ApplicationList []*OAuth2Application
diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go
index 0ddf57b743..eee9440574 100644
--- a/routers/api/v1/api.go
+++ b/routers/api/v1/api.go
@@ -576,6 +576,12 @@ func RegisterRoutes(m *macaron.Macaron) {
 				m.Combo("/:id").Get(user.GetPublicKey).
 					Delete(user.DeletePublicKey)
 			})
+			m.Group("/applications", func() {
+				m.Combo("/oauth2").
+					Get(user.ListOauth2Applications).
+					Post(bind(api.CreateOAuth2ApplicationOptions{}), user.CreateOauth2Application)
+				m.Delete("/oauth2/:id", user.DeleteOauth2Application)
+			}, reqToken())
 
 			m.Group("/gpg_keys", func() {
 				m.Combo("").Get(user.ListMyGPGKeys).
diff --git a/routers/api/v1/swagger/app.go b/routers/api/v1/swagger/app.go
new file mode 100644
index 0000000000..8be2c85574
--- /dev/null
+++ b/routers/api/v1/swagger/app.go
@@ -0,0 +1,16 @@
+// Copyright 2020 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package swagger
+
+import (
+	api "code.gitea.io/gitea/modules/structs"
+)
+
+// OAuth2Application
+// swagger:response OAuth2Application
+type swaggerResponseOAuth2Application struct {
+	// in:body
+	Body api.OAuth2Application `json:"body"`
+}
diff --git a/routers/api/v1/swagger/options.go b/routers/api/v1/swagger/options.go
index 679b4aa708..4bb649616a 100644
--- a/routers/api/v1/swagger/options.go
+++ b/routers/api/v1/swagger/options.go
@@ -134,4 +134,7 @@ type swaggerParameterBodies struct {
 
 	// in:body
 	EditBranchProtectionOption api.EditBranchProtectionOption
+
+	// in:body
+	CreateOAuth2ApplicationOptions api.CreateOAuth2ApplicationOptions
 }
diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go
index a65bdc51c1..7e0e620fea 100644
--- a/routers/api/v1/user/app.go
+++ b/routers/api/v1/user/app.go
@@ -10,6 +10,7 @@ import (
 
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/modules/context"
+	"code.gitea.io/gitea/modules/convert"
 	api "code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/routers/api/v1/utils"
 )
@@ -135,3 +136,98 @@ func DeleteAccessToken(ctx *context.APIContext) {
 
 	ctx.Status(http.StatusNoContent)
 }
+
+// CreateOauth2Application is the handler to create a new OAuth2 Application for the authenticated user
+func CreateOauth2Application(ctx *context.APIContext, data api.CreateOAuth2ApplicationOptions) {
+	// swagger:operation POST /user/applications/oauth2 user userCreateOAuth2Application
+	// ---
+	// summary: creates a new OAuth2 application
+	// produces:
+	// - application/json
+	// parameters:
+	// - name: body
+	//   in: body
+	//   required: true
+	//   schema:
+	//     "$ref": "#/definitions/CreateOAuth2ApplicationOptions"
+	// responses:
+	//   "201":
+	//     "$ref": "#/responses/OAuth2Application"
+	app, err := models.CreateOAuth2Application(models.CreateOAuth2ApplicationOptions{
+		Name:         data.Name,
+		UserID:       ctx.User.ID,
+		RedirectURIs: data.RedirectURIs,
+	})
+	if err != nil {
+		ctx.Error(http.StatusBadRequest, "", "error creating oauth2 application")
+		return
+	}
+	secret, err := app.GenerateClientSecret()
+	if err != nil {
+		ctx.Error(http.StatusBadRequest, "", "error creating application secret")
+		return
+	}
+	app.ClientSecret = secret
+
+	ctx.JSON(http.StatusCreated, convert.ToOAuth2Application(app))
+}
+
+// ListOauth2Applications list all the Oauth2 application
+func ListOauth2Applications(ctx *context.APIContext) {
+	// swagger:operation GET /user/applications/oauth2 user userGetOauth2Application
+	// ---
+	// summary: List the authenticated user's oauth2 applications
+	// produces:
+	// - application/json
+	// parameters:
+	// - name: page
+	//   in: query
+	//   description: page number of results to return (1-based)
+	//   type: integer
+	// - name: limit
+	//   in: query
+	//   description: page size of results, maximum page size is 50
+	//   type: integer
+	// responses:
+	//   "200":
+	//     "$ref": "#/responses/OAuth2ApplicationList"
+
+	apps, err := models.ListOAuth2Applications(ctx.User.ID, utils.GetListOptions(ctx))
+	if err != nil {
+		ctx.Error(http.StatusInternalServerError, "ListOAuth2Applications", err)
+		return
+	}
+
+	apiApps := make([]*api.OAuth2Application, len(apps))
+	for i := range apps {
+		apiApps[i] = convert.ToOAuth2Application(apps[i])
+		apiApps[i].ClientSecret = "" // Hide secret on application list
+	}
+	ctx.JSON(http.StatusOK, &apiApps)
+}
+
+// DeleteOauth2Application delete OAuth2 Application
+func DeleteOauth2Application(ctx *context.APIContext) {
+	// swagger:operation DELETE /user/applications/oauth2/{id} user userDeleteOAuth2Application
+	// ---
+	// summary: delete an OAuth2 Application
+	// produces:
+	// - application/json
+	// parameters:
+	// - name: id
+	//   in: path
+	//   description: token to be deleted
+	//   type: integer
+	//   format: int64
+	//   required: true
+	// responses:
+	//   "204":
+	//     "$ref": "#/responses/empty"
+	appID := ctx.ParamsInt64(":id")
+	if err := models.DeleteOAuth2Application(appID, ctx.User.ID); err != nil {
+		ctx.Error(http.StatusInternalServerError, "DeleteOauth2ApplicationByID", err)
+		return
+	}
+
+	ctx.Status(http.StatusNoContent)
+}
diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl
index bac1f05710..07d760212e 100644
--- a/templates/swagger/v1_json.tmpl
+++ b/templates/swagger/v1_json.tmpl
@@ -8071,6 +8071,89 @@
         }
       }
     },
+    "/user/applications/oauth2": {
+      "get": {
+        "produces": [
+          "application/json"
+        ],
+        "tags": [
+          "user"
+        ],
+        "summary": "List the authenticated user's oauth2 applications",
+        "operationId": "userGetOauth2Application",
+        "parameters": [
+          {
+            "type": "integer",
+            "description": "page number of results to return (1-based)",
+            "name": "page",
+            "in": "query"
+          },
+          {
+            "type": "integer",
+            "description": "page size of results, maximum page size is 50",
+            "name": "limit",
+            "in": "query"
+          }
+        ],
+        "responses": {
+          "200": {
+            "$ref": "#/responses/OAuth2ApplicationList"
+          }
+        }
+      },
+      "post": {
+        "produces": [
+          "application/json"
+        ],
+        "tags": [
+          "user"
+        ],
+        "summary": "creates a new OAuth2 application",
+        "operationId": "userCreateOAuth2Application",
+        "parameters": [
+          {
+            "name": "body",
+            "in": "body",
+            "required": true,
+            "schema": {
+              "$ref": "#/definitions/CreateOAuth2ApplicationOptions"
+            }
+          }
+        ],
+        "responses": {
+          "201": {
+            "$ref": "#/responses/OAuth2Application"
+          }
+        }
+      }
+    },
+    "/user/applications/oauth2/{id}": {
+      "delete": {
+        "produces": [
+          "application/json"
+        ],
+        "tags": [
+          "user"
+        ],
+        "summary": "delete an OAuth2 Application",
+        "operationId": "userDeleteOAuth2Application",
+        "parameters": [
+          {
+            "type": "integer",
+            "format": "int64",
+            "description": "token to be deleted",
+            "name": "id",
+            "in": "path",
+            "required": true
+          }
+        ],
+        "responses": {
+          "204": {
+            "$ref": "#/responses/empty"
+          }
+        }
+      }
+    },
     "/user/emails": {
       "get": {
         "produces": [
@@ -10357,6 +10440,24 @@
       },
       "x-go-package": "code.gitea.io/gitea/modules/structs"
     },
+    "CreateOAuth2ApplicationOptions": {
+      "description": "CreateOAuth2ApplicationOptions holds options to create an oauth2 application",
+      "type": "object",
+      "properties": {
+        "name": {
+          "type": "string",
+          "x-go-name": "Name"
+        },
+        "redirect_uris": {
+          "type": "array",
+          "items": {
+            "type": "string"
+          },
+          "x-go-name": "RedirectURIs"
+        }
+      },
+      "x-go-package": "code.gitea.io/gitea/modules/structs"
+    },
     "CreateOrgOption": {
       "description": "CreateOrgOption options for creating an organization",
       "type": "object",
@@ -12198,6 +12299,42 @@
       },
       "x-go-package": "code.gitea.io/gitea/modules/structs"
     },
+    "OAuth2Application": {
+      "type": "object",
+      "title": "OAuth2Application represents an OAuth2 application.",
+      "properties": {
+        "client_id": {
+          "type": "string",
+          "x-go-name": "ClientID"
+        },
+        "client_secret": {
+          "type": "string",
+          "x-go-name": "ClientSecret"
+        },
+        "created": {
+          "type": "string",
+          "format": "date-time",
+          "x-go-name": "Created"
+        },
+        "id": {
+          "type": "integer",
+          "format": "int64",
+          "x-go-name": "ID"
+        },
+        "name": {
+          "type": "string",
+          "x-go-name": "Name"
+        },
+        "redirect_uris": {
+          "type": "array",
+          "items": {
+            "type": "string"
+          },
+          "x-go-name": "RedirectURIs"
+        }
+      },
+      "x-go-package": "code.gitea.io/gitea/modules/structs"
+    },
     "Organization": {
       "description": "Organization represents an organization",
       "type": "object",
@@ -13689,6 +13826,21 @@
         }
       }
     },
+    "OAuth2Application": {
+      "description": "OAuth2Application",
+      "schema": {
+        "$ref": "#/definitions/OAuth2Application"
+      }
+    },
+    "OAuth2ApplicationList": {
+      "description": "OAuth2ApplicationList represents a list of OAuth2 applications.",
+      "schema": {
+        "type": "array",
+        "items": {
+          "$ref": "#/definitions/OAuth2Application"
+        }
+      }
+    },
     "Organization": {
       "description": "Organization",
       "schema": {
@@ -13971,7 +14123,7 @@
     "parameterBodies": {
       "description": "parameterBodies",
       "schema": {
-        "$ref": "#/definitions/EditBranchProtectionOption"
+        "$ref": "#/definitions/CreateOAuth2ApplicationOptions"
       }
     },
     "redirect": {