Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add API endpoints to manage OAuth2 Application (list/create/delete) #10437

Merged
merged 15 commits into from
Feb 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions integrations/api_oauth2_apps_test.go
Original file line number Diff line number Diff line change
@@ -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) {
This conversation was marked as resolved.
Show resolved Hide resolved
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:https://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:https://www.google.com",
},
}).(*models.OAuth2Application)

This conversation was marked as resolved.
Show resolved Hide resolved
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:https://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})
}
17 changes: 17 additions & 0 deletions models/oauth2_application.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions modules/convert/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
}
22 changes: 22 additions & 0 deletions modules/structs/user_app.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package structs

import (
"encoding/base64"
"time"
)

// BasicAuthEncode generate base64 of basic auth head
Expand All @@ -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
6 changes: 6 additions & 0 deletions routers/api/v1/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
16 changes: 16 additions & 0 deletions routers/api/v1/swagger/app.go
Original file line number Diff line number Diff line change
@@ -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
This conversation was marked as resolved.
Show resolved Hide resolved

import (
api "code.gitea.io/gitea/modules/structs"
)

// OAuth2Application
// swagger:response OAuth2Application
type swaggerResponseOAuth2Application struct {
// in:body
Body api.OAuth2Application `json:"body"`
}
3 changes: 3 additions & 0 deletions routers/api/v1/swagger/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,7 @@ type swaggerParameterBodies struct {

// in:body
EditBranchProtectionOption api.EditBranchProtectionOption

// in:body
CreateOAuth2ApplicationOptions api.CreateOAuth2ApplicationOptions
}
96 changes: 96 additions & 0 deletions routers/api/v1/user/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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))
This conversation was marked as resolved.
Show resolved Hide resolved
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)
}
Loading