Skip to content

Commit 46855d9

Browse files
committed
feat: add more repository integration test
1 parent c5ae68f commit 46855d9

File tree

10 files changed

+404
-194
lines changed

10 files changed

+404
-194
lines changed

api/custom_response.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"errors"
66
"net/http"
77

8+
"github.com/jiaozifs/jiaozifs/auth"
9+
810
"github.com/jiaozifs/jiaozifs/models"
911
)
1012

@@ -60,6 +62,10 @@ func (response *JiaozifsResponse) Error(err error) {
6062
response.NotFound()
6163
return
6264
}
65+
if errors.Is(err, auth.ErrUserNotFound) {
66+
response.WriteHeader(http.StatusUnauthorized)
67+
return
68+
}
6369

6470
response.WriteHeader(http.StatusInternalServerError)
6571
_, _ = response.Write([]byte(err.Error()))

api/custom_response_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"net/http"
66
"testing"
77

8+
"github.com/jiaozifs/jiaozifs/auth"
9+
810
"github.com/jiaozifs/jiaozifs/models"
911

1012
"go.uber.org/mock/gomock"
@@ -20,6 +22,15 @@ func TestJiaozifsResponse(t *testing.T) {
2022
jzResp.NotFound()
2123
})
2224

25+
t.Run("forbidden", func(t *testing.T) {
26+
ctrl := gomock.NewController(t)
27+
resp := NewMockResponseWriter(ctrl)
28+
jzResp := JiaozifsResponse{resp}
29+
30+
resp.EXPECT().WriteHeader(http.StatusForbidden)
31+
jzResp.Forbidden()
32+
})
33+
2334
t.Run("not found", func(t *testing.T) {
2435
ctrl := gomock.NewController(t)
2536
resp := NewMockResponseWriter(ctrl)
@@ -75,6 +86,15 @@ func TestJiaozifsResponse(t *testing.T) {
7586
jzResp.Error(fmt.Errorf("mock %w", models.ErrNotFound))
7687
})
7788

89+
t.Run("error no auth", func(t *testing.T) {
90+
ctrl := gomock.NewController(t)
91+
resp := NewMockResponseWriter(ctrl)
92+
jzResp := JiaozifsResponse{resp}
93+
94+
resp.EXPECT().WriteHeader(http.StatusUnauthorized)
95+
jzResp.Error(fmt.Errorf("mock %w", auth.ErrUserNotFound))
96+
})
97+
7898
t.Run("string", func(t *testing.T) {
7999
ctrl := gomock.NewController(t)
80100
resp := NewMockResponseWriter(ctrl)

auth/auth_test.go

Lines changed: 0 additions & 45 deletions
This file was deleted.

auth/basic_auth.go

Lines changed: 0 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,52 +5,13 @@ import (
55
"fmt"
66
"time"
77

8-
"github.com/jiaozifs/jiaozifs/config"
9-
10-
"github.com/go-openapi/swag"
118
logging "github.com/ipfs/go-log/v2"
12-
"github.com/jiaozifs/jiaozifs/api"
139
"github.com/jiaozifs/jiaozifs/models"
1410
"golang.org/x/crypto/bcrypt"
1511
)
1612

1713
var log = logging.Logger("auth")
1814

19-
type Login struct {
20-
Username string `json:"username"`
21-
Password string `json:"password"`
22-
}
23-
24-
func (l *Login) Login(ctx context.Context, repo models.IUserRepo, config *config.AuthConfig) (token api.AuthenticationToken, err error) {
25-
// get user encryptedPassword by username
26-
ep, err := repo.GetEPByName(ctx, l.Username)
27-
if err != nil {
28-
return token, fmt.Errorf("cannt get user %s encrypt password %w", l.Username, err)
29-
}
30-
31-
// Compare ep and password
32-
err = bcrypt.CompareHashAndPassword([]byte(ep), []byte(l.Password))
33-
if err != nil {
34-
log.Errorf("password err: %s", err)
35-
return token, fmt.Errorf("user %s password not match %w", l.Username, err)
36-
}
37-
// Generate user token
38-
loginTime := time.Now()
39-
expires := loginTime.Add(expirationDuration)
40-
secretKey := config.SecretKey
41-
42-
tokenString, err := GenerateJWTLogin(secretKey, l.Username, loginTime, expires)
43-
if err != nil {
44-
return token, fmt.Errorf("generate token err: %w", err)
45-
}
46-
47-
log.Infof("usert %s login successful", l.Username)
48-
49-
token.Token = tokenString
50-
token.TokenExpiration = swag.Int64(expires.Unix())
51-
return token, nil
52-
}
53-
5415
type Register struct {
5516
Username string `json:"username"`
5617
Email string `json:"email"`

auth/context.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
"github.com/jiaozifs/jiaozifs/models"
88
)
99

10+
var ErrUserNotFound = fmt.Errorf("UserNotFound")
11+
1012
type contextKey string
1113

1214
const (
@@ -16,7 +18,7 @@ const (
1618
func GetOperator(ctx context.Context) (*models.User, error) {
1719
user, ok := ctx.Value(userContextKey).(*models.User)
1820
if !ok {
19-
return nil, fmt.Errorf("UserNotFound")
21+
return nil, ErrUserNotFound
2022
}
2123
return user, nil
2224
}

auth/types.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@ package auth
33
import "time"
44

55
const (
6-
expirationDuration = time.Hour
6+
ExpirationDuration = time.Hour
77
passwordCost = 12
88
)

controller/repository_ctl.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ const DefaultBranchName = "main"
2929
var maxNameLength = 20
3030
var alphanumeric = regexp.MustCompile("^[a-zA-Z0-9_]*$")
3131

32-
var RepoNameBlackList = []string{"repository", "repo", "user", "users"}
32+
// RepoNameBlackList forbid repo name, reserve for routes
33+
var RepoNameBlackList = []string{"repository", "repositories", "wip", "wips", "object", "objects", "commit", "commits", "ref", "refs", "repo", "repos", "user", "users"}
3334

3435
func CheckRepositoryName(name string) error {
3536
for _, blackName := range RepoNameBlackList {
@@ -162,7 +163,13 @@ func (repositoryCtl RepositoryController) DeleteRepository(ctx context.Context,
162163
return
163164
}
164165

165-
if operator.Name != ownerName {
166+
owner, err := repositoryCtl.Repo.UserRepo().Get(ctx, models.NewGetUserParams().SetName(ownerName))
167+
if err != nil {
168+
w.Error(err)
169+
return
170+
}
171+
172+
if operator.Name != owner.Name {
166173
w.Forbidden()
167174
return
168175
}
@@ -273,6 +280,11 @@ func (repositoryCtl RepositoryController) GetCommitsInRepository(ctx context.Con
273280
return
274281
}
275282

283+
if ref.CommitHash.IsEmpty() {
284+
w.JSON([]api.Commit{})
285+
return
286+
}
287+
276288
commit, err := repositoryCtl.Repo.CommitRepo().Commit(ctx, ref.CommitHash)
277289
if err != nil {
278290
w.Error(err)

controller/user_ctl.go

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ package controller
33
import (
44
"context"
55
"net/http"
6+
"time"
7+
8+
"github.com/go-openapi/swag"
9+
"golang.org/x/crypto/bcrypt"
610

711
openapitypes "github.com/oapi-codegen/runtime/types"
812

@@ -33,27 +37,45 @@ type UserController struct {
3337
}
3438

3539
func (userCtl UserController) Login(ctx context.Context, w *api.JiaozifsResponse, r *http.Request, body api.LoginJSONRequestBody) {
36-
login := auth.Login{
37-
Username: body.Username,
38-
Password: body.Password,
40+
41+
// get user encryptedPassword by username
42+
ep, err := userCtl.Repo.UserRepo().GetEPByName(ctx, body.Username)
43+
if err != nil {
44+
w.Code(http.StatusUnauthorized)
45+
return
3946
}
4047

41-
// perform login
42-
authToken, err := login.Login(ctx, userCtl.Repo.UserRepo(), userCtl.Config)
48+
// Compare ep and password
49+
err = bcrypt.CompareHashAndPassword([]byte(ep), []byte(body.Password))
50+
if err != nil {
51+
w.Code(http.StatusUnauthorized)
52+
return
53+
}
54+
// Generate user token
55+
loginTime := time.Now()
56+
expires := loginTime.Add(auth.ExpirationDuration)
57+
secretKey := userCtl.Config.SecretKey
58+
59+
tokenString, err := auth.GenerateJWTLogin(secretKey, body.Username, loginTime, expires)
4360
if err != nil {
4461
w.Error(err)
4562
return
4663
}
4764

65+
userCtlLog.Infof("usert %s login successful", body.Username)
66+
4867
internalAuthSession, _ := userCtl.SessionStore.Get(r, auth.InternalAuthSessionName)
49-
internalAuthSession.Values[auth.TokenSessionKeyName] = authToken.Token
68+
internalAuthSession.Values[auth.TokenSessionKeyName] = tokenString
5069
err = userCtl.SessionStore.Save(r, w, internalAuthSession)
5170
if err != nil {
5271
userCtlLog.Errorf("Failed to save internal auth session %v", err)
5372
w.Code(http.StatusInternalServerError)
5473
return
5574
}
56-
w.JSON(authToken)
75+
w.JSON(api.AuthenticationToken{
76+
Token: tokenString,
77+
TokenExpiration: swag.Int64(expires.Unix()),
78+
})
5779
}
5880

5981
func (userCtl UserController) Register(ctx context.Context, w *api.JiaozifsResponse, _ *http.Request, body api.RegisterJSONRequestBody) {

0 commit comments

Comments
 (0)